blob: be8e22bf9fda714b45d1a5b50f592e60135af841 [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), "");
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 19:02:26119 ~BufferT() { MaybeZeroCompleteBuffer(); }
120
Ali Tofighfd6a4d62022-03-31 08:36:48121 // 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 05:52:50128 // 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 05:52:50163 RTC_DCHECK(buf.IsConsistent());
Karl Wiberg9d247952018-10-10 10:52:17164 MaybeZeroCompleteBuffer();
Henrik Kjellanderec78f1c2017-06-29 05:52:50165 size_ = buf.size_;
166 capacity_ = buf.capacity_;
Karl Wiberg4f3ce272018-10-17 11:34:33167 using std::swap;
168 swap(data_, buf.data_);
169 buf.data_.reset();
Henrik Kjellanderec78f1c2017-06-29 05:52:50170 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 19:02:26217 const size_t old_size = size_;
Henrik Kjellanderec78f1c2017-06-29 05:52:50218 size_ = 0;
219 AppendData(data, size);
Joachim Bauch5b32f232018-03-07 19:02:26220 if (ZeroOnFree && size_ < old_size) {
221 ZeroTrailingData(old_size - size_);
222 }
Henrik Kjellanderec78f1c2017-06-29 05:52:50223 }
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 14:03:14240 // 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 12:26:32242 //
Henrik Kjellanderec78f1c2017-06-29 05:52:50243 // size_t setter(ArrayView<U> view)
Karl Wiberg09819ec2017-11-24 12:26:32244 //
Artem Titov96e3b992021-07-26 14:03:14245 // `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 12:26:32247 // 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 05:52:50249 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 19:02:26255 const size_t old_size = size_;
Henrik Kjellanderec78f1c2017-06-29 05:52:50256 size_ = 0;
Joachim Bauch5b32f232018-03-07 19:02:26257 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 05:52:50262 }
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) {
270 RTC_DCHECK(IsConsistent());
271 const size_t new_size = size_ + size;
272 EnsureCapacityWithHeadroom(new_size, true);
273 static_assert(sizeof(T) == sizeof(U), "");
274 std::memcpy(data_.get() + size_, data, size * sizeof(U));
275 size_ = new_size;
276 RTC_DCHECK(IsConsistent());
277 }
278
279 template <typename U,
280 size_t N,
281 typename std::enable_if<
282 internal::BufferCompat<T, U>::value>::type* = nullptr>
283 void AppendData(const U (&array)[N]) {
284 AppendData(array, N);
285 }
286
287 template <typename W,
288 typename std::enable_if<
289 HasDataAndSize<const W, const T>::value>::type* = nullptr>
290 void AppendData(const W& w) {
291 AppendData(w.data(), w.size());
292 }
293
294 template <typename U,
295 typename std::enable_if<
296 internal::BufferCompat<T, U>::value>::type* = nullptr>
297 void AppendData(const U& item) {
298 AppendData(&item, 1);
299 }
300
Artem Titov96e3b992021-07-26 14:03:14301 // Appends at most `max_elements` to the end of the buffer, using the function
302 // `setter`, which should have the following signature:
Karl Wiberg09819ec2017-11-24 12:26:32303 //
Henrik Kjellanderec78f1c2017-06-29 05:52:50304 // size_t setter(ArrayView<U> view)
Karl Wiberg09819ec2017-11-24 12:26:32305 //
Artem Titov96e3b992021-07-26 14:03:14306 // `setter` is given an appropriately typed ArrayView of length exactly
307 // `max_elements` that describes the area where it should write the data; it
Karl Wiberg09819ec2017-11-24 12:26:32308 // should return the number of elements actually written. (If it doesn't fill
309 // the whole ArrayView, it should leave the unused space at the end.)
Henrik Kjellanderec78f1c2017-06-29 05:52:50310 template <typename U = T,
311 typename F,
312 typename std::enable_if<
313 internal::BufferCompat<T, U>::value>::type* = nullptr>
314 size_t AppendData(size_t max_elements, F&& setter) {
315 RTC_DCHECK(IsConsistent());
316 const size_t old_size = size_;
317 SetSize(old_size + max_elements);
318 U* base_ptr = data<U>() + old_size;
319 size_t written_elements = setter(rtc::ArrayView<U>(base_ptr, max_elements));
320
321 RTC_CHECK_LE(written_elements, max_elements);
322 size_ = old_size + written_elements;
323 RTC_DCHECK(IsConsistent());
324 return written_elements;
325 }
326
327 // Sets the size of the buffer. If the new size is smaller than the old, the
328 // buffer contents will be kept but truncated; if the new size is greater,
329 // the existing contents will be kept and the new space will be
330 // uninitialized.
331 void SetSize(size_t size) {
Joachim Bauch5b32f232018-03-07 19:02:26332 const size_t old_size = size_;
Henrik Kjellanderec78f1c2017-06-29 05:52:50333 EnsureCapacityWithHeadroom(size, true);
334 size_ = size;
Joachim Bauch5b32f232018-03-07 19:02:26335 if (ZeroOnFree && size_ < old_size) {
336 ZeroTrailingData(old_size - size_);
337 }
Henrik Kjellanderec78f1c2017-06-29 05:52:50338 }
339
340 // Ensure that the buffer size can be increased to at least capacity without
341 // further reallocation. (Of course, this operation might need to reallocate
342 // the buffer.)
343 void EnsureCapacity(size_t capacity) {
344 // Don't allocate extra headroom, since the user is asking for a specific
345 // capacity.
346 EnsureCapacityWithHeadroom(capacity, false);
347 }
348
349 // Resets the buffer to zero size without altering capacity. Works even if the
350 // buffer has been moved from.
351 void Clear() {
Joachim Bauch5b32f232018-03-07 19:02:26352 MaybeZeroCompleteBuffer();
Henrik Kjellanderec78f1c2017-06-29 05:52:50353 size_ = 0;
354 RTC_DCHECK(IsConsistent());
355 }
356
357 // Swaps two buffers. Also works for buffers that have been moved from.
358 friend void swap(BufferT& a, BufferT& b) {
359 using std::swap;
360 swap(a.size_, b.size_);
361 swap(a.capacity_, b.capacity_);
362 swap(a.data_, b.data_);
363 }
364
365 private:
366 void EnsureCapacityWithHeadroom(size_t capacity, bool extra_headroom) {
367 RTC_DCHECK(IsConsistent());
368 if (capacity <= capacity_)
369 return;
370
371 // If the caller asks for extra headroom, ensure that the new capacity is
372 // >= 1.5 times the old capacity. Any constant > 1 is sufficient to prevent
373 // quadratic behavior; as to why we pick 1.5 in particular, see
374 // https://github.com/facebook/folly/blob/master/folly/docs/FBVector.md and
375 // http://www.gahcep.com/cpp-internals-stl-vector-part-1/.
376 const size_t new_capacity =
377 extra_headroom ? std::max(capacity, capacity_ + capacity_ / 2)
378 : capacity;
379
380 std::unique_ptr<T[]> new_data(new T[new_capacity]);
Dan Minorb164e702020-05-28 13:21:42381 if (data_ != nullptr) {
382 std::memcpy(new_data.get(), data_.get(), size_ * sizeof(T));
383 }
Joachim Bauch5b32f232018-03-07 19:02:26384 MaybeZeroCompleteBuffer();
Henrik Kjellanderec78f1c2017-06-29 05:52:50385 data_ = std::move(new_data);
386 capacity_ = new_capacity;
387 RTC_DCHECK(IsConsistent());
388 }
389
Joachim Bauch5b32f232018-03-07 19:02:26390 // Zero the complete buffer if template argument "ZeroOnFree" is true.
391 void MaybeZeroCompleteBuffer() {
Karl Wiberg9d247952018-10-10 10:52:17392 if (ZeroOnFree && capacity_ > 0) {
Joachim Bauch5b32f232018-03-07 19:02:26393 // It would be sufficient to only zero "size_" elements, as all other
394 // methods already ensure that the unused capacity contains no sensitive
Karl Wiberg9d247952018-10-10 10:52:17395 // data---but better safe than sorry.
Joachim Bauch5b32f232018-03-07 19:02:26396 ExplicitZeroMemory(data_.get(), capacity_ * sizeof(T));
397 }
398 }
399
400 // Zero the first "count" elements of unused capacity.
401 void ZeroTrailingData(size_t count) {
402 RTC_DCHECK(IsConsistent());
403 RTC_DCHECK_LE(count, capacity_ - size_);
404 ExplicitZeroMemory(data_.get() + size_, count * sizeof(T));
405 }
406
Karl Wibergb3b01792018-10-10 10:44:12407 // Precondition for all methods except Clear, operator= and the destructor.
Henrik Kjellanderec78f1c2017-06-29 05:52:50408 // Postcondition for all methods except move construction and move
409 // assignment, which leave the moved-from object in a possibly inconsistent
410 // state.
411 bool IsConsistent() const {
412 return (data_ || capacity_ == 0) && capacity_ >= size_;
413 }
414
415 // Called when *this has been moved from. Conceptually it's a no-op, but we
416 // can mutate the state slightly to help subsequent sanity checks catch bugs.
417 void OnMovedFrom() {
Karl Wiberg4f3ce272018-10-17 11:34:33418 RTC_DCHECK(!data_); // Our heap block should have been stolen.
Henrik Kjellanderec78f1c2017-06-29 05:52:50419#if RTC_DCHECK_IS_ON
Karl Wibergb3b01792018-10-10 10:44:12420 // Ensure that *this is always inconsistent, to provoke bugs.
421 size_ = 1;
422 capacity_ = 0;
423#else
Henrik Kjellanderec78f1c2017-06-29 05:52:50424 // Make *this consistent and empty. Shouldn't be necessary, but better safe
425 // than sorry.
426 size_ = 0;
427 capacity_ = 0;
Henrik Kjellanderec78f1c2017-06-29 05:52:50428#endif
429 }
430
431 size_t size_;
432 size_t capacity_;
433 std::unique_ptr<T[]> data_;
434};
435
436// By far the most common sort of buffer.
437using Buffer = BufferT<uint8_t>;
438
Joachim Bauch5b32f232018-03-07 19:02:26439// A buffer that zeros memory before releasing it.
440template <typename T>
441using ZeroOnFreeBuffer = BufferT<T, true>;
442
Henrik Kjellanderec78f1c2017-06-29 05:52:50443} // namespace rtc
henrike@webrtc.orgf0488722014-05-13 18:00:26444
Mirko Bonadei92ea95e2017-09-15 04:47:31445#endif // RTC_BASE_BUFFER_H_