1 // Copyright (c) 2010 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 #ifndef PDF_CHUNK_STREAM_H_
6 #define PDF_CHUNK_STREAM_H_
17 #include "pdf/range_set.h"
19 namespace chrome_pdf {
21 // This class collects a chunks of data into one data stream. Client can check
22 // if data in certain range is available, and get missing chunks of data.
26 static constexpr uint32_t kChunkSize = N;
27 using ChunkData = typename std::array<unsigned char, N>;
32 void SetChunkData(uint32_t chunk_index, std::unique_ptr<ChunkData> data) {
36 if (chunk_index >= data_.size())
37 data_.resize(chunk_index + 1);
39 if (!data_[chunk_index])
40 ++filled_chunks_count_;
42 data_[chunk_index] = std::move(data);
43 filled_chunks_.Union(gfx::Range(chunk_index, chunk_index + 1));
46 bool ReadData(const gfx::Range& range, void* buffer) const {
47 if (!IsRangeAvailable(range))
50 unsigned char* data_buffer = static_cast<unsigned char*>(buffer);
51 uint32_t start = range.start();
52 while (start != range.end()) {
53 const uint32_t chunk_index = GetChunkIndex(start);
54 const uint32_t chunk_start = start % kChunkSize;
56 std::min(kChunkSize - chunk_start, range.end() - start);
57 memcpy(data_buffer, data_[chunk_index]->data() + chunk_start, len);
64 uint32_t GetChunkIndex(uint32_t offset) const { return offset / kChunkSize; }
66 gfx::Range GetChunksRange(uint32_t offset, uint32_t size) const {
67 return gfx::Range(GetChunkIndex(offset), GetChunkEnd(offset + size));
70 bool IsRangeAvailable(const gfx::Range& range) const {
71 if (!range.IsValid() || range.is_reversed() ||
72 (eof_pos_ > 0 && eof_pos_ < range.end())) {
79 const gfx::Range chunks_range(GetChunkIndex(range.start()),
80 GetChunkEnd(range.end()));
81 return filled_chunks_.Contains(chunks_range);
84 bool IsChunkAvailable(uint32_t chunk_index) const {
85 return filled_chunks_.Contains(chunk_index);
88 void set_eof_pos(uint32_t eof_pos) { eof_pos_ = eof_pos; }
89 uint32_t eof_pos() const { return eof_pos_; }
91 const RangeSet& filled_chunks() const { return filled_chunks_; }
93 bool IsComplete() const {
94 return eof_pos_ > 0 && IsRangeAvailable(gfx::Range(0, eof_pos_));
97 bool IsValidChunkIndex(uint32_t chunk_index) const {
98 return !eof_pos_ || (chunk_index <= GetChunkIndex(eof_pos_ - 1));
104 filled_chunks_.Clear();
105 filled_chunks_count_ = 0;
108 uint32_t filled_chunks_count() const { return filled_chunks_count_; }
109 uint32_t total_chunks_count() const { return GetChunkEnd(eof_pos_); }
112 uint32_t GetChunkEnd(uint32_t offset) const {
113 return (offset + kChunkSize - 1) / kChunkSize;
116 std::vector<std::unique_ptr<ChunkData>> data_;
117 uint32_t eof_pos_ = 0;
118 RangeSet filled_chunks_;
119 uint32_t filled_chunks_count_ = 0;
122 }; // namespace chrome_pdf
124 #endif // PDF_CHUNK_STREAM_H_