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