1 /*
2 * Copyright (C) 2017 The Android Open Source Project
3 *
4 * Licensed under the Apache License, Version 2.0 (the "License");
5 * you may not use this file except in compliance with the License.
6 * You may obtain a copy of the License at
7 *
8 * http://www.apache.org/licenses/LICENSE-2.0
9 *
10 * Unless required by applicable law or agreed to in writing, software
11 * distributed under the License is distributed on an "AS IS" BASIS,
12 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 * See the License for the specific language governing permissions and
14 * limitations under the License.
15 */
16
17 #include "perfetto/protozero/scattered_heap_buffer.h"
18
19 #include <algorithm>
20
21 namespace protozero {
22
Slice(size_t size)23 ScatteredHeapBuffer::Slice::Slice(size_t size)
24 : buffer_(std::unique_ptr<uint8_t[]>(new uint8_t[size])),
25 size_(size),
26 unused_bytes_(size) {
27 PERFETTO_DCHECK(size);
28 #if PERFETTO_DCHECK_IS_ON()
29 memset(start(), 0xff, size_);
30 #endif // PERFETTO_DCHECK_IS_ON()
31 }
32
33 ScatteredHeapBuffer::Slice::Slice(Slice&& slice) noexcept = default;
34
35 ScatteredHeapBuffer::Slice::~Slice() = default;
36
ScatteredHeapBuffer(size_t initial_slice_size_bytes,size_t maximum_slice_size_bytes)37 ScatteredHeapBuffer::ScatteredHeapBuffer(size_t initial_slice_size_bytes,
38 size_t maximum_slice_size_bytes)
39 : next_slice_size_(initial_slice_size_bytes),
40 maximum_slice_size_(maximum_slice_size_bytes) {
41 PERFETTO_DCHECK(next_slice_size_ && maximum_slice_size_);
42 PERFETTO_DCHECK(maximum_slice_size_ >= initial_slice_size_bytes);
43 }
44
45 ScatteredHeapBuffer::~ScatteredHeapBuffer() = default;
46
GetNewBuffer()47 protozero::ContiguousMemoryRange ScatteredHeapBuffer::GetNewBuffer() {
48 PERFETTO_CHECK(writer_);
49 AdjustUsedSizeOfCurrentSlice();
50
51 slices_.emplace_back(next_slice_size_);
52 next_slice_size_ = std::min(maximum_slice_size_, next_slice_size_ * 2);
53 return slices_.back().GetTotalRange();
54 }
55
StitchSlices()56 std::vector<uint8_t> ScatteredHeapBuffer::StitchSlices() {
57 AdjustUsedSizeOfCurrentSlice();
58 std::vector<uint8_t> buffer;
59 size_t i = 0;
60 for (const auto& slice : slices_) {
61 auto used_range = slice.GetUsedRange();
62 buffer.insert(buffer.end(), used_range.begin, used_range.end);
63 i++;
64 }
65 return buffer;
66 }
67
AdjustUsedSizeOfCurrentSlice()68 void ScatteredHeapBuffer::AdjustUsedSizeOfCurrentSlice() {
69 if (!slices_.empty())
70 slices_.back().set_unused_bytes(writer_->bytes_available());
71 }
72
GetTotalSize()73 size_t ScatteredHeapBuffer::GetTotalSize() {
74 size_t total_size = 0;
75 for (auto& slice : slices_) {
76 total_size += slice.size();
77 }
78 return total_size;
79 }
80
81 } // namespace protozero
82