blob: 64974d3ed90b16a3d22d404e0abdc91e8deaefa1 [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)),
90 data_(new T[capacity_]) {
91 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) {
152 RTC_DCHECK(IsConsistent());
153 RTC_DCHECK(buf.IsConsistent());
154 size_ = buf.size_;
155 capacity_ = buf.capacity_;
156 data_ = std::move(buf.data_);
157 buf.OnMovedFrom();
158 return *this;
159 }
160
161 bool operator==(const BufferT& buf) const {
162 RTC_DCHECK(IsConsistent());
163 if (size_ != buf.size_) {
164 return false;
165 }
166 if (std::is_integral<T>::value) {
167 // Optimization.
168 return std::memcmp(data_.get(), buf.data_.get(), size_ * sizeof(T)) == 0;
169 }
170 for (size_t i = 0; i < size_; ++i) {
171 if (data_[i] != buf.data_[i]) {
172 return false;
173 }
174 }
175 return true;
176 }
177
178 bool operator!=(const BufferT& buf) const { return !(*this == buf); }
179
180 T& operator[](size_t index) {
181 RTC_DCHECK_LT(index, size_);
182 return data()[index];
183 }
184
185 T operator[](size_t index) const {
186 RTC_DCHECK_LT(index, size_);
187 return data()[index];
188 }
189
190 T* begin() { return data(); }
191 T* end() { return data() + size(); }
192 const T* begin() const { return data(); }
193 const T* end() const { return data() + size(); }
194 const T* cbegin() const { return data(); }
195 const T* cend() const { return data() + size(); }
196
197 // The SetData functions replace the contents of the buffer. They accept the
198 // same input types as the constructors.
199 template <typename U,
200 typename std::enable_if<
201 internal::BufferCompat<T, U>::value>::type* = nullptr>
202 void SetData(const U* data, size_t size) {
203 RTC_DCHECK(IsConsistent());
Joachim Bauch5b32f232018-03-07 20:02:26 +0100204 const size_t old_size = size_;
Henrik Kjellanderec78f1c2017-06-29 07:52:50 +0200205 size_ = 0;
206 AppendData(data, size);
Joachim Bauch5b32f232018-03-07 20:02:26 +0100207 if (ZeroOnFree && size_ < old_size) {
208 ZeroTrailingData(old_size - size_);
209 }
Henrik Kjellanderec78f1c2017-06-29 07:52:50 +0200210 }
211
212 template <typename U,
213 size_t N,
214 typename std::enable_if<
215 internal::BufferCompat<T, U>::value>::type* = nullptr>
216 void SetData(const U (&array)[N]) {
217 SetData(array, N);
218 }
219
220 template <typename W,
221 typename std::enable_if<
222 HasDataAndSize<const W, const T>::value>::type* = nullptr>
223 void SetData(const W& w) {
224 SetData(w.data(), w.size());
225 }
226
Karl Wiberg09819ec2017-11-24 13:26:32 +0100227 // Replaces the data in the buffer with at most |max_elements| of data, using
Henrik Kjellanderec78f1c2017-06-29 07:52:50 +0200228 // the function |setter|, which should have the following signature:
Karl Wiberg09819ec2017-11-24 13:26:32 +0100229 //
Henrik Kjellanderec78f1c2017-06-29 07:52:50 +0200230 // size_t setter(ArrayView<U> view)
Karl Wiberg09819ec2017-11-24 13:26:32 +0100231 //
232 // |setter| is given an appropriately typed ArrayView of length exactly
233 // |max_elements| that describes the area where it should write the data; it
234 // should return the number of elements actually written. (If it doesn't fill
235 // the whole ArrayView, it should leave the unused space at the end.)
Henrik Kjellanderec78f1c2017-06-29 07:52:50 +0200236 template <typename U = T,
237 typename F,
238 typename std::enable_if<
239 internal::BufferCompat<T, U>::value>::type* = nullptr>
240 size_t SetData(size_t max_elements, F&& setter) {
241 RTC_DCHECK(IsConsistent());
Joachim Bauch5b32f232018-03-07 20:02:26 +0100242 const size_t old_size = size_;
Henrik Kjellanderec78f1c2017-06-29 07:52:50 +0200243 size_ = 0;
Joachim Bauch5b32f232018-03-07 20:02:26 +0100244 const size_t written = AppendData<U>(max_elements, std::forward<F>(setter));
245 if (ZeroOnFree && size_ < old_size) {
246 ZeroTrailingData(old_size - size_);
247 }
248 return written;
Henrik Kjellanderec78f1c2017-06-29 07:52:50 +0200249 }
250
251 // The AppendData functions add data to the end of the buffer. They accept
252 // the same input types as the constructors.
253 template <typename U,
254 typename std::enable_if<
255 internal::BufferCompat<T, U>::value>::type* = nullptr>
256 void AppendData(const U* data, size_t size) {
257 RTC_DCHECK(IsConsistent());
258 const size_t new_size = size_ + size;
259 EnsureCapacityWithHeadroom(new_size, true);
260 static_assert(sizeof(T) == sizeof(U), "");
261 std::memcpy(data_.get() + size_, data, size * sizeof(U));
262 size_ = new_size;
263 RTC_DCHECK(IsConsistent());
264 }
265
266 template <typename U,
267 size_t N,
268 typename std::enable_if<
269 internal::BufferCompat<T, U>::value>::type* = nullptr>
270 void AppendData(const U (&array)[N]) {
271 AppendData(array, N);
272 }
273
274 template <typename W,
275 typename std::enable_if<
276 HasDataAndSize<const W, const T>::value>::type* = nullptr>
277 void AppendData(const W& w) {
278 AppendData(w.data(), w.size());
279 }
280
281 template <typename U,
282 typename std::enable_if<
283 internal::BufferCompat<T, U>::value>::type* = nullptr>
284 void AppendData(const U& item) {
285 AppendData(&item, 1);
286 }
287
Karl Wiberg09819ec2017-11-24 13:26:32 +0100288 // Appends at most |max_elements| to the end of the buffer, using the function
Henrik Kjellanderec78f1c2017-06-29 07:52:50 +0200289 // |setter|, which should have the following signature:
Karl Wiberg09819ec2017-11-24 13:26:32 +0100290 //
Henrik Kjellanderec78f1c2017-06-29 07:52:50 +0200291 // size_t setter(ArrayView<U> view)
Karl Wiberg09819ec2017-11-24 13:26:32 +0100292 //
293 // |setter| is given an appropriately typed ArrayView of length exactly
294 // |max_elements| that describes the area where it should write the data; it
295 // should return the number of elements actually written. (If it doesn't fill
296 // the whole ArrayView, it should leave the unused space at the end.)
Henrik Kjellanderec78f1c2017-06-29 07:52:50 +0200297 template <typename U = T,
298 typename F,
299 typename std::enable_if<
300 internal::BufferCompat<T, U>::value>::type* = nullptr>
301 size_t AppendData(size_t max_elements, F&& setter) {
302 RTC_DCHECK(IsConsistent());
303 const size_t old_size = size_;
304 SetSize(old_size + max_elements);
305 U* base_ptr = data<U>() + old_size;
306 size_t written_elements = setter(rtc::ArrayView<U>(base_ptr, max_elements));
307
308 RTC_CHECK_LE(written_elements, max_elements);
309 size_ = old_size + written_elements;
310 RTC_DCHECK(IsConsistent());
311 return written_elements;
312 }
313
314 // Sets the size of the buffer. If the new size is smaller than the old, the
315 // buffer contents will be kept but truncated; if the new size is greater,
316 // the existing contents will be kept and the new space will be
317 // uninitialized.
318 void SetSize(size_t size) {
Joachim Bauch5b32f232018-03-07 20:02:26 +0100319 const size_t old_size = size_;
Henrik Kjellanderec78f1c2017-06-29 07:52:50 +0200320 EnsureCapacityWithHeadroom(size, true);
321 size_ = size;
Joachim Bauch5b32f232018-03-07 20:02:26 +0100322 if (ZeroOnFree && size_ < old_size) {
323 ZeroTrailingData(old_size - size_);
324 }
Henrik Kjellanderec78f1c2017-06-29 07:52:50 +0200325 }
326
327 // Ensure that the buffer size can be increased to at least capacity without
328 // further reallocation. (Of course, this operation might need to reallocate
329 // the buffer.)
330 void EnsureCapacity(size_t capacity) {
331 // Don't allocate extra headroom, since the user is asking for a specific
332 // capacity.
333 EnsureCapacityWithHeadroom(capacity, false);
334 }
335
336 // Resets the buffer to zero size without altering capacity. Works even if the
337 // buffer has been moved from.
338 void Clear() {
Joachim Bauch5b32f232018-03-07 20:02:26 +0100339 MaybeZeroCompleteBuffer();
Henrik Kjellanderec78f1c2017-06-29 07:52:50 +0200340 size_ = 0;
341 RTC_DCHECK(IsConsistent());
342 }
343
344 // Swaps two buffers. Also works for buffers that have been moved from.
345 friend void swap(BufferT& a, BufferT& b) {
346 using std::swap;
347 swap(a.size_, b.size_);
348 swap(a.capacity_, b.capacity_);
349 swap(a.data_, b.data_);
350 }
351
352 private:
353 void EnsureCapacityWithHeadroom(size_t capacity, bool extra_headroom) {
354 RTC_DCHECK(IsConsistent());
355 if (capacity <= capacity_)
356 return;
357
358 // If the caller asks for extra headroom, ensure that the new capacity is
359 // >= 1.5 times the old capacity. Any constant > 1 is sufficient to prevent
360 // quadratic behavior; as to why we pick 1.5 in particular, see
361 // https://github.com/facebook/folly/blob/master/folly/docs/FBVector.md and
362 // http://www.gahcep.com/cpp-internals-stl-vector-part-1/.
363 const size_t new_capacity =
364 extra_headroom ? std::max(capacity, capacity_ + capacity_ / 2)
365 : capacity;
366
367 std::unique_ptr<T[]> new_data(new T[new_capacity]);
368 std::memcpy(new_data.get(), data_.get(), size_ * sizeof(T));
Joachim Bauch5b32f232018-03-07 20:02:26 +0100369 MaybeZeroCompleteBuffer();
Henrik Kjellanderec78f1c2017-06-29 07:52:50 +0200370 data_ = std::move(new_data);
371 capacity_ = new_capacity;
372 RTC_DCHECK(IsConsistent());
373 }
374
Joachim Bauch5b32f232018-03-07 20:02:26 +0100375 // Zero the complete buffer if template argument "ZeroOnFree" is true.
376 void MaybeZeroCompleteBuffer() {
377 if (ZeroOnFree && capacity_) {
378 // It would be sufficient to only zero "size_" elements, as all other
379 // methods already ensure that the unused capacity contains no sensitive
380 // data - but better safe than sorry.
381 ExplicitZeroMemory(data_.get(), capacity_ * sizeof(T));
382 }
383 }
384
385 // Zero the first "count" elements of unused capacity.
386 void ZeroTrailingData(size_t count) {
387 RTC_DCHECK(IsConsistent());
388 RTC_DCHECK_LE(count, capacity_ - size_);
389 ExplicitZeroMemory(data_.get() + size_, count * sizeof(T));
390 }
391
Henrik Kjellanderec78f1c2017-06-29 07:52:50 +0200392 // Precondition for all methods except Clear and the destructor.
393 // Postcondition for all methods except move construction and move
394 // assignment, which leave the moved-from object in a possibly inconsistent
395 // state.
396 bool IsConsistent() const {
397 return (data_ || capacity_ == 0) && capacity_ >= size_;
398 }
399
400 // Called when *this has been moved from. Conceptually it's a no-op, but we
401 // can mutate the state slightly to help subsequent sanity checks catch bugs.
402 void OnMovedFrom() {
403#if RTC_DCHECK_IS_ON
404 // Make *this consistent and empty. Shouldn't be necessary, but better safe
405 // than sorry.
406 size_ = 0;
407 capacity_ = 0;
408#else
409 // Ensure that *this is always inconsistent, to provoke bugs.
410 size_ = 1;
411 capacity_ = 0;
412#endif
413 }
414
415 size_t size_;
416 size_t capacity_;
417 std::unique_ptr<T[]> data_;
418};
419
420// By far the most common sort of buffer.
421using Buffer = BufferT<uint8_t>;
422
Joachim Bauch5b32f232018-03-07 20:02:26 +0100423// A buffer that zeros memory before releasing it.
424template <typename T>
425using ZeroOnFreeBuffer = BufferT<T, true>;
426
Henrik Kjellanderec78f1c2017-06-29 07:52:50 +0200427} // namespace rtc
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000428
Mirko Bonadei92ea95e2017-09-15 06:47:31 +0200429#endif // RTC_BASE_BUFFER_H_