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.
5 #include "helpers/memenv/memenv.h"
7 #include "leveldb/env.h"
8 #include "leveldb/status.h"
10 #include "util/mutexlock.h"
22 // FileStates are reference counted. The initial reference count is zero
23 // and the caller must call Ref() at least once.
24 FileState() : refs_(0), size_(0) {}
26 // Increase the reference count.
28 MutexLock lock(&refs_mutex_);
32 // Decrease the reference count. Delete if this is the last reference.
34 bool do_delete = false;
37 MutexLock lock(&refs_mutex_);
50 uint64_t Size() const { return size_; }
52 Status Read(uint64_t offset, size_t n, Slice* result, char* scratch) const {
54 return Status::IOError("Offset greater than file size.");
56 const uint64_t available = size_ - offset;
58 n = static_cast<size_t>(available);
65 assert(offset / kBlockSize <= SIZE_MAX);
66 size_t block = static_cast<size_t>(offset / kBlockSize);
67 size_t block_offset = offset % kBlockSize;
69 if (n <= kBlockSize - block_offset) {
70 // The requested bytes are all in the first block.
71 *result = Slice(blocks_[block] + block_offset, n);
75 size_t bytes_to_copy = n;
78 while (bytes_to_copy > 0) {
79 size_t avail = kBlockSize - block_offset;
80 if (avail > bytes_to_copy) {
81 avail = bytes_to_copy;
83 memcpy(dst, blocks_[block] + block_offset, avail);
85 bytes_to_copy -= avail;
91 *result = Slice(scratch, n);
95 Status Append(const Slice& data) {
96 const char* src = data.data();
97 size_t src_len = data.size();
101 size_t offset = size_ % kBlockSize;
104 // There is some room in the last block.
105 avail = kBlockSize - offset;
107 // No room in the last block; push new one.
108 blocks_.push_back(new char[kBlockSize]);
112 if (avail > src_len) {
115 memcpy(blocks_.back() + offset, src, avail);
125 // Private since only Unref() should be used to delete it.
127 for (std::vector<char*>::iterator i = blocks_.begin(); i != blocks_.end();
133 // No copying allowed.
134 FileState(const FileState&);
135 void operator=(const FileState&);
137 port::Mutex refs_mutex_;
138 int refs_; // Protected by refs_mutex_;
140 // The following fields are not protected by any mutex. They are only mutable
141 // while the file is being written, and concurrent access is not allowed
142 // to writable files.
143 std::vector<char*> blocks_;
146 enum { kBlockSize = 8 * 1024 };
149 class SequentialFileImpl : public SequentialFile {
151 explicit SequentialFileImpl(FileState* file) : file_(file), pos_(0) {
155 ~SequentialFileImpl() {
159 virtual Status Read(size_t n, Slice* result, char* scratch) {
160 Status s = file_->Read(pos_, n, result, scratch);
162 pos_ += result->size();
167 virtual Status Skip(uint64_t n) {
168 if (pos_ > file_->Size()) {
169 return Status::IOError("pos_ > file_->Size()");
171 const uint64_t available = file_->Size() - pos_;
184 class RandomAccessFileImpl : public RandomAccessFile {
186 explicit RandomAccessFileImpl(FileState* file) : file_(file) {
190 ~RandomAccessFileImpl() {
194 virtual Status Read(uint64_t offset, size_t n, Slice* result,
195 char* scratch) const {
196 return file_->Read(offset, n, result, scratch);
203 class WritableFileImpl : public WritableFile {
205 WritableFileImpl(FileState* file) : file_(file) {
209 ~WritableFileImpl() {
213 virtual Status Append(const Slice& data) {
214 return file_->Append(data);
217 virtual Status Close() { return Status::OK(); }
218 virtual Status Flush() { return Status::OK(); }
219 virtual Status Sync() { return Status::OK(); }
225 class NoOpLogger : public Logger {
227 virtual void Logv(const char* format, va_list ap) { }
230 class InMemoryEnv : public EnvWrapper {
232 explicit InMemoryEnv(Env* base_env) : EnvWrapper(base_env) { }
234 virtual ~InMemoryEnv() {
235 for (FileSystem::iterator i = file_map_.begin(); i != file_map_.end(); ++i){
240 // Partial implementation of the Env interface.
241 virtual Status NewSequentialFile(const std::string& fname,
242 SequentialFile** result) {
243 MutexLock lock(&mutex_);
244 if (file_map_.find(fname) == file_map_.end()) {
246 return Status::IOError(fname, "File not found");
249 *result = new SequentialFileImpl(file_map_[fname]);
253 virtual Status NewRandomAccessFile(const std::string& fname,
254 RandomAccessFile** result) {
255 MutexLock lock(&mutex_);
256 if (file_map_.find(fname) == file_map_.end()) {
258 return Status::IOError(fname, "File not found");
261 *result = new RandomAccessFileImpl(file_map_[fname]);
265 virtual Status NewWritableFile(const std::string& fname,
266 WritableFile** result) {
267 MutexLock lock(&mutex_);
268 if (file_map_.find(fname) != file_map_.end()) {
269 DeleteFileInternal(fname);
272 FileState* file = new FileState();
274 file_map_[fname] = file;
276 *result = new WritableFileImpl(file);
280 virtual bool FileExists(const std::string& fname) {
281 MutexLock lock(&mutex_);
282 return file_map_.find(fname) != file_map_.end();
285 virtual Status GetChildren(const std::string& dir,
286 std::vector<std::string>* result) {
287 MutexLock lock(&mutex_);
290 for (FileSystem::iterator i = file_map_.begin(); i != file_map_.end(); ++i){
291 const std::string& filename = i->first;
293 if (filename.size() >= dir.size() + 1 && filename[dir.size()] == '/' &&
294 Slice(filename).starts_with(Slice(dir))) {
295 result->push_back(filename.substr(dir.size() + 1));
302 void DeleteFileInternal(const std::string& fname) {
303 if (file_map_.find(fname) == file_map_.end()) {
307 file_map_[fname]->Unref();
308 file_map_.erase(fname);
311 virtual Status DeleteFile(const std::string& fname) {
312 MutexLock lock(&mutex_);
313 if (file_map_.find(fname) == file_map_.end()) {
314 return Status::IOError(fname, "File not found");
317 DeleteFileInternal(fname);
321 virtual Status CreateDir(const std::string& dirname) {
325 virtual Status DeleteDir(const std::string& dirname) {
329 virtual Status GetFileSize(const std::string& fname, uint64_t* file_size) {
330 MutexLock lock(&mutex_);
331 if (file_map_.find(fname) == file_map_.end()) {
332 return Status::IOError(fname, "File not found");
335 *file_size = file_map_[fname]->Size();
339 virtual Status RenameFile(const std::string& src,
340 const std::string& target) {
341 MutexLock lock(&mutex_);
342 if (file_map_.find(src) == file_map_.end()) {
343 return Status::IOError(src, "File not found");
346 DeleteFileInternal(target);
347 file_map_[target] = file_map_[src];
348 file_map_.erase(src);
352 virtual Status LockFile(const std::string& fname, FileLock** lock) {
353 *lock = new FileLock;
357 virtual Status UnlockFile(FileLock* lock) {
362 virtual Status GetTestDirectory(std::string* path) {
367 virtual Status NewLogger(const std::string& fname, Logger** result) {
368 *result = new NoOpLogger;
373 // Map from filenames to FileState objects, representing a simple file system.
374 typedef std::map<std::string, FileState*> FileSystem;
376 FileSystem file_map_; // Protected by mutex_.
381 Env* NewMemEnv(Env* base_env) {
382 return new InMemoryEnv(base_env);
385 } // namespace leveldb