1 // Copyright (c) 2006-2008 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.
4
5 #include "net/disk_cache/mapped_file.h"
6
7 #include <errno.h>
8 #include <sys/mman.h>
9
10 #include "base/file_path.h"
11 #include "base/logging.h"
12 #include "net/disk_cache/disk_cache.h"
13
14 namespace disk_cache {
15
Init(const FilePath & name,size_t size)16 void* MappedFile::Init(const FilePath& name, size_t size) {
17 DCHECK(!init_);
18 if (init_ || !File::Init(name))
19 return NULL;
20
21 if (!size)
22 size = GetLength();
23
24 buffer_ = mmap(NULL, size, PROT_READ | PROT_WRITE, MAP_SHARED,
25 platform_file(), 0);
26 init_ = true;
27 DCHECK(reinterpret_cast<intptr_t>(buffer_) != -1);
28 if (reinterpret_cast<intptr_t>(buffer_) == -1)
29 buffer_ = 0;
30
31 view_size_ = size;
32 return buffer_;
33 }
34
~MappedFile()35 MappedFile::~MappedFile() {
36 if (!init_)
37 return;
38
39 if (buffer_) {
40 int ret = munmap(buffer_, view_size_);
41 DCHECK(0 == ret);
42 }
43 }
44
Load(const FileBlock * block)45 bool MappedFile::Load(const FileBlock* block) {
46 size_t offset = block->offset() + view_size_;
47 return Read(block->buffer(), block->size(), offset);
48 }
49
Store(const FileBlock * block)50 bool MappedFile::Store(const FileBlock* block) {
51 size_t offset = block->offset() + view_size_;
52 return Write(block->buffer(), block->size(), offset);
53 }
54
55 } // namespace disk_cache
56