File: rw_buffer.cc

package info (click to toggle)
chromium 138.0.7204.183-1
  • links: PTS, VCS
  • area: main
  • in suites: trixie
  • size: 6,071,908 kB
  • sloc: cpp: 34,937,088; ansic: 7,176,967; javascript: 4,110,704; python: 1,419,953; asm: 946,768; xml: 739,971; pascal: 187,324; sh: 89,623; perl: 88,663; objc: 79,944; sql: 50,304; cs: 41,786; fortran: 24,137; makefile: 21,806; php: 13,980; tcl: 13,166; yacc: 8,925; ruby: 7,485; awk: 3,720; lisp: 3,096; lex: 1,327; ada: 727; jsp: 228; sed: 36
file content (334 lines) | stat: -rw-r--r-- 9,260 bytes parent folder | download | duplicates (6)
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
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
// Copyright 2020 The Chromium Authors
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.

#include "third_party/blink/renderer/platform/image-decoders/rw_buffer.h"

#include <algorithm>
#include <atomic>
#include <new>

#include "base/atomic_ref_count.h"
#include "base/check.h"
#include "base/check_op.h"
#include "base/memory/raw_ptr.h"
#include "third_party/blink/renderer/platform/wtf/allocator/partitions.h"

namespace blink {

namespace {

// Force small chunks to be a page's worth
static const size_t kMinAllocSize = 4096;

}  // namespace

struct RWBuffer::BufferBlock {
  raw_ptr<RWBuffer::BufferBlock> next_;  // updated by the writer
  size_t used_;                          // updated by the writer
  const size_t capacity_;

  explicit BufferBlock(size_t capacity)
      : next_(nullptr), used_(0), capacity_(capacity) {}

  base::span<uint8_t> Buffer() {
    // SAFETY: The Alloc() function (in RWBuffer::BufferBlock or
    // RWBuffer::BufferHead) allocates an extra `capacity_` bytes at the end of
    // the object.
    return UNSAFE_BUFFERS({reinterpret_cast<uint8_t*>(this + 1), capacity_});
  }
  base::span<const uint8_t> Buffer() const {
    return const_cast<RWBuffer::BufferBlock*>(this)->Buffer();
  }

  static RWBuffer::BufferBlock* Alloc(size_t length) {
    size_t capacity = LengthToCapacity(length);
    void* buffer =
        WTF::Partitions::BufferMalloc(sizeof(RWBuffer::BufferBlock) + capacity,
                                      "blink::RWBuffer::BufferBlock");
    return new (buffer) RWBuffer::BufferBlock(capacity);
  }

  // Return number of bytes actually appended. Important that we always
  // completely fill this block before spilling into the next, since the reader
  // uses capacity_ to know how many bytes it can read.
  size_t Append(base::span<const uint8_t> src) {
    Validate();
    auto available_buffer = Buffer().subspan(used_);
    const size_t amount = std::min(available_buffer.size(), src.size());
    available_buffer.copy_prefix_from(src.first(amount));
    used_ += amount;
    Validate();
    return amount;
  }

  // Do not call in the reader thread, since the writer may be updating used_.
  // (The assertion is still true, but TSAN still may complain about its
  // raciness.)
  void Validate() const {
    DCHECK_GT(capacity_, 0u);
    DCHECK_LE(used_, capacity_);
  }

 private:
  static size_t LengthToCapacity(size_t length) {
    const size_t min_size = kMinAllocSize - sizeof(RWBuffer::BufferBlock);
    return std::max(length, min_size);
  }
};

struct RWBuffer::BufferHead {
  mutable base::AtomicRefCount ref_count_;
  RWBuffer::BufferBlock block_;

  explicit BufferHead(size_t capacity) : ref_count_(1), block_(capacity) {}

  static size_t LengthToCapacity(size_t length) {
    const size_t min_size = kMinAllocSize - sizeof(RWBuffer::BufferHead);
    return std::max(length, min_size);
  }

  static RWBuffer::BufferHead* Alloc(size_t length) {
    size_t capacity = LengthToCapacity(length);
    size_t size = sizeof(RWBuffer::BufferHead) + capacity;
    void* buffer =
        WTF::Partitions::BufferMalloc(size, "blink::RWBuffer::BufferHead");
    return new (buffer) RWBuffer::BufferHead(capacity);
  }

  void ref() const {
    auto old_ref_count = ref_count_.Increment();
    DCHECK_GT(old_ref_count, 0);
  }

  void unref() const {
    // A release here acts in place of all releases we "should" have been doing
    // in ref().
    if (!ref_count_.Decrement()) {
      // Like unique(), the acquire is only needed on success.
      RWBuffer::BufferBlock* block = block_.next_;

      // `buffer_` has a `raw_ptr` that needs to be destroyed to
      // properly lower the refcount.
      block_.~BufferBlock();
      WTF::Partitions::BufferFree(const_cast<RWBuffer::BufferHead*>(this));
      while (block) {
        RWBuffer::BufferBlock* next = block->next_;
        block->~BufferBlock();
        WTF::Partitions::BufferFree(block);
        block = next;
      }
    }
  }

  void Validate(size_t minUsed,
                const RWBuffer::BufferBlock* tail = nullptr) const {
#if DCHECK_IS_ON()
    DCHECK(!ref_count_.IsZero());
    size_t totalUsed = 0;
    const RWBuffer::BufferBlock* block = &block_;
    const RWBuffer::BufferBlock* lastBlock = block;
    while (block) {
      block->Validate();
      totalUsed += block->used_;
      lastBlock = block;
      block = block->next_;
    }
    DCHECK(minUsed <= totalUsed);
    if (tail) {
      DCHECK(tail == lastBlock);
    }
#endif
  }
};

RWBuffer::ROIter::ROIter(RWBuffer* rw_buffer, size_t available)
    : rw_buffer_(rw_buffer), remaining_(available) {
  DCHECK(rw_buffer_);
  block_ = &rw_buffer_->head_->block_;
}

base::span<const uint8_t> RWBuffer::ROIter::operator*() const {
  if (!remaining_) {
    return {};
  }
  DCHECK(block_);
  return block_->Buffer().first(std::min(block_->capacity_, remaining_));
}

bool RWBuffer::ROIter::Next() {
  if (remaining_) {
    const size_t current_size = std::min(block_->capacity_, remaining_);
    DCHECK_LE(current_size, remaining_);
    remaining_ -= current_size;
    if (remaining_ == 0) {
      block_ = nullptr;
    } else {
      block_ = block_->next_;
      DCHECK(block_);
    }
  }
  return remaining_ != 0;
}

bool RWBuffer::ROIter::HasNext() const {
  return block_ && block_->next_;
}

///////////////////////////////////////////////////////////////////////////////////////////////////
// The reader can only access block.capacity_ (which never changes), and cannot
// access block.used_, which may be updated by the writer.
//
ROBuffer::ROBuffer(const RWBuffer::BufferHead* head,
                   size_t available,
                   const RWBuffer::BufferBlock* tail)
    : head_(head), available_(available), tail_(tail) {
  if (head) {
    head_->ref();
    DCHECK_GT(available, 0u);
    head->Validate(available, tail);
  } else {
    DCHECK_EQ(0u, available);
    DCHECK(!tail);
  }
}

ROBuffer::~ROBuffer() {
  if (head_) {
    tail_ = nullptr;
    head_.ExtractAsDangling()->unref();
  }
}

ROBuffer::Iter::Iter(const ROBuffer* buffer) {
  Reset(buffer);
}

ROBuffer::Iter::Iter(const scoped_refptr<ROBuffer>& buffer) {
  Reset(buffer.get());
}

void ROBuffer::Iter::Reset(const ROBuffer* buffer) {
  buffer_ = buffer;
  if (buffer && buffer->head_) {
    block_ = &buffer->head_->block_;
    remaining_ = buffer->available_;
  } else {
    block_ = nullptr;
    remaining_ = 0;
  }
}

base::span<const uint8_t> ROBuffer::Iter::operator*() const {
  if (!remaining_) {
    return {};
  }
  DCHECK(block_);
  return block_->Buffer().first(std::min(block_->capacity_, remaining_));
}

bool ROBuffer::Iter::Next() {
  if (remaining_) {
    const size_t current_size = std::min(block_->capacity_, remaining_);
    remaining_ -= current_size;
    if (buffer_->tail_ == block_) {
      // There are more blocks, but buffer_ does not know about them.
      DCHECK_EQ(0u, remaining_);
      block_ = nullptr;
    } else {
      block_ = block_->next_;
    }
  }
  return remaining_ != 0;
}

///////////////////////////////////////////////////////////////////////////////////////////////////

RWBuffer::RWBuffer(size_t initial_capacity) {
  if (initial_capacity) {
    head_ = RWBuffer::BufferHead::Alloc(initial_capacity);
    tail_ = &head_->block_;
  }
}

RWBuffer::RWBuffer(base::OnceCallback<size_t(base::span<uint8_t>)> writer,
                   size_t initial_capacity) {
  if (initial_capacity) {
    head_ = RWBuffer::BufferHead::Alloc(initial_capacity);
    tail_ = &head_->block_;
  }

  size_t written =
      std::move(writer).Run(tail_->Buffer().first(initial_capacity));
  total_used_ += written;
  tail_->used_ += written;

  Validate();
}

RWBuffer::~RWBuffer() {
  Validate();
  if (head_) {
    tail_ = nullptr;
    head_.ExtractAsDangling()->unref();
  }
}

// It is important that we always completely fill the current block before
// spilling over to the next, since our reader will be using capacity_ (min'd
// against its total available) to know how many bytes to read from a given
// block.
//
void RWBuffer::Append(base::span<const uint8_t> src, size_t reserve) {
  Validate();
  if (src.empty()) {
    return;
  }

  total_used_ += src.size();

  if (!head_) {
    head_ = RWBuffer::BufferHead::Alloc(src.size() + reserve);
    tail_ = &head_->block_;
  }

  size_t written = tail_->Append(src);
  DCHECK_LE(written, src.size());
  src = src.subspan(written);

  if (!src.empty()) {
    auto* block = RWBuffer::BufferBlock::Alloc(src.size() + reserve);
    tail_->next_ = block;
    tail_ = block;
    written = tail_->Append(src);
    DCHECK_EQ(written, src.size());
  }
  Validate();
}

scoped_refptr<ROBuffer> RWBuffer::MakeROBufferSnapshot() const {
  return AdoptRef(new ROBuffer(head_, total_used_, tail_));
}

bool RWBuffer::HasNoSnapshots() const {
  // Trivially, there are no other references to the underlying buffer, because
  // there is no underlying buffer.
  if (!head_) {
    return true;
  }

  return head_->ref_count_.IsOne();
}

void RWBuffer::Validate() const {
#if DCHECK_IS_ON()
  if (head_) {
    head_->Validate(total_used_, tail_);
  } else {
    DCHECK(!tail_);
    DCHECK_EQ(0u, total_used_);
  }
#endif
}

}  // namespace blink