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.
7 #include "base/logging.h"
8 #include "net/disk_cache/flash/format.h"
9 #include "net/disk_cache/flash/segment.h"
10 #include "net/disk_cache/flash/storage.h"
12 namespace disk_cache {
14 Segment::Segment(int32 index, bool read_only, Storage* storage)
17 read_only_(read_only),
20 offset_(index * kFlashSegmentSize),
21 summary_offset_(offset_ + kFlashSegmentSize - kFlashSummarySize),
22 write_offset_(offset_) {
24 DCHECK(storage->size() % kFlashSegmentSize == 0);
28 DCHECK(!init_ || read_only_);
30 LOG(WARNING) << "Users exist, but we don't care? " << num_users_;
33 bool Segment::HaveOffset(int32 offset) const {
35 return std::binary_search(offsets_.begin(), offsets_.end(), offset);
38 void Segment::AddUser() {
43 void Segment::ReleaseUser() {
48 bool Segment::HasNoUsers() const {
50 return num_users_ == 0;
53 bool Segment::Init() {
56 if (offset_ < 0 || offset_ + kFlashSegmentSize > storage_->size())
64 int32 summary[kFlashMaxEntryCount + 1];
65 if (!storage_->Read(summary, kFlashSummarySize, summary_offset_))
68 size_t entry_count = summary[0];
69 DCHECK_LE(entry_count, kFlashMaxEntryCount);
71 std::vector<int32> tmp(summary + 1, summary + 1 + entry_count);
77 bool Segment::WriteData(const void* buffer, int32 size) {
78 DCHECK(init_ && !read_only_);
79 DCHECK(write_offset_ + size <= summary_offset_);
80 if (!storage_->Write(buffer, size, write_offset_))
82 write_offset_ += size;
86 void Segment::StoreOffset(int32 offset) {
87 DCHECK(init_ && !read_only_);
88 DCHECK(offsets_.size() < kFlashMaxEntryCount);
89 offsets_.push_back(offset);
92 bool Segment::ReadData(void* buffer, int32 size, int32 offset) const {
94 DCHECK(offset >= offset_ && offset + size <= offset_ + kFlashSegmentSize);
95 return storage_->Read(buffer, size, offset);
98 bool Segment::Close() {
103 DCHECK(offsets_.size() <= kFlashMaxEntryCount);
105 int32 summary[kFlashMaxEntryCount + 1];
106 memset(summary, 0, kFlashSummarySize);
107 summary[0] = offsets_.size();
108 std::copy(offsets_.begin(), offsets_.end(), summary + 1);
109 if (!storage_->Write(summary, kFlashSummarySize, summary_offset_))
116 bool Segment::CanHold(int32 size) const {
118 return offsets_.size() < kFlashMaxEntryCount &&
119 write_offset_ + size <= summary_offset_;
122 } // namespace disk_cache