blob: 819e7db3a6a44072a95c553650141944c8b9469e [file] [log] [blame]
henrike@webrtc.orgf0488722014-05-13 18:00:26 +00001/*
2 * Copyright 2004 The WebRTC Project Authors. All rights reserved.
3 *
4 * Use of this source code is governed by a BSD-style license
5 * that can be found in the LICENSE file in the root of the source
6 * tree. An additional intellectual property rights grant can be found
7 * in the file PATENTS. All contributing project authors may
8 * be found in the AUTHORS file in the root of the source tree.
9 */
10
Mirko Bonadei92ea95e2017-09-15 06:47:31 +020011#ifndef RTC_BASE_BUFFER_H_
12#define RTC_BASE_BUFFER_H_
henrike@webrtc.orgf0488722014-05-13 18:00:26 +000013
Yves Gerey3e707812018-11-28 16:47:49 +010014#include <stdint.h>
Jonas Olssona4d87372019-07-05 19:08:33 +020015
Henrik Kjellanderec78f1c2017-06-29 07:52:50 +020016#include <algorithm>
17#include <cstring>
18#include <memory>
19#include <type_traits>
20#include <utility>
21
Ali Tofighfd6a4d62022-03-31 10:36:48 +020022#include "absl/strings/string_view.h"
Mirko Bonadei92ea95e2017-09-15 06:47:31 +020023#include "api/array_view.h"
24#include "rtc_base/checks.h"
25#include "rtc_base/type_traits.h"
Joachim Bauch5b32f232018-03-07 20:02:26 +010026#include "rtc_base/zero_memory.h"
Henrik Kjellanderec78f1c2017-06-29 07:52:50 +020027
28namespace rtc {
29
30namespace internal {
31
32// (Internal; please don't use outside this file.) Determines if elements of
33// type U are compatible with a BufferT<T>. For most types, we just ignore
34// top-level const and forbid top-level volatile and require T and U to be
35// otherwise equal, but all byte-sized integers (notably char, int8_t, and
36// uint8_t) are compatible with each other. (Note: We aim to get rid of this
37// behavior, and treat all types the same.)
38template <typename T, typename U>
39struct BufferCompat {
40 static constexpr bool value =
41 !std::is_volatile<U>::value &&
42 ((std::is_integral<T>::value && sizeof(T) == 1)
43 ? (std::is_integral<U>::value && sizeof(U) == 1)
44 : (std::is_same<T, typename std::remove_const<U>::type>::value));
45};
46
47} // namespace internal
48
49// Basic buffer class, can be grown and shrunk dynamically.
50// Unlike std::string/vector, does not initialize data when increasing size.
Joachim Bauch5b32f232018-03-07 20:02:26 +010051// If "ZeroOnFree" is true, any memory is explicitly cleared before releasing.
52// The type alias "ZeroOnFreeBuffer" below should be used instead of setting
53// "ZeroOnFree" in the template manually to "true".
54template <typename T, bool ZeroOnFree = false>
Henrik Kjellanderec78f1c2017-06-29 07:52:50 +020055class BufferT {
56 // We want T's destructor and default constructor to be trivial, i.e. perform
57 // no action, so that we don't have to touch the memory we allocate and
58 // deallocate. And we want T to be trivially copyable, so that we can copy T
59 // instances with std::memcpy. This is precisely the definition of a trivial
60 // type.
61 static_assert(std::is_trivial<T>::value, "T must be a trivial type.");
62
63 // This class relies heavily on being able to mutate its data.
64 static_assert(!std::is_const<T>::value, "T may not be const");
65
66 public:
67 using value_type = T;
Karl Wiberg215963c2020-02-04 14:31:39 +010068 using const_iterator = const T*;
Henrik Kjellanderec78f1c2017-06-29 07:52:50 +020069
70 // An empty BufferT.
71 BufferT() : size_(0), capacity_(0), data_(nullptr) {
72 RTC_DCHECK(IsConsistent());
73 }
74
75 // Disable copy construction and copy assignment, since copying a buffer is
76 // expensive enough that we want to force the user to be explicit about it.
77 BufferT(const BufferT&) = delete;
78 BufferT& operator=(const BufferT&) = delete;
79
80 BufferT(BufferT&& buf)
81 : size_(buf.size()),
82 capacity_(buf.capacity()),
83 data_(std::move(buf.data_)) {
84 RTC_DCHECK(IsConsistent());
85 buf.OnMovedFrom();
86 }
87
88 // Construct a buffer with the specified number of uninitialized elements.
89 explicit BufferT(size_t size) : BufferT(size, size) {}
90
91 BufferT(size_t size, size_t capacity)
92 : size_(size),
93 capacity_(std::max(size, capacity)),
Oleh Prypin7d984ee2018-08-03 00:03:17 +020094 data_(capacity_ > 0 ? new T[capacity_] : nullptr) {
Henrik Kjellanderec78f1c2017-06-29 07:52:50 +020095 RTC_DCHECK(IsConsistent());
96 }
97
98 // Construct a buffer and copy the specified number of elements into it.
99 template <typename U,
100 typename std::enable_if<
101 internal::BufferCompat<T, U>::value>::type* = nullptr>
102 BufferT(const U* data, size_t size) : BufferT(data, size, size) {}
103
104 template <typename U,
105 typename std::enable_if<
106 internal::BufferCompat<T, U>::value>::type* = nullptr>
107 BufferT(U* data, size_t size, size_t capacity) : BufferT(size, capacity) {
108 static_assert(sizeof(T) == sizeof(U), "");
109 std::memcpy(data_.get(), data, size * sizeof(U));
110 }
111
112 // Construct a buffer from the contents of an array.
113 template <typename U,
114 size_t N,
115 typename std::enable_if<
116 internal::BufferCompat<T, U>::value>::type* = nullptr>
117 BufferT(U (&array)[N]) : BufferT(array, N) {}
118
Joachim Bauch5b32f232018-03-07 20:02:26 +0100119 ~BufferT() { MaybeZeroCompleteBuffer(); }
120
Ali Tofighfd6a4d62022-03-31 10:36:48 +0200121 // Implicit conversion to absl::string_view if T is compatible with char.
122 template <typename U = T>
123 operator typename std::enable_if<internal::BufferCompat<U, char>::value,
124 absl::string_view>::type() const {
125 return absl::string_view(data<char>(), size());
126 }
127
Henrik Kjellanderec78f1c2017-06-29 07:52:50 +0200128 // Get a pointer to the data. Just .data() will give you a (const) T*, but if
129 // T is a byte-sized integer, you may also use .data<U>() for any other
130 // byte-sized integer U.
131 template <typename U = T,
132 typename std::enable_if<
133 internal::BufferCompat<T, U>::value>::type* = nullptr>
134 const U* data() const {
135 RTC_DCHECK(IsConsistent());
136 return reinterpret_cast<U*>(data_.get());
137 }
138
139 template <typename U = T,
140 typename std::enable_if<
141 internal::BufferCompat<T, U>::value>::type* = nullptr>
142 U* data() {
143 RTC_DCHECK(IsConsistent());
144 return reinterpret_cast<U*>(data_.get());
145 }
146
147 bool empty() const {
148 RTC_DCHECK(IsConsistent());
149 return size_ == 0;
150 }
151
152 size_t size() const {
153 RTC_DCHECK(IsConsistent());
154 return size_;
155 }
156
157 size_t capacity() const {
158 RTC_DCHECK(IsConsistent());
159 return capacity_;
160 }
161
162 BufferT& operator=(BufferT&& buf) {
Henrik Kjellanderec78f1c2017-06-29 07:52:50 +0200163 RTC_DCHECK(buf.IsConsistent());
Karl Wiberg9d247952018-10-10 12:52:17 +0200164 MaybeZeroCompleteBuffer();
Henrik Kjellanderec78f1c2017-06-29 07:52:50 +0200165 size_ = buf.size_;
166 capacity_ = buf.capacity_;
Karl Wiberg4f3ce272018-10-17 13:34:33 +0200167 using std::swap;
168 swap(data_, buf.data_);
169 buf.data_.reset();
Henrik Kjellanderec78f1c2017-06-29 07:52:50 +0200170 buf.OnMovedFrom();
171 return *this;
172 }
173
174 bool operator==(const BufferT& buf) const {
175 RTC_DCHECK(IsConsistent());
176 if (size_ != buf.size_) {
177 return false;
178 }
179 if (std::is_integral<T>::value) {
180 // Optimization.
181 return std::memcmp(data_.get(), buf.data_.get(), size_ * sizeof(T)) == 0;
182 }
183 for (size_t i = 0; i < size_; ++i) {
184 if (data_[i] != buf.data_[i]) {
185 return false;
186 }
187 }
188 return true;
189 }
190
191 bool operator!=(const BufferT& buf) const { return !(*this == buf); }
192
193 T& operator[](size_t index) {
194 RTC_DCHECK_LT(index, size_);
195 return data()[index];
196 }
197
198 T operator[](size_t index) const {
199 RTC_DCHECK_LT(index, size_);
200 return data()[index];
201 }
202
203 T* begin() { return data(); }
204 T* end() { return data() + size(); }
205 const T* begin() const { return data(); }
206 const T* end() const { return data() + size(); }
207 const T* cbegin() const { return data(); }
208 const T* cend() const { return data() + size(); }
209
210 // The SetData functions replace the contents of the buffer. They accept the
211 // same input types as the constructors.
212 template <typename U,
213 typename std::enable_if<
214 internal::BufferCompat<T, U>::value>::type* = nullptr>
215 void SetData(const U* data, size_t size) {
216 RTC_DCHECK(IsConsistent());
Joachim Bauch5b32f232018-03-07 20:02:26 +0100217 const size_t old_size = size_;
Henrik Kjellanderec78f1c2017-06-29 07:52:50 +0200218 size_ = 0;
219 AppendData(data, size);
Joachim Bauch5b32f232018-03-07 20:02:26 +0100220 if (ZeroOnFree && size_ < old_size) {
221 ZeroTrailingData(old_size - size_);
222 }
Henrik Kjellanderec78f1c2017-06-29 07:52:50 +0200223 }
224
225 template <typename U,
226 size_t N,
227 typename std::enable_if<
228 internal::BufferCompat<T, U>::value>::type* = nullptr>
229 void SetData(const U (&array)[N]) {
230 SetData(array, N);
231 }
232
233 template <typename W,
234 typename std::enable_if<
235 HasDataAndSize<const W, const T>::value>::type* = nullptr>
236 void SetData(const W& w) {
237 SetData(w.data(), w.size());
238 }
239
Artem Titov96e3b992021-07-26 16:03:14 +0200240 // Replaces the data in the buffer with at most `max_elements` of data, using
241 // the function `setter`, which should have the following signature:
Karl Wiberg09819ec2017-11-24 13:26:32 +0100242 //
Henrik Kjellanderec78f1c2017-06-29 07:52:50 +0200243 // size_t setter(ArrayView<U> view)
Karl Wiberg09819ec2017-11-24 13:26:32 +0100244 //
Artem Titov96e3b992021-07-26 16:03:14 +0200245 // `setter` is given an appropriately typed ArrayView of length exactly
246 // `max_elements` that describes the area where it should write the data; it
Karl Wiberg09819ec2017-11-24 13:26:32 +0100247 // should return the number of elements actually written. (If it doesn't fill
248 // the whole ArrayView, it should leave the unused space at the end.)
Henrik Kjellanderec78f1c2017-06-29 07:52:50 +0200249 template <typename U = T,
250 typename F,
251 typename std::enable_if<
252 internal::BufferCompat<T, U>::value>::type* = nullptr>
253 size_t SetData(size_t max_elements, F&& setter) {
254 RTC_DCHECK(IsConsistent());
Joachim Bauch5b32f232018-03-07 20:02:26 +0100255 const size_t old_size = size_;
Henrik Kjellanderec78f1c2017-06-29 07:52:50 +0200256 size_ = 0;
Joachim Bauch5b32f232018-03-07 20:02:26 +0100257 const size_t written = AppendData<U>(max_elements, std::forward<F>(setter));
258 if (ZeroOnFree && size_ < old_size) {
259 ZeroTrailingData(old_size - size_);
260 }
261 return written;
Henrik Kjellanderec78f1c2017-06-29 07:52:50 +0200262 }
263
264 // The AppendData functions add data to the end of the buffer. They accept
265 // the same input types as the constructors.
266 template <typename U,
267 typename std::enable_if<
268 internal::BufferCompat<T, U>::value>::type* = nullptr>
269 void AppendData(const U* data, size_t size) {
Mirko Bonadei48ac38e2022-08-15 08:20:44 +0000270 if (!data) {
271 RTC_CHECK_EQ(size, 0U);
272 return;
273 }
Henrik Kjellanderec78f1c2017-06-29 07:52:50 +0200274 RTC_DCHECK(IsConsistent());
275 const size_t new_size = size_ + size;
276 EnsureCapacityWithHeadroom(new_size, true);
277 static_assert(sizeof(T) == sizeof(U), "");
278 std::memcpy(data_.get() + size_, data, size * sizeof(U));
279 size_ = new_size;
280 RTC_DCHECK(IsConsistent());
281 }
282
283 template <typename U,
284 size_t N,
285 typename std::enable_if<
286 internal::BufferCompat<T, U>::value>::type* = nullptr>
287 void AppendData(const U (&array)[N]) {
288 AppendData(array, N);
289 }
290
291 template <typename W,
292 typename std::enable_if<
293 HasDataAndSize<const W, const T>::value>::type* = nullptr>
294 void AppendData(const W& w) {
295 AppendData(w.data(), w.size());
296 }
297
298 template <typename U,
299 typename std::enable_if<
300 internal::BufferCompat<T, U>::value>::type* = nullptr>
301 void AppendData(const U& item) {
302 AppendData(&item, 1);
303 }
304
Artem Titov96e3b992021-07-26 16:03:14 +0200305 // Appends at most `max_elements` to the end of the buffer, using the function
306 // `setter`, which should have the following signature:
Karl Wiberg09819ec2017-11-24 13:26:32 +0100307 //
Henrik Kjellanderec78f1c2017-06-29 07:52:50 +0200308 // size_t setter(ArrayView<U> view)
Karl Wiberg09819ec2017-11-24 13:26:32 +0100309 //
Artem Titov96e3b992021-07-26 16:03:14 +0200310 // `setter` is given an appropriately typed ArrayView of length exactly
311 // `max_elements` that describes the area where it should write the data; it
Karl Wiberg09819ec2017-11-24 13:26:32 +0100312 // should return the number of elements actually written. (If it doesn't fill
313 // the whole ArrayView, it should leave the unused space at the end.)
Henrik Kjellanderec78f1c2017-06-29 07:52:50 +0200314 template <typename U = T,
315 typename F,
316 typename std::enable_if<
317 internal::BufferCompat<T, U>::value>::type* = nullptr>
318 size_t AppendData(size_t max_elements, F&& setter) {
319 RTC_DCHECK(IsConsistent());
320 const size_t old_size = size_;
321 SetSize(old_size + max_elements);
322 U* base_ptr = data<U>() + old_size;
323 size_t written_elements = setter(rtc::ArrayView<U>(base_ptr, max_elements));
324
325 RTC_CHECK_LE(written_elements, max_elements);
326 size_ = old_size + written_elements;
327 RTC_DCHECK(IsConsistent());
328 return written_elements;
329 }
330
331 // Sets the size of the buffer. If the new size is smaller than the old, the
332 // buffer contents will be kept but truncated; if the new size is greater,
333 // the existing contents will be kept and the new space will be
334 // uninitialized.
335 void SetSize(size_t size) {
Joachim Bauch5b32f232018-03-07 20:02:26 +0100336 const size_t old_size = size_;
Henrik Kjellanderec78f1c2017-06-29 07:52:50 +0200337 EnsureCapacityWithHeadroom(size, true);
338 size_ = size;
Joachim Bauch5b32f232018-03-07 20:02:26 +0100339 if (ZeroOnFree && size_ < old_size) {
340 ZeroTrailingData(old_size - size_);
341 }
Henrik Kjellanderec78f1c2017-06-29 07:52:50 +0200342 }
343
344 // Ensure that the buffer size can be increased to at least capacity without
345 // further reallocation. (Of course, this operation might need to reallocate
346 // the buffer.)
347 void EnsureCapacity(size_t capacity) {
348 // Don't allocate extra headroom, since the user is asking for a specific
349 // capacity.
350 EnsureCapacityWithHeadroom(capacity, false);
351 }
352
353 // Resets the buffer to zero size without altering capacity. Works even if the
354 // buffer has been moved from.
355 void Clear() {
Joachim Bauch5b32f232018-03-07 20:02:26 +0100356 MaybeZeroCompleteBuffer();
Henrik Kjellanderec78f1c2017-06-29 07:52:50 +0200357 size_ = 0;
358 RTC_DCHECK(IsConsistent());
359 }
360
361 // Swaps two buffers. Also works for buffers that have been moved from.
362 friend void swap(BufferT& a, BufferT& b) {
363 using std::swap;
364 swap(a.size_, b.size_);
365 swap(a.capacity_, b.capacity_);
366 swap(a.data_, b.data_);
367 }
368
369 private:
370 void EnsureCapacityWithHeadroom(size_t capacity, bool extra_headroom) {
371 RTC_DCHECK(IsConsistent());
372 if (capacity <= capacity_)
373 return;
374
375 // If the caller asks for extra headroom, ensure that the new capacity is
376 // >= 1.5 times the old capacity. Any constant > 1 is sufficient to prevent
377 // quadratic behavior; as to why we pick 1.5 in particular, see
378 // https://github.com/facebook/folly/blob/master/folly/docs/FBVector.md and
379 // http://www.gahcep.com/cpp-internals-stl-vector-part-1/.
380 const size_t new_capacity =
381 extra_headroom ? std::max(capacity, capacity_ + capacity_ / 2)
382 : capacity;
383
384 std::unique_ptr<T[]> new_data(new T[new_capacity]);
Dan Minorb164e702020-05-28 09:21:42 -0400385 if (data_ != nullptr) {
386 std::memcpy(new_data.get(), data_.get(), size_ * sizeof(T));
387 }
Joachim Bauch5b32f232018-03-07 20:02:26 +0100388 MaybeZeroCompleteBuffer();
Henrik Kjellanderec78f1c2017-06-29 07:52:50 +0200389 data_ = std::move(new_data);
390 capacity_ = new_capacity;
391 RTC_DCHECK(IsConsistent());
392 }
393
Joachim Bauch5b32f232018-03-07 20:02:26 +0100394 // Zero the complete buffer if template argument "ZeroOnFree" is true.
395 void MaybeZeroCompleteBuffer() {
Karl Wiberg9d247952018-10-10 12:52:17 +0200396 if (ZeroOnFree && capacity_ > 0) {
Joachim Bauch5b32f232018-03-07 20:02:26 +0100397 // It would be sufficient to only zero "size_" elements, as all other
398 // methods already ensure that the unused capacity contains no sensitive
Karl Wiberg9d247952018-10-10 12:52:17 +0200399 // data---but better safe than sorry.
Joachim Bauch5b32f232018-03-07 20:02:26 +0100400 ExplicitZeroMemory(data_.get(), capacity_ * sizeof(T));
401 }
402 }
403
404 // Zero the first "count" elements of unused capacity.
405 void ZeroTrailingData(size_t count) {
406 RTC_DCHECK(IsConsistent());
407 RTC_DCHECK_LE(count, capacity_ - size_);
408 ExplicitZeroMemory(data_.get() + size_, count * sizeof(T));
409 }
410
Karl Wibergb3b01792018-10-10 12:44:12 +0200411 // Precondition for all methods except Clear, operator= and the destructor.
Henrik Kjellanderec78f1c2017-06-29 07:52:50 +0200412 // Postcondition for all methods except move construction and move
413 // assignment, which leave the moved-from object in a possibly inconsistent
414 // state.
415 bool IsConsistent() const {
416 return (data_ || capacity_ == 0) && capacity_ >= size_;
417 }
418
419 // Called when *this has been moved from. Conceptually it's a no-op, but we
420 // can mutate the state slightly to help subsequent sanity checks catch bugs.
421 void OnMovedFrom() {
Karl Wiberg4f3ce272018-10-17 13:34:33 +0200422 RTC_DCHECK(!data_); // Our heap block should have been stolen.
Henrik Kjellanderec78f1c2017-06-29 07:52:50 +0200423#if RTC_DCHECK_IS_ON
Karl Wibergb3b01792018-10-10 12:44:12 +0200424 // Ensure that *this is always inconsistent, to provoke bugs.
425 size_ = 1;
426 capacity_ = 0;
427#else
Henrik Kjellanderec78f1c2017-06-29 07:52:50 +0200428 // Make *this consistent and empty. Shouldn't be necessary, but better safe
429 // than sorry.
430 size_ = 0;
431 capacity_ = 0;
Henrik Kjellanderec78f1c2017-06-29 07:52:50 +0200432#endif
433 }
434
435 size_t size_;
436 size_t capacity_;
437 std::unique_ptr<T[]> data_;
438};
439
440// By far the most common sort of buffer.
441using Buffer = BufferT<uint8_t>;
442
Joachim Bauch5b32f232018-03-07 20:02:26 +0100443// A buffer that zeros memory before releasing it.
444template <typename T>
445using ZeroOnFreeBuffer = BufferT<T, true>;
446
Henrik Kjellanderec78f1c2017-06-29 07:52:50 +0200447} // namespace rtc
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000448
Mirko Bonadei92ea95e2017-09-15 06:47:31 +0200449#endif // RTC_BASE_BUFFER_H_