memenv.cc 9.6 KB

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