LevelDB project 1 10225501460 林子骥 10211900416 郭夏辉
Nevar pievienot vairāk kā 25 tēmas Tēmai ir jāsākas ar burtu vai ciparu, tā var saturēt domu zīmes ('-') un var būt līdz 35 simboliem gara.

390 rindas
9.6 KiB

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