Write new Starts/EndsWith and convert FilePath functions to StringPiece.
[chromium-blink-merge.git] / base / files / memory_mapped_file.cc
blobbad1792ec3de4ea32be250de2d0515d74e263731
1 // Copyright 2013 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 "base/files/memory_mapped_file.h"
7 #include "base/files/file_path.h"
8 #include "base/logging.h"
9 #include "base/sys_info.h"
11 namespace base {
13 const MemoryMappedFile::Region MemoryMappedFile::Region::kWholeFile(
14 base::LINKER_INITIALIZED);
16 MemoryMappedFile::Region::Region(base::LinkerInitialized) : offset(0), size(0) {
19 MemoryMappedFile::Region::Region() : offset(-1), size(-1) {
22 MemoryMappedFile::Region::Region(int64 offset, int64 size)
23 : offset(offset), size(size) {
26 bool MemoryMappedFile::Region::operator==(
27 const MemoryMappedFile::Region& other) const {
28 return other.offset == offset && other.size == size;
31 bool MemoryMappedFile::Region::operator!=(
32 const MemoryMappedFile::Region& other) const {
33 return other.offset != offset || other.size != size;
36 MemoryMappedFile::~MemoryMappedFile() {
37 CloseHandles();
40 #if !defined(OS_NACL)
41 bool MemoryMappedFile::Initialize(const FilePath& file_name) {
42 if (IsValid())
43 return false;
45 file_.Initialize(file_name, File::FLAG_OPEN | File::FLAG_READ);
47 if (!file_.IsValid()) {
48 DLOG(ERROR) << "Couldn't open " << file_name.AsUTF8Unsafe();
49 return false;
52 if (!MapFileRegionToMemory(Region::kWholeFile)) {
53 CloseHandles();
54 return false;
57 return true;
60 bool MemoryMappedFile::Initialize(File file) {
61 return Initialize(file.Pass(), Region::kWholeFile);
64 bool MemoryMappedFile::Initialize(File file, const Region& region) {
65 if (IsValid())
66 return false;
68 if (region != Region::kWholeFile) {
69 DCHECK_GE(region.offset, 0);
70 DCHECK_GT(region.size, 0);
73 file_ = file.Pass();
75 if (!MapFileRegionToMemory(region)) {
76 CloseHandles();
77 return false;
80 return true;
83 bool MemoryMappedFile::IsValid() const {
84 return data_ != NULL;
87 // static
88 void MemoryMappedFile::CalculateVMAlignedBoundaries(int64 start,
89 int64 size,
90 int64* aligned_start,
91 int64* aligned_size,
92 int32* offset) {
93 // Sadly, on Windows, the mmap alignment is not just equal to the page size.
94 const int64 mask = static_cast<int64>(SysInfo::VMAllocationGranularity()) - 1;
95 DCHECK_LT(mask, std::numeric_limits<int32>::max());
96 *offset = start & mask;
97 *aligned_start = start & ~mask;
98 *aligned_size = (size + *offset + mask) & ~mask;
100 #endif
102 } // namespace base