xref: /aosp_15_r20/external/cronet/net/disk_cache/blockfile/mapped_file_bypass_mmap_posix.cc (revision 6777b5387eb2ff775bb5750e3f5d96f37fb7352b)
1 // Copyright 2012 The Chromium Authors
2 // Use of this source code is governed by a BSD-style license that can be
3 // found in the LICENSE file.
4 
5 #include "net/disk_cache/blockfile/mapped_file.h"
6 
7 #include <stdlib.h>
8 
9 #include "base/check.h"
10 #include "base/files/file_path.h"
11 
12 namespace disk_cache {
13 
Init(const base::FilePath & name,size_t size)14 void* MappedFile::Init(const base::FilePath& name, size_t size) {
15   DCHECK(!init_);
16   if (init_ || !File::Init(name))
17     return nullptr;
18 
19   if (!size)
20     size = GetLength();
21 
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_ = nullptr;
30     snapshot_ = nullptr;
31   }
32 
33   init_ = true;
34   view_size_ = size;
35   return buffer_;
36 }
37 
Flush()38 void MappedFile::Flush() {
39   DCHECK(buffer_);
40   DCHECK(snapshot_);
41   const char* buffer_ptr = static_cast<const char*>(buffer_);
42   char* snapshot_ptr = static_cast<char*>(snapshot_);
43   const size_t block_size = 4096;
44   for (size_t offset = 0; offset < view_size_; offset += block_size) {
45     size_t size = std::min(view_size_ - offset, block_size);
46     if (memcmp(snapshot_ptr + offset, buffer_ptr + offset, size)) {
47       memcpy(snapshot_ptr + offset, buffer_ptr + offset, size);
48       Write(snapshot_ptr + offset, size, offset);
49     }
50   }
51 }
52 
~MappedFile()53 MappedFile::~MappedFile() {
54   if (!init_)
55     return;
56 
57   if (buffer_ && snapshot_) {
58     Flush();
59   }
60   free(buffer_);
61   free(snapshot_);
62 }
63 
64 }  // namespace disk_cache
65