Cache Backend Proxy to intercept all cache events from the IO thread.
[chromium-blink-merge.git] / net / disk_cache / mapped_file_avoid_mmap_posix.cc
blobd751c74fe4a08f5fe70a26369b413848e1dc7674
1 // Copyright (c) 2012 The Chromium 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.
5 #include "net/disk_cache/mapped_file.h"
7 #include <stdlib.h>
9 #include "base/files/file_path.h"
10 #include "base/logging.h"
12 namespace disk_cache {
14 void* MappedFile::Init(const base::FilePath& name, size_t size) {
15 DCHECK(!init_);
16 if (init_ || !File::Init(name))
17 return NULL;
19 if (!size)
20 size = GetLength();
22 buffer_ = malloc(size);
23 snapshot_ = malloc(size);
24 if (buffer_ && snapshot_ && Read(buffer_, size, 0)) {
25 memcpy(snapshot_, buffer_, size);
26 } else {
27 free(buffer_);
28 free(snapshot_);
29 buffer_ = snapshot_ = 0;
32 init_ = true;
33 view_size_ = size;
34 return buffer_;
37 bool MappedFile::Load(const FileBlock* block) {
38 size_t offset = block->offset() + view_size_;
39 return Read(block->buffer(), block->size(), offset);
42 bool MappedFile::Store(const FileBlock* block) {
43 size_t offset = block->offset() + view_size_;
44 return Write(block->buffer(), block->size(), offset);
47 void MappedFile::Flush() {
48 DCHECK(buffer_);
49 DCHECK(snapshot_);
50 if (0 == memcmp(buffer_, snapshot_, view_size_)) {
51 // Nothing changed, no need to flush.
52 return;
55 const char* buffer_ptr = static_cast<const char*>(buffer_);
56 char* snapshot_ptr = static_cast<char*>(snapshot_);
57 size_t i = 0;
58 while (i < view_size_) {
59 size_t run_start = i;
60 // Look for a run of changed bytes (possibly zero-sized). Write them out.
61 while(i < view_size_ && snapshot_ptr[i] != buffer_ptr[i]) {
62 snapshot_ptr[i] = buffer_ptr[i];
63 i++;
65 if (i > run_start) {
66 Write(snapshot_ptr + run_start, i - run_start, run_start);
68 // Look for a run of unchanged bytes (possibly zero-sized). Skip them.
69 while (i < view_size_ && snapshot_ptr[i] == buffer_ptr[i]) {
70 i++;
73 DCHECK(0 == memcmp(buffer_, snapshot_, view_size_));
76 MappedFile::~MappedFile() {
77 if (!init_)
78 return;
80 if (buffer_ && snapshot_) {
81 Flush();
83 free(buffer_);
84 free(snapshot_);
87 } // namespace disk_cache