blob: 34ef8859a8d64e614e7cb9b2e77835272ee0ac33 [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
Mirko Bonadei92ea95e2017-09-15 06:47:31 +020022#include "api/array_view.h"
23#include "rtc_base/checks.h"
24#include "rtc_base/type_traits.h"
Joachim Bauch5b32f232018-03-07 20:02:26 +010025#include "rtc_base/zero_memory.h"
Henrik Kjellanderec78f1c2017-06-29 07:52:50 +020026
27namespace rtc {
28
29namespace internal {
30
31// (Internal; please don't use outside this file.) Determines if elements of
32// type U are compatible with a BufferT<T>. For most types, we just ignore
33// top-level const and forbid top-level volatile and require T and U to be
34// otherwise equal, but all byte-sized integers (notably char, int8_t, and
35// uint8_t) are compatible with each other. (Note: We aim to get rid of this
36// behavior, and treat all types the same.)
37template <typename T, typename U>
38struct BufferCompat {
39 static constexpr bool value =
40 !std::is_volatile<U>::value &&
41 ((std::is_integral<T>::value && sizeof(T) == 1)
42 ? (std::is_integral<U>::value && sizeof(U) == 1)
43 : (std::is_same<T, typename std::remove_const<U>::type>::value));
44};
45
46} // namespace internal
47
48// Basic buffer class, can be grown and shrunk dynamically.
49// Unlike std::string/vector, does not initialize data when increasing size.
Joachim Bauch5b32f232018-03-07 20:02:26 +010050// If "ZeroOnFree" is true, any memory is explicitly cleared before releasing.
51// The type alias "ZeroOnFreeBuffer" below should be used instead of setting
52// "ZeroOnFree" in the template manually to "true".
53template <typename T, bool ZeroOnFree = false>
Henrik Kjellanderec78f1c2017-06-29 07:52:50 +020054class BufferT {
55 // We want T's destructor and default constructor to be trivial, i.e. perform
56 // no action, so that we don't have to touch the memory we allocate and
57 // deallocate. And we want T to be trivially copyable, so that we can copy T
58 // instances with std::memcpy. This is precisely the definition of a trivial
59 // type.
60 static_assert(std::is_trivial<T>::value, "T must be a trivial type.");
61
62 // This class relies heavily on being able to mutate its data.
63 static_assert(!std::is_const<T>::value, "T may not be const");
64
65 public:
66 using value_type = T;
67
68 // An empty BufferT.
69 BufferT() : size_(0), capacity_(0), data_(nullptr) {
70 RTC_DCHECK(IsConsistent());
71 }
72
73 // Disable copy construction and copy assignment, since copying a buffer is
74 // expensive enough that we want to force the user to be explicit about it.
75 BufferT(const BufferT&) = delete;
76 BufferT& operator=(const BufferT&) = delete;
77
78 BufferT(BufferT&& buf)
79 : size_(buf.size()),
80 capacity_(buf.capacity()),
81 data_(std::move(buf.data_)) {
82 RTC_DCHECK(IsConsistent());
83 buf.OnMovedFrom();
84 }
85
86 // Construct a buffer with the specified number of uninitialized elements.
87 explicit BufferT(size_t size) : BufferT(size, size) {}
88
89 BufferT(size_t size, size_t capacity)
90 : size_(size),
91 capacity_(std::max(size, capacity)),
Oleh Prypin7d984ee2018-08-03 00:03:17 +020092 data_(capacity_ > 0 ? new T[capacity_] : nullptr) {
Henrik Kjellanderec78f1c2017-06-29 07:52:50 +020093 RTC_DCHECK(IsConsistent());
94 }
95
96 // Construct a buffer and copy the specified number of elements into it.
97 template <typename U,
98 typename std::enable_if<
99 internal::BufferCompat<T, U>::value>::type* = nullptr>
100 BufferT(const U* data, size_t size) : BufferT(data, size, size) {}
101
102 template <typename U,
103 typename std::enable_if<
104 internal::BufferCompat<T, U>::value>::type* = nullptr>
105 BufferT(U* data, size_t size, size_t capacity) : BufferT(size, capacity) {
106 static_assert(sizeof(T) == sizeof(U), "");
107 std::memcpy(data_.get(), data, size * sizeof(U));
108 }
109
110 // Construct a buffer from the contents of an array.
111 template <typename U,
112 size_t N,
113 typename std::enable_if<
114 internal::BufferCompat<T, U>::value>::type* = nullptr>
115 BufferT(U (&array)[N]) : BufferT(array, N) {}
116
Joachim Bauch5b32f232018-03-07 20:02:26 +0100117 ~BufferT() { MaybeZeroCompleteBuffer(); }
118
Henrik Kjellanderec78f1c2017-06-29 07:52:50 +0200119 // Get a pointer to the data. Just .data() will give you a (const) T*, but if
120 // T is a byte-sized integer, you may also use .data<U>() for any other
121 // byte-sized integer U.
122 template <typename U = T,
123 typename std::enable_if<
124 internal::BufferCompat<T, U>::value>::type* = nullptr>
125 const U* data() const {
126 RTC_DCHECK(IsConsistent());
127 return reinterpret_cast<U*>(data_.get());
128 }
129
130 template <typename U = T,
131 typename std::enable_if<
132 internal::BufferCompat<T, U>::value>::type* = nullptr>
133 U* data() {
134 RTC_DCHECK(IsConsistent());
135 return reinterpret_cast<U*>(data_.get());
136 }
137
138 bool empty() const {
139 RTC_DCHECK(IsConsistent());
140 return size_ == 0;
141 }
142
143 size_t size() const {
144 RTC_DCHECK(IsConsistent());
145 return size_;
146 }
147
148 size_t capacity() const {
149 RTC_DCHECK(IsConsistent());
150 return capacity_;
151 }
152
153 BufferT& operator=(BufferT&& buf) {
Henrik Kjellanderec78f1c2017-06-29 07:52:50 +0200154 RTC_DCHECK(buf.IsConsistent());
Karl Wiberg9d247952018-10-10 12:52:17 +0200155 MaybeZeroCompleteBuffer();
Henrik Kjellanderec78f1c2017-06-29 07:52:50 +0200156 size_ = buf.size_;
157 capacity_ = buf.capacity_;
Karl Wiberg4f3ce272018-10-17 13:34:33 +0200158 using std::swap;
159 swap(data_, buf.data_);
160 buf.data_.reset();
Henrik Kjellanderec78f1c2017-06-29 07:52:50 +0200161 buf.OnMovedFrom();
162 return *this;
163 }
164
165 bool operator==(const BufferT& buf) const {
166 RTC_DCHECK(IsConsistent());
167 if (size_ != buf.size_) {
168 return false;
169 }
170 if (std::is_integral<T>::value) {
171 // Optimization.
172 return std::memcmp(data_.get(), buf.data_.get(), size_ * sizeof(T)) == 0;
173 }
174 for (size_t i = 0; i < size_; ++i) {
175 if (data_[i] != buf.data_[i]) {
176 return false;
177 }
178 }
179 return true;
180 }
181
182 bool operator!=(const BufferT& buf) const { return !(*this == buf); }
183
184 T& operator[](size_t index) {
185 RTC_DCHECK_LT(index, size_);
186 return data()[index];
187 }
188
189 T operator[](size_t index) const {
190 RTC_DCHECK_LT(index, size_);
191 return data()[index];
192 }
193
194 T* begin() { return data(); }
195 T* end() { return data() + size(); }
196 const T* begin() const { return data(); }
197 const T* end() const { return data() + size(); }
198 const T* cbegin() const { return data(); }
199 const T* cend() const { return data() + size(); }
200
201 // The SetData functions replace the contents of the buffer. They accept the
202 // same input types as the constructors.
203 template <typename U,
204 typename std::enable_if<
205 internal::BufferCompat<T, U>::value>::type* = nullptr>
206 void SetData(const U* data, size_t size) {
207 RTC_DCHECK(IsConsistent());
Joachim Bauch5b32f232018-03-07 20:02:26 +0100208 const size_t old_size = size_;
Henrik Kjellanderec78f1c2017-06-29 07:52:50 +0200209 size_ = 0;
210 AppendData(data, size);
Joachim Bauch5b32f232018-03-07 20:02:26 +0100211 if (ZeroOnFree && size_ < old_size) {
212 ZeroTrailingData(old_size - size_);
213 }
Henrik Kjellanderec78f1c2017-06-29 07:52:50 +0200214 }
215
216 template <typename U,
217 size_t N,
218 typename std::enable_if<
219 internal::BufferCompat<T, U>::value>::type* = nullptr>
220 void SetData(const U (&array)[N]) {
221 SetData(array, N);
222 }
223
224 template <typename W,
225 typename std::enable_if<
226 HasDataAndSize<const W, const T>::value>::type* = nullptr>
227 void SetData(const W& w) {
228 SetData(w.data(), w.size());
229 }
230
Karl Wiberg09819ec2017-11-24 13:26:32 +0100231 // Replaces the data in the buffer with at most |max_elements| of data, using
Henrik Kjellanderec78f1c2017-06-29 07:52:50 +0200232 // the function |setter|, which should have the following signature:
Karl Wiberg09819ec2017-11-24 13:26:32 +0100233 //
Henrik Kjellanderec78f1c2017-06-29 07:52:50 +0200234 // size_t setter(ArrayView<U> view)
Karl Wiberg09819ec2017-11-24 13:26:32 +0100235 //
236 // |setter| is given an appropriately typed ArrayView of length exactly
237 // |max_elements| that describes the area where it should write the data; it
238 // should return the number of elements actually written. (If it doesn't fill
239 // the whole ArrayView, it should leave the unused space at the end.)
Henrik Kjellanderec78f1c2017-06-29 07:52:50 +0200240 template <typename U = T,
241 typename F,
242 typename std::enable_if<
243 internal::BufferCompat<T, U>::value>::type* = nullptr>
244 size_t SetData(size_t max_elements, F&& setter) {
245 RTC_DCHECK(IsConsistent());
Joachim Bauch5b32f232018-03-07 20:02:26 +0100246 const size_t old_size = size_;
Henrik Kjellanderec78f1c2017-06-29 07:52:50 +0200247 size_ = 0;
Joachim Bauch5b32f232018-03-07 20:02:26 +0100248 const size_t written = AppendData<U>(max_elements, std::forward<F>(setter));
249 if (ZeroOnFree && size_ < old_size) {
250 ZeroTrailingData(old_size - size_);
251 }
252 return written;
Henrik Kjellanderec78f1c2017-06-29 07:52:50 +0200253 }
254
255 // The AppendData functions add data to the end of the buffer. They accept
256 // the same input types as the constructors.
257 template <typename U,
258 typename std::enable_if<
259 internal::BufferCompat<T, U>::value>::type* = nullptr>
260 void AppendData(const U* data, size_t size) {
261 RTC_DCHECK(IsConsistent());
262 const size_t new_size = size_ + size;
263 EnsureCapacityWithHeadroom(new_size, true);
264 static_assert(sizeof(T) == sizeof(U), "");
265 std::memcpy(data_.get() + size_, data, size * sizeof(U));
266 size_ = new_size;
267 RTC_DCHECK(IsConsistent());
268 }
269
270 template <typename U,
271 size_t N,
272 typename std::enable_if<
273 internal::BufferCompat<T, U>::value>::type* = nullptr>
274 void AppendData(const U (&array)[N]) {
275 AppendData(array, N);
276 }
277
278 template <typename W,
279 typename std::enable_if<
280 HasDataAndSize<const W, const T>::value>::type* = nullptr>
281 void AppendData(const W& w) {
282 AppendData(w.data(), w.size());
283 }
284
285 template <typename U,
286 typename std::enable_if<
287 internal::BufferCompat<T, U>::value>::type* = nullptr>
288 void AppendData(const U& item) {
289 AppendData(&item, 1);
290 }
291
Karl Wiberg09819ec2017-11-24 13:26:32 +0100292 // Appends at most |max_elements| to the end of the buffer, using the function
Henrik Kjellanderec78f1c2017-06-29 07:52:50 +0200293 // |setter|, which should have the following signature:
Karl Wiberg09819ec2017-11-24 13:26:32 +0100294 //
Henrik Kjellanderec78f1c2017-06-29 07:52:50 +0200295 // size_t setter(ArrayView<U> view)
Karl Wiberg09819ec2017-11-24 13:26:32 +0100296 //
297 // |setter| is given an appropriately typed ArrayView of length exactly
298 // |max_elements| that describes the area where it should write the data; it
299 // should return the number of elements actually written. (If it doesn't fill
300 // the whole ArrayView, it should leave the unused space at the end.)
Henrik Kjellanderec78f1c2017-06-29 07:52:50 +0200301 template <typename U = T,
302 typename F,
303 typename std::enable_if<
304 internal::BufferCompat<T, U>::value>::type* = nullptr>
305 size_t AppendData(size_t max_elements, F&& setter) {
306 RTC_DCHECK(IsConsistent());
307 const size_t old_size = size_;
308 SetSize(old_size + max_elements);
309 U* base_ptr = data<U>() + old_size;
310 size_t written_elements = setter(rtc::ArrayView<U>(base_ptr, max_elements));
311
312 RTC_CHECK_LE(written_elements, max_elements);
313 size_ = old_size + written_elements;
314 RTC_DCHECK(IsConsistent());
315 return written_elements;
316 }
317
318 // Sets the size of the buffer. If the new size is smaller than the old, the
319 // buffer contents will be kept but truncated; if the new size is greater,
320 // the existing contents will be kept and the new space will be
321 // uninitialized.
322 void SetSize(size_t size) {
Joachim Bauch5b32f232018-03-07 20:02:26 +0100323 const size_t old_size = size_;
Henrik Kjellanderec78f1c2017-06-29 07:52:50 +0200324 EnsureCapacityWithHeadroom(size, true);
325 size_ = size;
Joachim Bauch5b32f232018-03-07 20:02:26 +0100326 if (ZeroOnFree && size_ < old_size) {
327 ZeroTrailingData(old_size - size_);
328 }
Henrik Kjellanderec78f1c2017-06-29 07:52:50 +0200329 }
330
331 // Ensure that the buffer size can be increased to at least capacity without
332 // further reallocation. (Of course, this operation might need to reallocate
333 // the buffer.)
334 void EnsureCapacity(size_t capacity) {
335 // Don't allocate extra headroom, since the user is asking for a specific
336 // capacity.
337 EnsureCapacityWithHeadroom(capacity, false);
338 }
339
340 // Resets the buffer to zero size without altering capacity. Works even if the
341 // buffer has been moved from.
342 void Clear() {
Joachim Bauch5b32f232018-03-07 20:02:26 +0100343 MaybeZeroCompleteBuffer();
Henrik Kjellanderec78f1c2017-06-29 07:52:50 +0200344 size_ = 0;
345 RTC_DCHECK(IsConsistent());
346 }
347
348 // Swaps two buffers. Also works for buffers that have been moved from.
349 friend void swap(BufferT& a, BufferT& b) {
350 using std::swap;
351 swap(a.size_, b.size_);
352 swap(a.capacity_, b.capacity_);
353 swap(a.data_, b.data_);
354 }
355
356 private:
357 void EnsureCapacityWithHeadroom(size_t capacity, bool extra_headroom) {
358 RTC_DCHECK(IsConsistent());
359 if (capacity <= capacity_)
360 return;
361
362 // If the caller asks for extra headroom, ensure that the new capacity is
363 // >= 1.5 times the old capacity. Any constant > 1 is sufficient to prevent
364 // quadratic behavior; as to why we pick 1.5 in particular, see
365 // https://github.com/facebook/folly/blob/master/folly/docs/FBVector.md and
366 // http://www.gahcep.com/cpp-internals-stl-vector-part-1/.
367 const size_t new_capacity =
368 extra_headroom ? std::max(capacity, capacity_ + capacity_ / 2)
369 : capacity;
370
371 std::unique_ptr<T[]> new_data(new T[new_capacity]);
372 std::memcpy(new_data.get(), data_.get(), size_ * sizeof(T));
Joachim Bauch5b32f232018-03-07 20:02:26 +0100373 MaybeZeroCompleteBuffer();
Henrik Kjellanderec78f1c2017-06-29 07:52:50 +0200374 data_ = std::move(new_data);
375 capacity_ = new_capacity;
376 RTC_DCHECK(IsConsistent());
377 }
378
Joachim Bauch5b32f232018-03-07 20:02:26 +0100379 // Zero the complete buffer if template argument "ZeroOnFree" is true.
380 void MaybeZeroCompleteBuffer() {
Karl Wiberg9d247952018-10-10 12:52:17 +0200381 if (ZeroOnFree && capacity_ > 0) {
Joachim Bauch5b32f232018-03-07 20:02:26 +0100382 // It would be sufficient to only zero "size_" elements, as all other
383 // methods already ensure that the unused capacity contains no sensitive
Karl Wiberg9d247952018-10-10 12:52:17 +0200384 // data---but better safe than sorry.
Joachim Bauch5b32f232018-03-07 20:02:26 +0100385 ExplicitZeroMemory(data_.get(), capacity_ * sizeof(T));
386 }
387 }
388
389 // Zero the first "count" elements of unused capacity.
390 void ZeroTrailingData(size_t count) {
391 RTC_DCHECK(IsConsistent());
392 RTC_DCHECK_LE(count, capacity_ - size_);
393 ExplicitZeroMemory(data_.get() + size_, count * sizeof(T));
394 }
395
Karl Wibergb3b01792018-10-10 12:44:12 +0200396 // Precondition for all methods except Clear, operator= and the destructor.
Henrik Kjellanderec78f1c2017-06-29 07:52:50 +0200397 // Postcondition for all methods except move construction and move
398 // assignment, which leave the moved-from object in a possibly inconsistent
399 // state.
400 bool IsConsistent() const {
401 return (data_ || capacity_ == 0) && capacity_ >= size_;
402 }
403
404 // Called when *this has been moved from. Conceptually it's a no-op, but we
405 // can mutate the state slightly to help subsequent sanity checks catch bugs.
406 void OnMovedFrom() {
Karl Wiberg4f3ce272018-10-17 13:34:33 +0200407 RTC_DCHECK(!data_); // Our heap block should have been stolen.
Henrik Kjellanderec78f1c2017-06-29 07:52:50 +0200408#if RTC_DCHECK_IS_ON
Karl Wibergb3b01792018-10-10 12:44:12 +0200409 // Ensure that *this is always inconsistent, to provoke bugs.
410 size_ = 1;
411 capacity_ = 0;
412#else
Henrik Kjellanderec78f1c2017-06-29 07:52:50 +0200413 // Make *this consistent and empty. Shouldn't be necessary, but better safe
414 // than sorry.
415 size_ = 0;
416 capacity_ = 0;
Henrik Kjellanderec78f1c2017-06-29 07:52:50 +0200417#endif
418 }
419
420 size_t size_;
421 size_t capacity_;
422 std::unique_ptr<T[]> data_;
423};
424
425// By far the most common sort of buffer.
426using Buffer = BufferT<uint8_t>;
427
Joachim Bauch5b32f232018-03-07 20:02:26 +0100428// A buffer that zeros memory before releasing it.
429template <typename T>
430using ZeroOnFreeBuffer = BufferT<T, true>;
431
Henrik Kjellanderec78f1c2017-06-29 07:52:50 +0200432} // namespace rtc
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000433
Mirko Bonadei92ea95e2017-09-15 06:47:31 +0200434#endif // RTC_BASE_BUFFER_H_