• Home
  • Line#
  • Scopes#
  • Navigate#
  • Raw
  • Download
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_stream_writer.h"
18 
19 #include <algorithm>
20 
21 #include "perfetto/base/logging.h"
22 
23 namespace protozero {
24 
~Delegate()25 ScatteredStreamWriter::Delegate::~Delegate() {}
26 
ScatteredStreamWriter(Delegate * delegate)27 ScatteredStreamWriter::ScatteredStreamWriter(Delegate* delegate)
28     : delegate_(delegate),
29       cur_range_({nullptr, nullptr}),
30       write_ptr_(nullptr) {}
31 
~ScatteredStreamWriter()32 ScatteredStreamWriter::~ScatteredStreamWriter() {}
33 
Reset(ContiguousMemoryRange range)34 void ScatteredStreamWriter::Reset(ContiguousMemoryRange range) {
35   written_previously_ += static_cast<uint64_t>(write_ptr_ - cur_range_.begin);
36   cur_range_ = range;
37   write_ptr_ = range.begin;
38   PERFETTO_DCHECK(!write_ptr_ || write_ptr_ < cur_range_.end);
39 }
40 
Extend()41 void ScatteredStreamWriter::Extend() {
42   Reset(delegate_->GetNewBuffer());
43 }
44 
WriteBytesSlowPath(const uint8_t * src,size_t size)45 void ScatteredStreamWriter::WriteBytesSlowPath(const uint8_t* src,
46                                                size_t size) {
47   size_t bytes_left = size;
48   while (bytes_left > 0) {
49     if (write_ptr_ >= cur_range_.end)
50       Extend();
51     const size_t burst_size = std::min(bytes_available(), bytes_left);
52     WriteBytesUnsafe(src, burst_size);
53     bytes_left -= burst_size;
54     src += burst_size;
55   }
56 }
57 
58 // TODO(primiano): perf optimization: I suspect that at the end this will always
59 // be called with |size| == 4, in which case we might just hardcode it.
ReserveBytes(size_t size)60 uint8_t* ScatteredStreamWriter::ReserveBytes(size_t size) {
61   if (write_ptr_ + size > cur_range_.end) {
62     // Assume the reservations are always < Delegate::GetNewBuffer().size(),
63     // so that one single call to Extend() will definitely give enough headroom.
64     Extend();
65     PERFETTO_DCHECK(write_ptr_ + size <= cur_range_.end);
66   }
67   uint8_t* begin = write_ptr_;
68   write_ptr_ += size;
69 #if PERFETTO_DCHECK_IS_ON()
70   memset(begin, 0, size);
71 #endif
72   return begin;
73 }
74 
75 }  // namespace protozero
76