作者: 韩晨旭 10225101440 李畅 10225102463
Ви не можете вибрати більше 25 тем Теми мають розпочинатися з літери або цифри, можуть містити дефіси (-) і не повинні перевищувати 35 символів.

384 рядки
9.2 KiB

  1. // Copyright (c) 2011 The LevelDB Authors. All rights reserved.
  2. // Use of this source code is governed by a BSD-style license that can be
  3. // found in the LICENSE file. See the AUTHORS file for names of contributors.
  4. #include "helpers/memenv/memenv.h"
  5. #include "leveldb/env.h"
  6. #include "leveldb/status.h"
  7. #include "port/port.h"
  8. #include "util/mutexlock.h"
  9. #include <map>
  10. #include <string.h>
  11. #include <string>
  12. #include <vector>
  13. namespace leveldb {
  14. namespace {
  15. class FileState {
  16. public:
  17. // FileStates are reference counted. The initial reference count is zero
  18. // and the caller must call Ref() at least once.
  19. FileState() : refs_(0), size_(0) {}
  20. // Increase the reference count.
  21. void Ref() {
  22. MutexLock lock(&refs_mutex_);
  23. ++refs_;
  24. }
  25. // Decrease the reference count. Delete if this is the last reference.
  26. void Unref() {
  27. bool do_delete = false;
  28. {
  29. MutexLock lock(&refs_mutex_);
  30. --refs_;
  31. assert(refs_ >= 0);
  32. if (refs_ <= 0) {
  33. do_delete = true;
  34. }
  35. }
  36. if (do_delete) {
  37. delete this;
  38. }
  39. }
  40. uint64_t Size() const { return size_; }
  41. Status Read(uint64_t offset, size_t n, Slice* result, char* scratch) const {
  42. if (offset > size_) {
  43. return Status::IOError("Offset greater than file size.");
  44. }
  45. const uint64_t available = size_ - offset;
  46. if (n > available) {
  47. n = available;
  48. }
  49. if (n == 0) {
  50. *result = Slice();
  51. return Status::OK();
  52. }
  53. size_t block = offset / kBlockSize;
  54. size_t block_offset = offset % kBlockSize;
  55. if (n <= kBlockSize - block_offset) {
  56. // The requested bytes are all in the first block.
  57. *result = Slice(blocks_[block] + block_offset, n);
  58. return Status::OK();
  59. }
  60. size_t bytes_to_copy = n;
  61. char* dst = scratch;
  62. while (bytes_to_copy > 0) {
  63. size_t avail = kBlockSize - block_offset;
  64. if (avail > bytes_to_copy) {
  65. avail = bytes_to_copy;
  66. }
  67. memcpy(dst, blocks_[block] + block_offset, avail);
  68. bytes_to_copy -= avail;
  69. dst += avail;
  70. block++;
  71. block_offset = 0;
  72. }
  73. *result = Slice(scratch, n);
  74. return Status::OK();
  75. }
  76. Status Append(const Slice& data) {
  77. const char* src = data.data();
  78. size_t src_len = data.size();
  79. while (src_len > 0) {
  80. size_t avail;
  81. size_t offset = size_ % kBlockSize;
  82. if (offset != 0) {
  83. // There is some room in the last block.
  84. avail = kBlockSize - offset;
  85. } else {
  86. // No room in the last block; push new one.
  87. blocks_.push_back(new char[kBlockSize]);
  88. avail = kBlockSize;
  89. }
  90. if (avail > src_len) {
  91. avail = src_len;
  92. }
  93. memcpy(blocks_.back() + offset, src, avail);
  94. src_len -= avail;
  95. src += avail;
  96. size_ += avail;
  97. }
  98. return Status::OK();
  99. }
  100. private:
  101. // Private since only Unref() should be used to delete it.
  102. ~FileState() {
  103. for (std::vector<char*>::iterator i = blocks_.begin(); i != blocks_.end();
  104. ++i) {
  105. delete [] *i;
  106. }
  107. }
  108. // No copying allowed.
  109. FileState(const FileState&);
  110. void operator=(const FileState&);
  111. port::Mutex refs_mutex_;
  112. int refs_; // Protected by refs_mutex_;
  113. // The following fields are not protected by any mutex. They are only mutable
  114. // while the file is being written, and concurrent access is not allowed
  115. // to writable files.
  116. std::vector<char*> blocks_;
  117. uint64_t size_;
  118. enum { kBlockSize = 8 * 1024 };
  119. };
  120. class SequentialFileImpl : public SequentialFile {
  121. public:
  122. explicit SequentialFileImpl(FileState* file) : file_(file), pos_(0) {
  123. file_->Ref();
  124. }
  125. ~SequentialFileImpl() {
  126. file_->Unref();
  127. }
  128. virtual Status Read(size_t n, Slice* result, char* scratch) {
  129. Status s = file_->Read(pos_, n, result, scratch);
  130. if (s.ok()) {
  131. pos_ += result->size();
  132. }
  133. return s;
  134. }
  135. virtual Status Skip(uint64_t n) {
  136. if (pos_ > file_->Size()) {
  137. return Status::IOError("pos_ > file_->Size()");
  138. }
  139. const size_t available = file_->Size() - pos_;
  140. if (n > available) {
  141. n = available;
  142. }
  143. pos_ += n;
  144. return Status::OK();
  145. }
  146. private:
  147. FileState* file_;
  148. size_t pos_;
  149. };
  150. class RandomAccessFileImpl : public RandomAccessFile {
  151. public:
  152. explicit RandomAccessFileImpl(FileState* file) : file_(file) {
  153. file_->Ref();
  154. }
  155. ~RandomAccessFileImpl() {
  156. file_->Unref();
  157. }
  158. virtual Status Read(uint64_t offset, size_t n, Slice* result,
  159. char* scratch) const {
  160. return file_->Read(offset, n, result, scratch);
  161. }
  162. private:
  163. FileState* file_;
  164. };
  165. class WritableFileImpl : public WritableFile {
  166. public:
  167. WritableFileImpl(FileState* file) : file_(file) {
  168. file_->Ref();
  169. }
  170. ~WritableFileImpl() {
  171. file_->Unref();
  172. }
  173. virtual Status Append(const Slice& data) {
  174. return file_->Append(data);
  175. }
  176. virtual Status Close() { return Status::OK(); }
  177. virtual Status Flush() { return Status::OK(); }
  178. virtual Status Sync() { return Status::OK(); }
  179. private:
  180. FileState* file_;
  181. };
  182. class NoOpLogger : public Logger {
  183. public:
  184. virtual void Logv(const char* format, va_list ap) { }
  185. };
  186. class InMemoryEnv : public EnvWrapper {
  187. public:
  188. explicit InMemoryEnv(Env* base_env) : EnvWrapper(base_env) { }
  189. virtual ~InMemoryEnv() {
  190. for (FileSystem::iterator i = file_map_.begin(); i != file_map_.end(); ++i){
  191. i->second->Unref();
  192. }
  193. }
  194. // Partial implementation of the Env interface.
  195. virtual Status NewSequentialFile(const std::string& fname,
  196. SequentialFile** result) {
  197. MutexLock lock(&mutex_);
  198. if (file_map_.find(fname) == file_map_.end()) {
  199. *result = NULL;
  200. return Status::IOError(fname, "File not found");
  201. }
  202. *result = new SequentialFileImpl(file_map_[fname]);
  203. return Status::OK();
  204. }
  205. virtual Status NewRandomAccessFile(const std::string& fname,
  206. RandomAccessFile** result) {
  207. MutexLock lock(&mutex_);
  208. if (file_map_.find(fname) == file_map_.end()) {
  209. *result = NULL;
  210. return Status::IOError(fname, "File not found");
  211. }
  212. *result = new RandomAccessFileImpl(file_map_[fname]);
  213. return Status::OK();
  214. }
  215. virtual Status NewWritableFile(const std::string& fname,
  216. WritableFile** result) {
  217. MutexLock lock(&mutex_);
  218. if (file_map_.find(fname) != file_map_.end()) {
  219. DeleteFileInternal(fname);
  220. }
  221. FileState* file = new FileState();
  222. file->Ref();
  223. file_map_[fname] = file;
  224. *result = new WritableFileImpl(file);
  225. return Status::OK();
  226. }
  227. virtual bool FileExists(const std::string& fname) {
  228. MutexLock lock(&mutex_);
  229. return file_map_.find(fname) != file_map_.end();
  230. }
  231. virtual Status GetChildren(const std::string& dir,
  232. std::vector<std::string>* result) {
  233. MutexLock lock(&mutex_);
  234. result->clear();
  235. for (FileSystem::iterator i = file_map_.begin(); i != file_map_.end(); ++i){
  236. const std::string& filename = i->first;
  237. if (filename.size() >= dir.size() + 1 && filename[dir.size()] == '/' &&
  238. Slice(filename).starts_with(Slice(dir))) {
  239. result->push_back(filename.substr(dir.size() + 1));
  240. }
  241. }
  242. return Status::OK();
  243. }
  244. void DeleteFileInternal(const std::string& fname) {
  245. if (file_map_.find(fname) == file_map_.end()) {
  246. return;
  247. }
  248. file_map_[fname]->Unref();
  249. file_map_.erase(fname);
  250. }
  251. virtual Status DeleteFile(const std::string& fname) {
  252. MutexLock lock(&mutex_);
  253. if (file_map_.find(fname) == file_map_.end()) {
  254. return Status::IOError(fname, "File not found");
  255. }
  256. DeleteFileInternal(fname);
  257. return Status::OK();
  258. }
  259. virtual Status CreateDir(const std::string& dirname) {
  260. return Status::OK();
  261. }
  262. virtual Status DeleteDir(const std::string& dirname) {
  263. return Status::OK();
  264. }
  265. virtual Status GetFileSize(const std::string& fname, uint64_t* file_size) {
  266. MutexLock lock(&mutex_);
  267. if (file_map_.find(fname) == file_map_.end()) {
  268. return Status::IOError(fname, "File not found");
  269. }
  270. *file_size = file_map_[fname]->Size();
  271. return Status::OK();
  272. }
  273. virtual Status RenameFile(const std::string& src,
  274. const std::string& target) {
  275. MutexLock lock(&mutex_);
  276. if (file_map_.find(src) == file_map_.end()) {
  277. return Status::IOError(src, "File not found");
  278. }
  279. DeleteFileInternal(target);
  280. file_map_[target] = file_map_[src];
  281. file_map_.erase(src);
  282. return Status::OK();
  283. }
  284. virtual Status LockFile(const std::string& fname, FileLock** lock) {
  285. *lock = new FileLock;
  286. return Status::OK();
  287. }
  288. virtual Status UnlockFile(FileLock* lock) {
  289. delete lock;
  290. return Status::OK();
  291. }
  292. virtual Status GetTestDirectory(std::string* path) {
  293. *path = "/test";
  294. return Status::OK();
  295. }
  296. virtual Status NewLogger(const std::string& fname, Logger** result) {
  297. *result = new NoOpLogger;
  298. return Status::OK();
  299. }
  300. private:
  301. // Map from filenames to FileState objects, representing a simple file system.
  302. typedef std::map<std::string, FileState*> FileSystem;
  303. port::Mutex mutex_;
  304. FileSystem file_map_; // Protected by mutex_.
  305. };
  306. } // namespace
  307. Env* NewMemEnv(Env* base_env) {
  308. return new InMemoryEnv(base_env);
  309. }
  310. } // namespace leveldb