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