blob: 9bf96cd146a38a79e164fc4df0d8f4a2f237eebd [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
Henrik Kjellanderec78f1c2017-06-29 05:52:5014#include <algorithm>
15#include <cstring>
16#include <memory>
17#include <type_traits>
18#include <utility>
19
Mirko Bonadei92ea95e2017-09-15 04:47:3120#include "api/array_view.h"
21#include "rtc_base/checks.h"
22#include "rtc_base/type_traits.h"
Joachim Bauch5b32f232018-03-07 19:02:2623#include "rtc_base/zero_memory.h"
Henrik Kjellanderec78f1c2017-06-29 05:52:5024
25namespace rtc {
26
27namespace internal {
28
29// (Internal; please don't use outside this file.) Determines if elements of
30// type U are compatible with a BufferT<T>. For most types, we just ignore
31// top-level const and forbid top-level volatile and require T and U to be
32// otherwise equal, but all byte-sized integers (notably char, int8_t, and
33// uint8_t) are compatible with each other. (Note: We aim to get rid of this
34// behavior, and treat all types the same.)
35template <typename T, typename U>
36struct BufferCompat {
37 static constexpr bool value =
38 !std::is_volatile<U>::value &&
39 ((std::is_integral<T>::value && sizeof(T) == 1)
40 ? (std::is_integral<U>::value && sizeof(U) == 1)
41 : (std::is_same<T, typename std::remove_const<U>::type>::value));
42};
43
44} // namespace internal
45
46// Basic buffer class, can be grown and shrunk dynamically.
47// Unlike std::string/vector, does not initialize data when increasing size.
Joachim Bauch5b32f232018-03-07 19:02:2648// If "ZeroOnFree" is true, any memory is explicitly cleared before releasing.
49// The type alias "ZeroOnFreeBuffer" below should be used instead of setting
50// "ZeroOnFree" in the template manually to "true".
51template <typename T, bool ZeroOnFree = false>
Henrik Kjellanderec78f1c2017-06-29 05:52:5052class BufferT {
53 // We want T's destructor and default constructor to be trivial, i.e. perform
54 // no action, so that we don't have to touch the memory we allocate and
55 // deallocate. And we want T to be trivially copyable, so that we can copy T
56 // instances with std::memcpy. This is precisely the definition of a trivial
57 // type.
58 static_assert(std::is_trivial<T>::value, "T must be a trivial type.");
59
60 // This class relies heavily on being able to mutate its data.
61 static_assert(!std::is_const<T>::value, "T may not be const");
62
63 public:
64 using value_type = T;
65
66 // An empty BufferT.
67 BufferT() : size_(0), capacity_(0), data_(nullptr) {
68 RTC_DCHECK(IsConsistent());
69 }
70
71 // Disable copy construction and copy assignment, since copying a buffer is
72 // expensive enough that we want to force the user to be explicit about it.
73 BufferT(const BufferT&) = delete;
74 BufferT& operator=(const BufferT&) = delete;
75
76 BufferT(BufferT&& buf)
77 : size_(buf.size()),
78 capacity_(buf.capacity()),
79 data_(std::move(buf.data_)) {
80 RTC_DCHECK(IsConsistent());
81 buf.OnMovedFrom();
82 }
83
84 // Construct a buffer with the specified number of uninitialized elements.
85 explicit BufferT(size_t size) : BufferT(size, size) {}
86
87 BufferT(size_t size, size_t capacity)
88 : size_(size),
89 capacity_(std::max(size, capacity)),
Oleh Prypin7d984ee2018-08-02 22:03:1790 data_(capacity_ > 0 ? new T[capacity_] : nullptr) {
Henrik Kjellanderec78f1c2017-06-29 05:52:5091 RTC_DCHECK(IsConsistent());
92 }
93
94 // Construct a buffer and copy the specified number of elements into it.
95 template <typename U,
96 typename std::enable_if<
97 internal::BufferCompat<T, U>::value>::type* = nullptr>
98 BufferT(const U* data, size_t size) : BufferT(data, size, size) {}
99
100 template <typename U,
101 typename std::enable_if<
102 internal::BufferCompat<T, U>::value>::type* = nullptr>
103 BufferT(U* data, size_t size, size_t capacity) : BufferT(size, capacity) {
104 static_assert(sizeof(T) == sizeof(U), "");
105 std::memcpy(data_.get(), data, size * sizeof(U));
106 }
107
108 // Construct a buffer from the contents of an array.
109 template <typename U,
110 size_t N,
111 typename std::enable_if<
112 internal::BufferCompat<T, U>::value>::type* = nullptr>
113 BufferT(U (&array)[N]) : BufferT(array, N) {}
114
Joachim Bauch5b32f232018-03-07 19:02:26115 ~BufferT() { MaybeZeroCompleteBuffer(); }
116
Henrik Kjellanderec78f1c2017-06-29 05:52:50117 // Get a pointer to the data. Just .data() will give you a (const) T*, but if
118 // T is a byte-sized integer, you may also use .data<U>() for any other
119 // byte-sized integer U.
120 template <typename U = T,
121 typename std::enable_if<
122 internal::BufferCompat<T, U>::value>::type* = nullptr>
123 const U* data() const {
124 RTC_DCHECK(IsConsistent());
125 return reinterpret_cast<U*>(data_.get());
126 }
127
128 template <typename U = T,
129 typename std::enable_if<
130 internal::BufferCompat<T, U>::value>::type* = nullptr>
131 U* data() {
132 RTC_DCHECK(IsConsistent());
133 return reinterpret_cast<U*>(data_.get());
134 }
135
136 bool empty() const {
137 RTC_DCHECK(IsConsistent());
138 return size_ == 0;
139 }
140
141 size_t size() const {
142 RTC_DCHECK(IsConsistent());
143 return size_;
144 }
145
146 size_t capacity() const {
147 RTC_DCHECK(IsConsistent());
148 return capacity_;
149 }
150
151 BufferT& operator=(BufferT&& buf) {
Henrik Kjellanderec78f1c2017-06-29 05:52:50152 RTC_DCHECK(buf.IsConsistent());
153 size_ = buf.size_;
154 capacity_ = buf.capacity_;
155 data_ = std::move(buf.data_);
156 buf.OnMovedFrom();
157 return *this;
158 }
159
160 bool operator==(const BufferT& buf) const {
161 RTC_DCHECK(IsConsistent());
162 if (size_ != buf.size_) {
163 return false;
164 }
165 if (std::is_integral<T>::value) {
166 // Optimization.
167 return std::memcmp(data_.get(), buf.data_.get(), size_ * sizeof(T)) == 0;
168 }
169 for (size_t i = 0; i < size_; ++i) {
170 if (data_[i] != buf.data_[i]) {
171 return false;
172 }
173 }
174 return true;
175 }
176
177 bool operator!=(const BufferT& buf) const { return !(*this == buf); }
178
179 T& operator[](size_t index) {
180 RTC_DCHECK_LT(index, size_);
181 return data()[index];
182 }
183
184 T operator[](size_t index) const {
185 RTC_DCHECK_LT(index, size_);
186 return data()[index];
187 }
188
189 T* begin() { return data(); }
190 T* end() { return data() + size(); }
191 const T* begin() const { return data(); }
192 const T* end() const { return data() + size(); }
193 const T* cbegin() const { return data(); }
194 const T* cend() const { return data() + size(); }
195
196 // The SetData functions replace the contents of the buffer. They accept the
197 // same input types as the constructors.
198 template <typename U,
199 typename std::enable_if<
200 internal::BufferCompat<T, U>::value>::type* = nullptr>
201 void SetData(const U* data, size_t size) {
202 RTC_DCHECK(IsConsistent());
Joachim Bauch5b32f232018-03-07 19:02:26203 const size_t old_size = size_;
Henrik Kjellanderec78f1c2017-06-29 05:52:50204 size_ = 0;
205 AppendData(data, size);
Joachim Bauch5b32f232018-03-07 19:02:26206 if (ZeroOnFree && size_ < old_size) {
207 ZeroTrailingData(old_size - size_);
208 }
Henrik Kjellanderec78f1c2017-06-29 05:52:50209 }
210
211 template <typename U,
212 size_t N,
213 typename std::enable_if<
214 internal::BufferCompat<T, U>::value>::type* = nullptr>
215 void SetData(const U (&array)[N]) {
216 SetData(array, N);
217 }
218
219 template <typename W,
220 typename std::enable_if<
221 HasDataAndSize<const W, const T>::value>::type* = nullptr>
222 void SetData(const W& w) {
223 SetData(w.data(), w.size());
224 }
225
Karl Wiberg09819ec2017-11-24 12:26:32226 // Replaces the data in the buffer with at most |max_elements| of data, using
Henrik Kjellanderec78f1c2017-06-29 05:52:50227 // the function |setter|, which should have the following signature:
Karl Wiberg09819ec2017-11-24 12:26:32228 //
Henrik Kjellanderec78f1c2017-06-29 05:52:50229 // size_t setter(ArrayView<U> view)
Karl Wiberg09819ec2017-11-24 12:26:32230 //
231 // |setter| is given an appropriately typed ArrayView of length exactly
232 // |max_elements| that describes the area where it should write the data; it
233 // should return the number of elements actually written. (If it doesn't fill
234 // the whole ArrayView, it should leave the unused space at the end.)
Henrik Kjellanderec78f1c2017-06-29 05:52:50235 template <typename U = T,
236 typename F,
237 typename std::enable_if<
238 internal::BufferCompat<T, U>::value>::type* = nullptr>
239 size_t SetData(size_t max_elements, F&& setter) {
240 RTC_DCHECK(IsConsistent());
Joachim Bauch5b32f232018-03-07 19:02:26241 const size_t old_size = size_;
Henrik Kjellanderec78f1c2017-06-29 05:52:50242 size_ = 0;
Joachim Bauch5b32f232018-03-07 19:02:26243 const size_t written = AppendData<U>(max_elements, std::forward<F>(setter));
244 if (ZeroOnFree && size_ < old_size) {
245 ZeroTrailingData(old_size - size_);
246 }
247 return written;
Henrik Kjellanderec78f1c2017-06-29 05:52:50248 }
249
250 // The AppendData functions add data to the end of the buffer. They accept
251 // the same input types as the constructors.
252 template <typename U,
253 typename std::enable_if<
254 internal::BufferCompat<T, U>::value>::type* = nullptr>
255 void AppendData(const U* data, size_t size) {
256 RTC_DCHECK(IsConsistent());
257 const size_t new_size = size_ + size;
258 EnsureCapacityWithHeadroom(new_size, true);
259 static_assert(sizeof(T) == sizeof(U), "");
260 std::memcpy(data_.get() + size_, data, size * sizeof(U));
261 size_ = new_size;
262 RTC_DCHECK(IsConsistent());
263 }
264
265 template <typename U,
266 size_t N,
267 typename std::enable_if<
268 internal::BufferCompat<T, U>::value>::type* = nullptr>
269 void AppendData(const U (&array)[N]) {
270 AppendData(array, N);
271 }
272
273 template <typename W,
274 typename std::enable_if<
275 HasDataAndSize<const W, const T>::value>::type* = nullptr>
276 void AppendData(const W& w) {
277 AppendData(w.data(), w.size());
278 }
279
280 template <typename U,
281 typename std::enable_if<
282 internal::BufferCompat<T, U>::value>::type* = nullptr>
283 void AppendData(const U& item) {
284 AppendData(&item, 1);
285 }
286
Karl Wiberg09819ec2017-11-24 12:26:32287 // Appends at most |max_elements| to the end of the buffer, using the function
Henrik Kjellanderec78f1c2017-06-29 05:52:50288 // |setter|, which should have the following signature:
Karl Wiberg09819ec2017-11-24 12:26:32289 //
Henrik Kjellanderec78f1c2017-06-29 05:52:50290 // size_t setter(ArrayView<U> view)
Karl Wiberg09819ec2017-11-24 12:26:32291 //
292 // |setter| is given an appropriately typed ArrayView of length exactly
293 // |max_elements| that describes the area where it should write the data; it
294 // should return the number of elements actually written. (If it doesn't fill
295 // the whole ArrayView, it should leave the unused space at the end.)
Henrik Kjellanderec78f1c2017-06-29 05:52:50296 template <typename U = T,
297 typename F,
298 typename std::enable_if<
299 internal::BufferCompat<T, U>::value>::type* = nullptr>
300 size_t AppendData(size_t max_elements, F&& setter) {
301 RTC_DCHECK(IsConsistent());
302 const size_t old_size = size_;
303 SetSize(old_size + max_elements);
304 U* base_ptr = data<U>() + old_size;
305 size_t written_elements = setter(rtc::ArrayView<U>(base_ptr, max_elements));
306
307 RTC_CHECK_LE(written_elements, max_elements);
308 size_ = old_size + written_elements;
309 RTC_DCHECK(IsConsistent());
310 return written_elements;
311 }
312
313 // Sets the size of the buffer. If the new size is smaller than the old, the
314 // buffer contents will be kept but truncated; if the new size is greater,
315 // the existing contents will be kept and the new space will be
316 // uninitialized.
317 void SetSize(size_t size) {
Joachim Bauch5b32f232018-03-07 19:02:26318 const size_t old_size = size_;
Henrik Kjellanderec78f1c2017-06-29 05:52:50319 EnsureCapacityWithHeadroom(size, true);
320 size_ = size;
Joachim Bauch5b32f232018-03-07 19:02:26321 if (ZeroOnFree && size_ < old_size) {
322 ZeroTrailingData(old_size - size_);
323 }
Henrik Kjellanderec78f1c2017-06-29 05:52:50324 }
325
326 // Ensure that the buffer size can be increased to at least capacity without
327 // further reallocation. (Of course, this operation might need to reallocate
328 // the buffer.)
329 void EnsureCapacity(size_t capacity) {
330 // Don't allocate extra headroom, since the user is asking for a specific
331 // capacity.
332 EnsureCapacityWithHeadroom(capacity, false);
333 }
334
335 // Resets the buffer to zero size without altering capacity. Works even if the
336 // buffer has been moved from.
337 void Clear() {
Joachim Bauch5b32f232018-03-07 19:02:26338 MaybeZeroCompleteBuffer();
Henrik Kjellanderec78f1c2017-06-29 05:52:50339 size_ = 0;
340 RTC_DCHECK(IsConsistent());
341 }
342
343 // Swaps two buffers. Also works for buffers that have been moved from.
344 friend void swap(BufferT& a, BufferT& b) {
345 using std::swap;
346 swap(a.size_, b.size_);
347 swap(a.capacity_, b.capacity_);
348 swap(a.data_, b.data_);
349 }
350
351 private:
352 void EnsureCapacityWithHeadroom(size_t capacity, bool extra_headroom) {
353 RTC_DCHECK(IsConsistent());
354 if (capacity <= capacity_)
355 return;
356
357 // If the caller asks for extra headroom, ensure that the new capacity is
358 // >= 1.5 times the old capacity. Any constant > 1 is sufficient to prevent
359 // quadratic behavior; as to why we pick 1.5 in particular, see
360 // https://github.com/facebook/folly/blob/master/folly/docs/FBVector.md and
361 // http://www.gahcep.com/cpp-internals-stl-vector-part-1/.
362 const size_t new_capacity =
363 extra_headroom ? std::max(capacity, capacity_ + capacity_ / 2)
364 : capacity;
365
366 std::unique_ptr<T[]> new_data(new T[new_capacity]);
367 std::memcpy(new_data.get(), data_.get(), size_ * sizeof(T));
Joachim Bauch5b32f232018-03-07 19:02:26368 MaybeZeroCompleteBuffer();
Henrik Kjellanderec78f1c2017-06-29 05:52:50369 data_ = std::move(new_data);
370 capacity_ = new_capacity;
371 RTC_DCHECK(IsConsistent());
372 }
373
Joachim Bauch5b32f232018-03-07 19:02:26374 // Zero the complete buffer if template argument "ZeroOnFree" is true.
375 void MaybeZeroCompleteBuffer() {
376 if (ZeroOnFree && capacity_) {
377 // It would be sufficient to only zero "size_" elements, as all other
378 // methods already ensure that the unused capacity contains no sensitive
379 // data - but better safe than sorry.
380 ExplicitZeroMemory(data_.get(), capacity_ * sizeof(T));
381 }
382 }
383
384 // Zero the first "count" elements of unused capacity.
385 void ZeroTrailingData(size_t count) {
386 RTC_DCHECK(IsConsistent());
387 RTC_DCHECK_LE(count, capacity_ - size_);
388 ExplicitZeroMemory(data_.get() + size_, count * sizeof(T));
389 }
390
Karl Wibergb3b01792018-10-10 10:44:12391 // Precondition for all methods except Clear, operator= and the destructor.
Henrik Kjellanderec78f1c2017-06-29 05:52:50392 // Postcondition for all methods except move construction and move
393 // assignment, which leave the moved-from object in a possibly inconsistent
394 // state.
395 bool IsConsistent() const {
396 return (data_ || capacity_ == 0) && capacity_ >= size_;
397 }
398
399 // Called when *this has been moved from. Conceptually it's a no-op, but we
400 // can mutate the state slightly to help subsequent sanity checks catch bugs.
401 void OnMovedFrom() {
402#if RTC_DCHECK_IS_ON
Karl Wibergb3b01792018-10-10 10:44:12403 // Ensure that *this is always inconsistent, to provoke bugs.
404 size_ = 1;
405 capacity_ = 0;
406#else
Henrik Kjellanderec78f1c2017-06-29 05:52:50407 // Make *this consistent and empty. Shouldn't be necessary, but better safe
408 // than sorry.
409 size_ = 0;
410 capacity_ = 0;
Henrik Kjellanderec78f1c2017-06-29 05:52:50411#endif
412 }
413
414 size_t size_;
415 size_t capacity_;
416 std::unique_ptr<T[]> data_;
417};
418
419// By far the most common sort of buffer.
420using Buffer = BufferT<uint8_t>;
421
Joachim Bauch5b32f232018-03-07 19:02:26422// A buffer that zeros memory before releasing it.
423template <typename T>
424using ZeroOnFreeBuffer = BufferT<T, true>;
425
Henrik Kjellanderec78f1c2017-06-29 05:52:50426} // namespace rtc
henrike@webrtc.orgf0488722014-05-13 18:00:26427
Mirko Bonadei92ea95e2017-09-15 04:47:31428#endif // RTC_BASE_BUFFER_H_