blob: 6663c687b850346012191adbdd00ad9ff9b1caa2 [file] [log] [blame]
henrike@webrtc.orgf0488722014-05-13 18:00:261/*
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 04:47:3111#ifndef RTC_BASE_BUFFER_H_
12#define RTC_BASE_BUFFER_H_
henrike@webrtc.orgf0488722014-05-13 18:00:2613
Yves Gerey3e707812018-11-28 15:47:4914#include <stdint.h>
Jonas Olssona4d87372019-07-05 17:08:3315
Henrik Kjellanderec78f1c2017-06-29 05:52:5016#include <algorithm>
17#include <cstring>
18#include <memory>
19#include <type_traits>
20#include <utility>
21
Ali Tofighfd6a4d62022-03-31 08:36:4822#include "absl/strings/string_view.h"
Mirko Bonadei92ea95e2017-09-15 04:47:3123#include "api/array_view.h"
24#include "rtc_base/checks.h"
25#include "rtc_base/type_traits.h"
Joachim Bauch5b32f232018-03-07 19:02:2626#include "rtc_base/zero_memory.h"
Henrik Kjellanderec78f1c2017-06-29 05:52:5027
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 19:02:2651// 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 05:52:5055class 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 13:31:3968 using const_iterator = const T*;
Henrik Kjellanderec78f1c2017-06-29 05:52:5069
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-02 22:03:1794 data_(capacity_ > 0 ? new T[capacity_] : nullptr) {
Henrik Kjellanderec78f1c2017-06-29 05:52:5095 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), "");
Mirko Bonadei7103e702022-08-17 14:24:46109 if (size > 0) {
110 RTC_DCHECK(data);
111 std::memcpy(data_.get(), data, size * sizeof(U));
112 }
Henrik Kjellanderec78f1c2017-06-29 05:52:50113 }
114
115 // Construct a buffer from the contents of an array.
116 template <typename U,
117 size_t N,
118 typename std::enable_if<
119 internal::BufferCompat<T, U>::value>::type* = nullptr>
120 BufferT(U (&array)[N]) : BufferT(array, N) {}
121
Joachim Bauch5b32f232018-03-07 19:02:26122 ~BufferT() { MaybeZeroCompleteBuffer(); }
123
Ali Tofighfd6a4d62022-03-31 08:36:48124 // Implicit conversion to absl::string_view if T is compatible with char.
125 template <typename U = T>
126 operator typename std::enable_if<internal::BufferCompat<U, char>::value,
127 absl::string_view>::type() const {
128 return absl::string_view(data<char>(), size());
129 }
130
Henrik Kjellanderec78f1c2017-06-29 05:52:50131 // Get a pointer to the data. Just .data() will give you a (const) T*, but if
132 // T is a byte-sized integer, you may also use .data<U>() for any other
133 // byte-sized integer U.
134 template <typename U = T,
135 typename std::enable_if<
136 internal::BufferCompat<T, U>::value>::type* = nullptr>
137 const U* data() const {
138 RTC_DCHECK(IsConsistent());
139 return reinterpret_cast<U*>(data_.get());
140 }
141
142 template <typename U = T,
143 typename std::enable_if<
144 internal::BufferCompat<T, U>::value>::type* = nullptr>
145 U* data() {
146 RTC_DCHECK(IsConsistent());
147 return reinterpret_cast<U*>(data_.get());
148 }
149
150 bool empty() const {
151 RTC_DCHECK(IsConsistent());
152 return size_ == 0;
153 }
154
155 size_t size() const {
156 RTC_DCHECK(IsConsistent());
157 return size_;
158 }
159
160 size_t capacity() const {
161 RTC_DCHECK(IsConsistent());
162 return capacity_;
163 }
164
165 BufferT& operator=(BufferT&& buf) {
Henrik Kjellanderec78f1c2017-06-29 05:52:50166 RTC_DCHECK(buf.IsConsistent());
Karl Wiberg9d247952018-10-10 10:52:17167 MaybeZeroCompleteBuffer();
Henrik Kjellanderec78f1c2017-06-29 05:52:50168 size_ = buf.size_;
169 capacity_ = buf.capacity_;
Karl Wiberg4f3ce272018-10-17 11:34:33170 using std::swap;
171 swap(data_, buf.data_);
172 buf.data_.reset();
Henrik Kjellanderec78f1c2017-06-29 05:52:50173 buf.OnMovedFrom();
174 return *this;
175 }
176
177 bool operator==(const BufferT& buf) const {
178 RTC_DCHECK(IsConsistent());
179 if (size_ != buf.size_) {
180 return false;
181 }
182 if (std::is_integral<T>::value) {
183 // Optimization.
184 return std::memcmp(data_.get(), buf.data_.get(), size_ * sizeof(T)) == 0;
185 }
186 for (size_t i = 0; i < size_; ++i) {
187 if (data_[i] != buf.data_[i]) {
188 return false;
189 }
190 }
191 return true;
192 }
193
194 bool operator!=(const BufferT& buf) const { return !(*this == buf); }
195
196 T& operator[](size_t index) {
197 RTC_DCHECK_LT(index, size_);
198 return data()[index];
199 }
200
201 T operator[](size_t index) const {
202 RTC_DCHECK_LT(index, size_);
203 return data()[index];
204 }
205
206 T* begin() { return data(); }
207 T* end() { return data() + size(); }
208 const T* begin() const { return data(); }
209 const T* end() const { return data() + size(); }
210 const T* cbegin() const { return data(); }
211 const T* cend() const { return data() + size(); }
212
213 // The SetData functions replace the contents of the buffer. They accept the
214 // same input types as the constructors.
215 template <typename U,
216 typename std::enable_if<
217 internal::BufferCompat<T, U>::value>::type* = nullptr>
218 void SetData(const U* data, size_t size) {
219 RTC_DCHECK(IsConsistent());
Joachim Bauch5b32f232018-03-07 19:02:26220 const size_t old_size = size_;
Henrik Kjellanderec78f1c2017-06-29 05:52:50221 size_ = 0;
222 AppendData(data, size);
Joachim Bauch5b32f232018-03-07 19:02:26223 if (ZeroOnFree && size_ < old_size) {
224 ZeroTrailingData(old_size - size_);
225 }
Henrik Kjellanderec78f1c2017-06-29 05:52:50226 }
227
228 template <typename U,
229 size_t N,
230 typename std::enable_if<
231 internal::BufferCompat<T, U>::value>::type* = nullptr>
232 void SetData(const U (&array)[N]) {
233 SetData(array, N);
234 }
235
236 template <typename W,
237 typename std::enable_if<
238 HasDataAndSize<const W, const T>::value>::type* = nullptr>
239 void SetData(const W& w) {
240 SetData(w.data(), w.size());
241 }
242
Artem Titov96e3b992021-07-26 14:03:14243 // Replaces the data in the buffer with at most `max_elements` of data, using
244 // the function `setter`, which should have the following signature:
Karl Wiberg09819ec2017-11-24 12:26:32245 //
Henrik Kjellanderec78f1c2017-06-29 05:52:50246 // size_t setter(ArrayView<U> view)
Karl Wiberg09819ec2017-11-24 12:26:32247 //
Artem Titov96e3b992021-07-26 14:03:14248 // `setter` is given an appropriately typed ArrayView of length exactly
249 // `max_elements` that describes the area where it should write the data; it
Karl Wiberg09819ec2017-11-24 12:26:32250 // should return the number of elements actually written. (If it doesn't fill
251 // the whole ArrayView, it should leave the unused space at the end.)
Henrik Kjellanderec78f1c2017-06-29 05:52:50252 template <typename U = T,
253 typename F,
254 typename std::enable_if<
255 internal::BufferCompat<T, U>::value>::type* = nullptr>
256 size_t SetData(size_t max_elements, F&& setter) {
257 RTC_DCHECK(IsConsistent());
Joachim Bauch5b32f232018-03-07 19:02:26258 const size_t old_size = size_;
Henrik Kjellanderec78f1c2017-06-29 05:52:50259 size_ = 0;
Joachim Bauch5b32f232018-03-07 19:02:26260 const size_t written = AppendData<U>(max_elements, std::forward<F>(setter));
261 if (ZeroOnFree && size_ < old_size) {
262 ZeroTrailingData(old_size - size_);
263 }
264 return written;
Henrik Kjellanderec78f1c2017-06-29 05:52:50265 }
266
267 // The AppendData functions add data to the end of the buffer. They accept
268 // the same input types as the constructors.
269 template <typename U,
270 typename std::enable_if<
271 internal::BufferCompat<T, U>::value>::type* = nullptr>
272 void AppendData(const U* data, size_t size) {
Mirko Bonadei7103e702022-08-17 14:24:46273 if (size == 0) {
Mirko Bonadei48ac38e2022-08-15 08:20:44274 return;
275 }
Mirko Bonadei7103e702022-08-17 14:24:46276 RTC_DCHECK(data);
Henrik Kjellanderec78f1c2017-06-29 05:52:50277 RTC_DCHECK(IsConsistent());
278 const size_t new_size = size_ + size;
279 EnsureCapacityWithHeadroom(new_size, true);
280 static_assert(sizeof(T) == sizeof(U), "");
281 std::memcpy(data_.get() + size_, data, size * sizeof(U));
282 size_ = new_size;
283 RTC_DCHECK(IsConsistent());
284 }
285
286 template <typename U,
287 size_t N,
288 typename std::enable_if<
289 internal::BufferCompat<T, U>::value>::type* = nullptr>
290 void AppendData(const U (&array)[N]) {
291 AppendData(array, N);
292 }
293
294 template <typename W,
295 typename std::enable_if<
296 HasDataAndSize<const W, const T>::value>::type* = nullptr>
297 void AppendData(const W& w) {
298 AppendData(w.data(), w.size());
299 }
300
301 template <typename U,
302 typename std::enable_if<
303 internal::BufferCompat<T, U>::value>::type* = nullptr>
304 void AppendData(const U& item) {
305 AppendData(&item, 1);
306 }
307
Artem Titov96e3b992021-07-26 14:03:14308 // Appends at most `max_elements` to the end of the buffer, using the function
309 // `setter`, which should have the following signature:
Karl Wiberg09819ec2017-11-24 12:26:32310 //
Henrik Kjellanderec78f1c2017-06-29 05:52:50311 // size_t setter(ArrayView<U> view)
Karl Wiberg09819ec2017-11-24 12:26:32312 //
Artem Titov96e3b992021-07-26 14:03:14313 // `setter` is given an appropriately typed ArrayView of length exactly
314 // `max_elements` that describes the area where it should write the data; it
Karl Wiberg09819ec2017-11-24 12:26:32315 // should return the number of elements actually written. (If it doesn't fill
316 // the whole ArrayView, it should leave the unused space at the end.)
Henrik Kjellanderec78f1c2017-06-29 05:52:50317 template <typename U = T,
318 typename F,
319 typename std::enable_if<
320 internal::BufferCompat<T, U>::value>::type* = nullptr>
321 size_t AppendData(size_t max_elements, F&& setter) {
322 RTC_DCHECK(IsConsistent());
323 const size_t old_size = size_;
324 SetSize(old_size + max_elements);
325 U* base_ptr = data<U>() + old_size;
326 size_t written_elements = setter(rtc::ArrayView<U>(base_ptr, max_elements));
327
328 RTC_CHECK_LE(written_elements, max_elements);
329 size_ = old_size + written_elements;
330 RTC_DCHECK(IsConsistent());
331 return written_elements;
332 }
333
334 // Sets the size of the buffer. If the new size is smaller than the old, the
335 // buffer contents will be kept but truncated; if the new size is greater,
336 // the existing contents will be kept and the new space will be
337 // uninitialized.
338 void SetSize(size_t size) {
Joachim Bauch5b32f232018-03-07 19:02:26339 const size_t old_size = size_;
Henrik Kjellanderec78f1c2017-06-29 05:52:50340 EnsureCapacityWithHeadroom(size, true);
341 size_ = size;
Joachim Bauch5b32f232018-03-07 19:02:26342 if (ZeroOnFree && size_ < old_size) {
343 ZeroTrailingData(old_size - size_);
344 }
Henrik Kjellanderec78f1c2017-06-29 05:52:50345 }
346
347 // Ensure that the buffer size can be increased to at least capacity without
348 // further reallocation. (Of course, this operation might need to reallocate
349 // the buffer.)
350 void EnsureCapacity(size_t capacity) {
351 // Don't allocate extra headroom, since the user is asking for a specific
352 // capacity.
353 EnsureCapacityWithHeadroom(capacity, false);
354 }
355
356 // Resets the buffer to zero size without altering capacity. Works even if the
357 // buffer has been moved from.
358 void Clear() {
Joachim Bauch5b32f232018-03-07 19:02:26359 MaybeZeroCompleteBuffer();
Henrik Kjellanderec78f1c2017-06-29 05:52:50360 size_ = 0;
361 RTC_DCHECK(IsConsistent());
362 }
363
364 // Swaps two buffers. Also works for buffers that have been moved from.
365 friend void swap(BufferT& a, BufferT& b) {
366 using std::swap;
367 swap(a.size_, b.size_);
368 swap(a.capacity_, b.capacity_);
369 swap(a.data_, b.data_);
370 }
371
372 private:
373 void EnsureCapacityWithHeadroom(size_t capacity, bool extra_headroom) {
374 RTC_DCHECK(IsConsistent());
375 if (capacity <= capacity_)
376 return;
377
378 // If the caller asks for extra headroom, ensure that the new capacity is
379 // >= 1.5 times the old capacity. Any constant > 1 is sufficient to prevent
380 // quadratic behavior; as to why we pick 1.5 in particular, see
381 // https://github.com/facebook/folly/blob/master/folly/docs/FBVector.md and
382 // http://www.gahcep.com/cpp-internals-stl-vector-part-1/.
383 const size_t new_capacity =
384 extra_headroom ? std::max(capacity, capacity_ + capacity_ / 2)
385 : capacity;
386
387 std::unique_ptr<T[]> new_data(new T[new_capacity]);
Dan Minorb164e702020-05-28 13:21:42388 if (data_ != nullptr) {
389 std::memcpy(new_data.get(), data_.get(), size_ * sizeof(T));
390 }
Joachim Bauch5b32f232018-03-07 19:02:26391 MaybeZeroCompleteBuffer();
Henrik Kjellanderec78f1c2017-06-29 05:52:50392 data_ = std::move(new_data);
393 capacity_ = new_capacity;
394 RTC_DCHECK(IsConsistent());
395 }
396
Joachim Bauch5b32f232018-03-07 19:02:26397 // Zero the complete buffer if template argument "ZeroOnFree" is true.
398 void MaybeZeroCompleteBuffer() {
Karl Wiberg9d247952018-10-10 10:52:17399 if (ZeroOnFree && capacity_ > 0) {
Joachim Bauch5b32f232018-03-07 19:02:26400 // It would be sufficient to only zero "size_" elements, as all other
401 // methods already ensure that the unused capacity contains no sensitive
Karl Wiberg9d247952018-10-10 10:52:17402 // data---but better safe than sorry.
Joachim Bauch5b32f232018-03-07 19:02:26403 ExplicitZeroMemory(data_.get(), capacity_ * sizeof(T));
404 }
405 }
406
407 // Zero the first "count" elements of unused capacity.
408 void ZeroTrailingData(size_t count) {
409 RTC_DCHECK(IsConsistent());
410 RTC_DCHECK_LE(count, capacity_ - size_);
411 ExplicitZeroMemory(data_.get() + size_, count * sizeof(T));
412 }
413
Karl Wibergb3b01792018-10-10 10:44:12414 // Precondition for all methods except Clear, operator= and the destructor.
Henrik Kjellanderec78f1c2017-06-29 05:52:50415 // Postcondition for all methods except move construction and move
416 // assignment, which leave the moved-from object in a possibly inconsistent
417 // state.
418 bool IsConsistent() const {
419 return (data_ || capacity_ == 0) && capacity_ >= size_;
420 }
421
422 // Called when *this has been moved from. Conceptually it's a no-op, but we
423 // can mutate the state slightly to help subsequent sanity checks catch bugs.
424 void OnMovedFrom() {
Karl Wiberg4f3ce272018-10-17 11:34:33425 RTC_DCHECK(!data_); // Our heap block should have been stolen.
Henrik Kjellanderec78f1c2017-06-29 05:52:50426#if RTC_DCHECK_IS_ON
Karl Wibergb3b01792018-10-10 10:44:12427 // Ensure that *this is always inconsistent, to provoke bugs.
428 size_ = 1;
429 capacity_ = 0;
430#else
Henrik Kjellanderec78f1c2017-06-29 05:52:50431 // Make *this consistent and empty. Shouldn't be necessary, but better safe
432 // than sorry.
433 size_ = 0;
434 capacity_ = 0;
Henrik Kjellanderec78f1c2017-06-29 05:52:50435#endif
436 }
437
438 size_t size_;
439 size_t capacity_;
440 std::unique_ptr<T[]> data_;
441};
442
443// By far the most common sort of buffer.
444using Buffer = BufferT<uint8_t>;
445
Joachim Bauch5b32f232018-03-07 19:02:26446// A buffer that zeros memory before releasing it.
447template <typename T>
448using ZeroOnFreeBuffer = BufferT<T, true>;
449
Henrik Kjellanderec78f1c2017-06-29 05:52:50450} // namespace rtc
henrike@webrtc.orgf0488722014-05-13 18:00:26451
Mirko Bonadei92ea95e2017-09-15 04:47:31452#endif // RTC_BASE_BUFFER_H_