summaryrefslogtreecommitdiff
path: root/chromium/net/disk_cache/blockfile/mapped_file_avoid_mmap_posix.cc
blob: 3936358236dd37d787ff9396fd6fc2e218da7b91 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
// Copyright (c) 2012 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.

#include "net/disk_cache/blockfile/mapped_file.h"

#include <stdlib.h>

#include "base/files/file_path.h"
#include "base/logging.h"

namespace disk_cache {

void* MappedFile::Init(const base::FilePath& name, size_t size) {
  DCHECK(!init_);
  if (init_ || !File::Init(name))
    return NULL;

  if (!size)
    size = GetLength();

  buffer_ = malloc(size);
  snapshot_ = malloc(size);
  if (buffer_ && snapshot_ && Read(buffer_, size, 0)) {
    memcpy(snapshot_, buffer_, size);
  } else {
    free(buffer_);
    free(snapshot_);
    buffer_ = snapshot_ = 0;
  }

  init_ = true;
  view_size_ = size;
  return buffer_;
}

void MappedFile::Flush() {
  DCHECK(buffer_);
  DCHECK(snapshot_);
  const char* buffer_ptr = static_cast<const char*>(buffer_);
  char* snapshot_ptr = static_cast<char*>(snapshot_);
  const size_t block_size = 4096;
  for (size_t offset = 0; offset < view_size_; offset += block_size) {
    size_t size = std::min(view_size_ - offset, block_size);
    if (memcmp(snapshot_ptr + offset, buffer_ptr + offset, size)) {
      memcpy(snapshot_ptr + offset, buffer_ptr + offset, size);
      Write(snapshot_ptr + offset, size, offset);
    }
  }
}

MappedFile::~MappedFile() {
  if (!init_)
    return;

  if (buffer_ && snapshot_) {
    Flush();
  }
  free(buffer_);
  free(snapshot_);
}

}  // namespace disk_cache