blob: f9291b99e5a103244c7d6c46cba82641e96eb176 [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
Henrik Kjellanderec78f1c2017-06-29 07:52:50 +020014#include <algorithm>
15#include <cstring>
16#include <memory>
17#include <type_traits>
18#include <utility>
19
Mirko Bonadei92ea95e2017-09-15 06:47:31 +020020#include "api/array_view.h"
21#include "rtc_base/checks.h"
22#include "rtc_base/type_traits.h"
Joachim Bauch5b32f232018-03-07 20:02:26 +010023#include "rtc_base/zero_memory.h"
Henrik Kjellanderec78f1c2017-06-29 07:52:50 +020024
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 20:02:26 +010048// 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 07:52:50 +020052class 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-03 00:03:17 +020090 data_(capacity_ > 0 ? new T[capacity_] : nullptr) {
Henrik Kjellanderec78f1c2017-06-29 07:52:50 +020091 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 20:02:26 +0100115 ~BufferT() { MaybeZeroCompleteBuffer(); }
116
Henrik Kjellanderec78f1c2017-06-29 07:52:50 +0200117 // 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 07:52:50 +0200152 RTC_DCHECK(buf.IsConsistent());
Karl Wiberg9d247952018-10-10 12:52:17 +0200153 MaybeZeroCompleteBuffer();
Henrik Kjellanderec78f1c2017-06-29 07:52:50 +0200154 size_ = buf.size_;
155 capacity_ = buf.capacity_;
Karl Wiberg4f3ce272018-10-17 13:34:33 +0200156 using std::swap;
157 swap(data_, buf.data_);
158 buf.data_.reset();
Henrik Kjellanderec78f1c2017-06-29 07:52:50 +0200159 buf.OnMovedFrom();
160 return *this;
161 }
162
163 bool operator==(const BufferT& buf) const {
164 RTC_DCHECK(IsConsistent());
165 if (size_ != buf.size_) {
166 return false;
167 }
168 if (std::is_integral<T>::value) {
169 // Optimization.
170 return std::memcmp(data_.get(), buf.data_.get(), size_ * sizeof(T)) == 0;
171 }
172 for (size_t i = 0; i < size_; ++i) {
173 if (data_[i] != buf.data_[i]) {
174 return false;
175 }
176 }
177 return true;
178 }
179
180 bool operator!=(const BufferT& buf) const { return !(*this == buf); }
181
182 T& operator[](size_t index) {
183 RTC_DCHECK_LT(index, size_);
184 return data()[index];
185 }
186
187 T operator[](size_t index) const {
188 RTC_DCHECK_LT(index, size_);
189 return data()[index];
190 }
191
192 T* begin() { return data(); }
193 T* end() { return data() + size(); }
194 const T* begin() const { return data(); }
195 const T* end() const { return data() + size(); }
196 const T* cbegin() const { return data(); }
197 const T* cend() const { return data() + size(); }
198
199 // The SetData functions replace the contents of the buffer. They accept the
200 // same input types as the constructors.
201 template <typename U,
202 typename std::enable_if<
203 internal::BufferCompat<T, U>::value>::type* = nullptr>
204 void SetData(const U* data, size_t size) {
205 RTC_DCHECK(IsConsistent());
Joachim Bauch5b32f232018-03-07 20:02:26 +0100206 const size_t old_size = size_;
Henrik Kjellanderec78f1c2017-06-29 07:52:50 +0200207 size_ = 0;
208 AppendData(data, size);
Joachim Bauch5b32f232018-03-07 20:02:26 +0100209 if (ZeroOnFree && size_ < old_size) {
210 ZeroTrailingData(old_size - size_);
211 }
Henrik Kjellanderec78f1c2017-06-29 07:52:50 +0200212 }
213
214 template <typename U,
215 size_t N,
216 typename std::enable_if<
217 internal::BufferCompat<T, U>::value>::type* = nullptr>
218 void SetData(const U (&array)[N]) {
219 SetData(array, N);
220 }
221
222 template <typename W,
223 typename std::enable_if<
224 HasDataAndSize<const W, const T>::value>::type* = nullptr>
225 void SetData(const W& w) {
226 SetData(w.data(), w.size());
227 }
228
Karl Wiberg09819ec2017-11-24 13:26:32 +0100229 // Replaces the data in the buffer with at most |max_elements| of data, using
Henrik Kjellanderec78f1c2017-06-29 07:52:50 +0200230 // the function |setter|, which should have the following signature:
Karl Wiberg09819ec2017-11-24 13:26:32 +0100231 //
Henrik Kjellanderec78f1c2017-06-29 07:52:50 +0200232 // size_t setter(ArrayView<U> view)
Karl Wiberg09819ec2017-11-24 13:26:32 +0100233 //
234 // |setter| is given an appropriately typed ArrayView of length exactly
235 // |max_elements| that describes the area where it should write the data; it
236 // should return the number of elements actually written. (If it doesn't fill
237 // the whole ArrayView, it should leave the unused space at the end.)
Henrik Kjellanderec78f1c2017-06-29 07:52:50 +0200238 template <typename U = T,
239 typename F,
240 typename std::enable_if<
241 internal::BufferCompat<T, U>::value>::type* = nullptr>
242 size_t SetData(size_t max_elements, F&& setter) {
243 RTC_DCHECK(IsConsistent());
Joachim Bauch5b32f232018-03-07 20:02:26 +0100244 const size_t old_size = size_;
Henrik Kjellanderec78f1c2017-06-29 07:52:50 +0200245 size_ = 0;
Joachim Bauch5b32f232018-03-07 20:02:26 +0100246 const size_t written = AppendData<U>(max_elements, std::forward<F>(setter));
247 if (ZeroOnFree && size_ < old_size) {
248 ZeroTrailingData(old_size - size_);
249 }
250 return written;
Henrik Kjellanderec78f1c2017-06-29 07:52:50 +0200251 }
252
253 // The AppendData functions add data to the end of the buffer. They accept
254 // the same input types as the constructors.
255 template <typename U,
256 typename std::enable_if<
257 internal::BufferCompat<T, U>::value>::type* = nullptr>
258 void AppendData(const U* data, size_t size) {
259 RTC_DCHECK(IsConsistent());
260 const size_t new_size = size_ + size;
261 EnsureCapacityWithHeadroom(new_size, true);
262 static_assert(sizeof(T) == sizeof(U), "");
263 std::memcpy(data_.get() + size_, data, size * sizeof(U));
264 size_ = new_size;
265 RTC_DCHECK(IsConsistent());
266 }
267
268 template <typename U,
269 size_t N,
270 typename std::enable_if<
271 internal::BufferCompat<T, U>::value>::type* = nullptr>
272 void AppendData(const U (&array)[N]) {
273 AppendData(array, N);
274 }
275
276 template <typename W,
277 typename std::enable_if<
278 HasDataAndSize<const W, const T>::value>::type* = nullptr>
279 void AppendData(const W& w) {
280 AppendData(w.data(), w.size());
281 }
282
283 template <typename U,
284 typename std::enable_if<
285 internal::BufferCompat<T, U>::value>::type* = nullptr>
286 void AppendData(const U& item) {
287 AppendData(&item, 1);
288 }
289
Karl Wiberg09819ec2017-11-24 13:26:32 +0100290 // Appends at most |max_elements| to the end of the buffer, using the function
Henrik Kjellanderec78f1c2017-06-29 07:52:50 +0200291 // |setter|, which should have the following signature:
Karl Wiberg09819ec2017-11-24 13:26:32 +0100292 //
Henrik Kjellanderec78f1c2017-06-29 07:52:50 +0200293 // size_t setter(ArrayView<U> view)
Karl Wiberg09819ec2017-11-24 13:26:32 +0100294 //
295 // |setter| is given an appropriately typed ArrayView of length exactly
296 // |max_elements| that describes the area where it should write the data; it
297 // should return the number of elements actually written. (If it doesn't fill
298 // the whole ArrayView, it should leave the unused space at the end.)
Henrik Kjellanderec78f1c2017-06-29 07:52:50 +0200299 template <typename U = T,
300 typename F,
301 typename std::enable_if<
302 internal::BufferCompat<T, U>::value>::type* = nullptr>
303 size_t AppendData(size_t max_elements, F&& setter) {
304 RTC_DCHECK(IsConsistent());
305 const size_t old_size = size_;
306 SetSize(old_size + max_elements);
307 U* base_ptr = data<U>() + old_size;
308 size_t written_elements = setter(rtc::ArrayView<U>(base_ptr, max_elements));
309
310 RTC_CHECK_LE(written_elements, max_elements);
311 size_ = old_size + written_elements;
312 RTC_DCHECK(IsConsistent());
313 return written_elements;
314 }
315
316 // Sets the size of the buffer. If the new size is smaller than the old, the
317 // buffer contents will be kept but truncated; if the new size is greater,
318 // the existing contents will be kept and the new space will be
319 // uninitialized.
320 void SetSize(size_t size) {
Joachim Bauch5b32f232018-03-07 20:02:26 +0100321 const size_t old_size = size_;
Henrik Kjellanderec78f1c2017-06-29 07:52:50 +0200322 EnsureCapacityWithHeadroom(size, true);
323 size_ = size;
Joachim Bauch5b32f232018-03-07 20:02:26 +0100324 if (ZeroOnFree && size_ < old_size) {
325 ZeroTrailingData(old_size - size_);
326 }
Henrik Kjellanderec78f1c2017-06-29 07:52:50 +0200327 }
328
329 // Ensure that the buffer size can be increased to at least capacity without
330 // further reallocation. (Of course, this operation might need to reallocate
331 // the buffer.)
332 void EnsureCapacity(size_t capacity) {
333 // Don't allocate extra headroom, since the user is asking for a specific
334 // capacity.
335 EnsureCapacityWithHeadroom(capacity, false);
336 }
337
338 // Resets the buffer to zero size without altering capacity. Works even if the
339 // buffer has been moved from.
340 void Clear() {
Joachim Bauch5b32f232018-03-07 20:02:26 +0100341 MaybeZeroCompleteBuffer();
Henrik Kjellanderec78f1c2017-06-29 07:52:50 +0200342 size_ = 0;
343 RTC_DCHECK(IsConsistent());
344 }
345
346 // Swaps two buffers. Also works for buffers that have been moved from.
347 friend void swap(BufferT& a, BufferT& b) {
348 using std::swap;
349 swap(a.size_, b.size_);
350 swap(a.capacity_, b.capacity_);
351 swap(a.data_, b.data_);
352 }
353
354 private:
355 void EnsureCapacityWithHeadroom(size_t capacity, bool extra_headroom) {
356 RTC_DCHECK(IsConsistent());
357 if (capacity <= capacity_)
358 return;
359
360 // If the caller asks for extra headroom, ensure that the new capacity is
361 // >= 1.5 times the old capacity. Any constant > 1 is sufficient to prevent
362 // quadratic behavior; as to why we pick 1.5 in particular, see
363 // https://github.com/facebook/folly/blob/master/folly/docs/FBVector.md and
364 // http://www.gahcep.com/cpp-internals-stl-vector-part-1/.
365 const size_t new_capacity =
366 extra_headroom ? std::max(capacity, capacity_ + capacity_ / 2)
367 : capacity;
368
369 std::unique_ptr<T[]> new_data(new T[new_capacity]);
370 std::memcpy(new_data.get(), data_.get(), size_ * sizeof(T));
Joachim Bauch5b32f232018-03-07 20:02:26 +0100371 MaybeZeroCompleteBuffer();
Henrik Kjellanderec78f1c2017-06-29 07:52:50 +0200372 data_ = std::move(new_data);
373 capacity_ = new_capacity;
374 RTC_DCHECK(IsConsistent());
375 }
376
Joachim Bauch5b32f232018-03-07 20:02:26 +0100377 // Zero the complete buffer if template argument "ZeroOnFree" is true.
378 void MaybeZeroCompleteBuffer() {
Karl Wiberg9d247952018-10-10 12:52:17 +0200379 if (ZeroOnFree && capacity_ > 0) {
Joachim Bauch5b32f232018-03-07 20:02:26 +0100380 // It would be sufficient to only zero "size_" elements, as all other
381 // methods already ensure that the unused capacity contains no sensitive
Karl Wiberg9d247952018-10-10 12:52:17 +0200382 // data---but better safe than sorry.
Joachim Bauch5b32f232018-03-07 20:02:26 +0100383 ExplicitZeroMemory(data_.get(), capacity_ * sizeof(T));
384 }
385 }
386
387 // Zero the first "count" elements of unused capacity.
388 void ZeroTrailingData(size_t count) {
389 RTC_DCHECK(IsConsistent());
390 RTC_DCHECK_LE(count, capacity_ - size_);
391 ExplicitZeroMemory(data_.get() + size_, count * sizeof(T));
392 }
393
Karl Wibergb3b01792018-10-10 12:44:12 +0200394 // Precondition for all methods except Clear, operator= and the destructor.
Henrik Kjellanderec78f1c2017-06-29 07:52:50 +0200395 // Postcondition for all methods except move construction and move
396 // assignment, which leave the moved-from object in a possibly inconsistent
397 // state.
398 bool IsConsistent() const {
399 return (data_ || capacity_ == 0) && capacity_ >= size_;
400 }
401
402 // Called when *this has been moved from. Conceptually it's a no-op, but we
403 // can mutate the state slightly to help subsequent sanity checks catch bugs.
404 void OnMovedFrom() {
Karl Wiberg4f3ce272018-10-17 13:34:33 +0200405 RTC_DCHECK(!data_); // Our heap block should have been stolen.
Henrik Kjellanderec78f1c2017-06-29 07:52:50 +0200406#if RTC_DCHECK_IS_ON
Karl Wibergb3b01792018-10-10 12:44:12 +0200407 // Ensure that *this is always inconsistent, to provoke bugs.
408 size_ = 1;
409 capacity_ = 0;
410#else
Henrik Kjellanderec78f1c2017-06-29 07:52:50 +0200411 // Make *this consistent and empty. Shouldn't be necessary, but better safe
412 // than sorry.
413 size_ = 0;
414 capacity_ = 0;
Henrik Kjellanderec78f1c2017-06-29 07:52:50 +0200415#endif
416 }
417
418 size_t size_;
419 size_t capacity_;
420 std::unique_ptr<T[]> data_;
421};
422
423// By far the most common sort of buffer.
424using Buffer = BufferT<uint8_t>;
425
Joachim Bauch5b32f232018-03-07 20:02:26 +0100426// A buffer that zeros memory before releasing it.
427template <typename T>
428using ZeroOnFreeBuffer = BufferT<T, true>;
429
Henrik Kjellanderec78f1c2017-06-29 07:52:50 +0200430} // namespace rtc
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000431
Mirko Bonadei92ea95e2017-09-15 06:47:31 +0200432#endif // RTC_BASE_BUFFER_H_