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"
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
) {
16 if (init_
|| !File::Init(name
))
22 buffer_
= malloc(size
);
23 snapshot_
= malloc(size
);
24 if (buffer_
&& snapshot_
&& Read(buffer_
, size
, 0)) {
25 memcpy(snapshot_
, buffer_
, size
);
29 buffer_
= snapshot_
= 0;
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() {
50 if (0 == memcmp(buffer_
, snapshot_
, view_size_
)) {
51 // Nothing changed, no need to flush.
55 const char* buffer_ptr
= static_cast<const char*>(buffer_
);
56 char* snapshot_ptr
= static_cast<char*>(snapshot_
);
58 while (i
< view_size_
) {
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
];
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
]) {
73 DCHECK(0 == memcmp(buffer_
, snapshot_
, view_size_
));
76 MappedFile::~MappedFile() {
80 if (buffer_
&& snapshot_
) {
87 } // namespace disk_cache