blob: e9f7cfac1058828ce555e528b9dc601daae876ec [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
11#ifndef WEBRTC_BASE_BUFFER_H_
12#define WEBRTC_BASE_BUFFER_H_
13
Erik Språng16426202016-06-16 15:54:44 +020014#include <algorithm>
Karl Wiberg94784372015-04-20 14:03:07 +020015#include <cstring>
kwiberg8fb35572016-02-11 13:36:43 -080016#include <memory>
kwiberga4ac4782016-04-29 08:00:22 -070017#include <type_traits>
ossub01c7812016-02-24 01:05:56 -080018#include <utility>
kwiberg36220ae2016-01-12 07:24:19 -080019
ossub01c7812016-02-24 01:05:56 -080020#include "webrtc/base/array_view.h"
21#include "webrtc/base/checks.h"
henrike@webrtc.orgf0488722014-05-13 18:00:26 +000022
23namespace rtc {
24
Karl Wiberg94784372015-04-20 14:03:07 +020025namespace internal {
26
kwiberga4ac4782016-04-29 08:00:22 -070027// (Internal; please don't use outside this file.) Determines if elements of
28// type U are compatible with a BufferT<T>. For most types, we just ignore
29// top-level const and forbid top-level volatile and require T and U to be
30// otherwise equal, but all byte-sized integers (notably char, int8_t, and
31// uint8_t) are compatible with each other. (Note: We aim to get rid of this
32// behavior, and treat all types the same.)
33template <typename T, typename U>
34struct BufferCompat {
35 static constexpr bool value =
36 !std::is_volatile<U>::value &&
37 ((std::is_integral<T>::value && sizeof(T) == 1)
38 ? (std::is_integral<U>::value && sizeof(U) == 1)
39 : (std::is_same<T, typename std::remove_const<U>::type>::value));
Karl Wiberg94784372015-04-20 14:03:07 +020040};
41
42} // namespace internal
43
henrike@webrtc.orgf0488722014-05-13 18:00:26 +000044// Basic buffer class, can be grown and shrunk dynamically.
kwiberga4ac4782016-04-29 08:00:22 -070045// Unlike std::string/vector, does not initialize data when increasing size.
46template <typename T>
47class BufferT {
48 // We want T's destructor and default constructor to be trivial, i.e. perform
49 // no action, so that we don't have to touch the memory we allocate and
50 // deallocate. And we want T to be trivially copyable, so that we can copy T
51 // instances with std::memcpy. This is precisely the definition of a trivial
52 // type.
53 static_assert(std::is_trivial<T>::value, "T must be a trivial type.");
54
55 // This class relies heavily on being able to mutate its data.
56 static_assert(!std::is_const<T>::value, "T may not be const");
57
henrike@webrtc.orgf0488722014-05-13 18:00:26 +000058 public:
kwiberga4ac4782016-04-29 08:00:22 -070059 // An empty BufferT.
60 BufferT() : size_(0), capacity_(0), data_(nullptr) {
61 RTC_DCHECK(IsConsistent());
62 }
Karl Wiberg94784372015-04-20 14:03:07 +020063
kwiberga4ac4782016-04-29 08:00:22 -070064 // Disable copy construction and copy assignment, since copying a buffer is
65 // expensive enough that we want to force the user to be explicit about it.
66 BufferT(const BufferT&) = delete;
67 BufferT& operator=(const BufferT&) = delete;
Karl Wiberg94784372015-04-20 14:03:07 +020068
kwiberga4ac4782016-04-29 08:00:22 -070069 BufferT(BufferT&& buf)
70 : size_(buf.size()),
71 capacity_(buf.capacity()),
72 data_(std::move(buf.data_)) {
73 RTC_DCHECK(IsConsistent());
74 buf.OnMovedFrom();
75 }
ossub01c7812016-02-24 01:05:56 -080076
kwiberga4ac4782016-04-29 08:00:22 -070077 // Construct a buffer with the specified number of uninitialized elements.
78 explicit BufferT(size_t size) : BufferT(size, size) {}
79
80 BufferT(size_t size, size_t capacity)
81 : size_(size),
82 capacity_(std::max(size, capacity)),
83 data_(new T[capacity_]) {
84 RTC_DCHECK(IsConsistent());
85 }
86
87 // Construct a buffer and copy the specified number of elements into it.
88 template <typename U,
89 typename std::enable_if<
90 internal::BufferCompat<T, U>::value>::type* = nullptr>
91 BufferT(const U* data, size_t size) : BufferT(data, size, size) {}
92
93 template <typename U,
94 typename std::enable_if<
95 internal::BufferCompat<T, U>::value>::type* = nullptr>
96 BufferT(U* data, size_t size, size_t capacity) : BufferT(size, capacity) {
97 static_assert(sizeof(T) == sizeof(U), "");
98 std::memcpy(data_.get(), data, size * sizeof(U));
Karl Wiberg94784372015-04-20 14:03:07 +020099 }
100
101 // Construct a buffer from the contents of an array.
kwiberga4ac4782016-04-29 08:00:22 -0700102 template <typename U,
103 size_t N,
104 typename std::enable_if<
105 internal::BufferCompat<T, U>::value>::type* = nullptr>
106 BufferT(U (&array)[N]) : BufferT(array, N) {}
Karl Wiberg94784372015-04-20 14:03:07 +0200107
kwiberga4ac4782016-04-29 08:00:22 -0700108 // Get a pointer to the data. Just .data() will give you a (const) T*, but if
109 // T is a byte-sized integer, you may also use .data<U>() for any other
110 // byte-sized integer U.
111 template <typename U = T,
112 typename std::enable_if<
113 internal::BufferCompat<T, U>::value>::type* = nullptr>
114 const U* data() const {
kwiberge3d99222016-03-01 01:57:38 -0800115 RTC_DCHECK(IsConsistent());
kwiberga4ac4782016-04-29 08:00:22 -0700116 return reinterpret_cast<U*>(data_.get());
Karl Wiberg94784372015-04-20 14:03:07 +0200117 }
ossub01c7812016-02-24 01:05:56 -0800118
kwiberga4ac4782016-04-29 08:00:22 -0700119 template <typename U = T,
120 typename std::enable_if<
121 internal::BufferCompat<T, U>::value>::type* = nullptr>
122 U* data() {
kwiberge3d99222016-03-01 01:57:38 -0800123 RTC_DCHECK(IsConsistent());
kwiberga4ac4782016-04-29 08:00:22 -0700124 return reinterpret_cast<U*>(data_.get());
Karl Wiberg94784372015-04-20 14:03:07 +0200125 }
126
ossu5955e242016-08-31 08:40:04 -0700127 bool empty() const {
128 RTC_DCHECK(IsConsistent());
129 return size_ == 0;
130 }
131
Karl Wiberg94784372015-04-20 14:03:07 +0200132 size_t size() const {
kwiberge3d99222016-03-01 01:57:38 -0800133 RTC_DCHECK(IsConsistent());
Karl Wiberg94784372015-04-20 14:03:07 +0200134 return size_;
135 }
ossub01c7812016-02-24 01:05:56 -0800136
Karl Wiberg94784372015-04-20 14:03:07 +0200137 size_t capacity() const {
kwiberge3d99222016-03-01 01:57:38 -0800138 RTC_DCHECK(IsConsistent());
Karl Wiberg94784372015-04-20 14:03:07 +0200139 return capacity_;
140 }
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000141
kwiberga4ac4782016-04-29 08:00:22 -0700142 BufferT& operator=(BufferT&& buf) {
kwiberge3d99222016-03-01 01:57:38 -0800143 RTC_DCHECK(IsConsistent());
144 RTC_DCHECK(buf.IsConsistent());
Karl Wiberg94784372015-04-20 14:03:07 +0200145 size_ = buf.size_;
146 capacity_ = buf.capacity_;
kwiberg0eb15ed2015-12-17 03:04:15 -0800147 data_ = std::move(buf.data_);
Karl Wiberg94784372015-04-20 14:03:07 +0200148 buf.OnMovedFrom();
149 return *this;
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000150 }
151
kwiberga4ac4782016-04-29 08:00:22 -0700152 bool operator==(const BufferT& buf) const {
kwiberge3d99222016-03-01 01:57:38 -0800153 RTC_DCHECK(IsConsistent());
kwiberga4ac4782016-04-29 08:00:22 -0700154 if (size_ != buf.size_) {
155 return false;
156 }
157 if (std::is_integral<T>::value) {
158 // Optimization.
159 return std::memcmp(data_.get(), buf.data_.get(), size_ * sizeof(T)) == 0;
160 }
161 for (size_t i = 0; i < size_; ++i) {
162 if (data_[i] != buf.data_[i]) {
163 return false;
164 }
165 }
166 return true;
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000167 }
Karl Wiberg94784372015-04-20 14:03:07 +0200168
kwiberga4ac4782016-04-29 08:00:22 -0700169 bool operator!=(const BufferT& buf) const { return !(*this == buf); }
Karl Wiberg94784372015-04-20 14:03:07 +0200170
kwiberga4ac4782016-04-29 08:00:22 -0700171 T& operator[](size_t index) {
ossub9338ac2016-02-29 09:36:37 -0800172 RTC_DCHECK_LT(index, size_);
173 return data()[index];
174 }
175
kwiberga4ac4782016-04-29 08:00:22 -0700176 T operator[](size_t index) const {
ossub9338ac2016-02-29 09:36:37 -0800177 RTC_DCHECK_LT(index, size_);
178 return data()[index];
179 }
180
ossub01c7812016-02-24 01:05:56 -0800181 // The SetData functions replace the contents of the buffer. They accept the
182 // same input types as the constructors.
kwiberga4ac4782016-04-29 08:00:22 -0700183 template <typename U,
184 typename std::enable_if<
185 internal::BufferCompat<T, U>::value>::type* = nullptr>
186 void SetData(const U* data, size_t size) {
kwiberge3d99222016-03-01 01:57:38 -0800187 RTC_DCHECK(IsConsistent());
Karl Wiberg94784372015-04-20 14:03:07 +0200188 size_ = 0;
189 AppendData(data, size);
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000190 }
ossub01c7812016-02-24 01:05:56 -0800191
kwiberga4ac4782016-04-29 08:00:22 -0700192 template <typename U,
193 size_t N,
194 typename std::enable_if<
195 internal::BufferCompat<T, U>::value>::type* = nullptr>
196 void SetData(const U (&array)[N]) {
Karl Wiberg94784372015-04-20 14:03:07 +0200197 SetData(array, N);
198 }
ossub01c7812016-02-24 01:05:56 -0800199
kwiberga4ac4782016-04-29 08:00:22 -0700200 void SetData(const BufferT& buf) { SetData(buf.data(), buf.size()); }
Karl Wiberg94784372015-04-20 14:03:07 +0200201
kwiberga4ac4782016-04-29 08:00:22 -0700202 // Replace the data in the buffer with at most |max_elements| of data, using
203 // the function |setter|, which should have the following signature:
204 // size_t setter(ArrayView<U> view)
ossub01c7812016-02-24 01:05:56 -0800205 // |setter| is given an appropriately typed ArrayView of the area in which to
206 // write the data (i.e. starting at the beginning of the buffer) and should
kwiberga4ac4782016-04-29 08:00:22 -0700207 // return the number of elements actually written. This number must be <=
208 // |max_elements|.
209 template <typename U = T,
210 typename F,
211 typename std::enable_if<
212 internal::BufferCompat<T, U>::value>::type* = nullptr>
213 size_t SetData(size_t max_elements, F&& setter) {
ossub01c7812016-02-24 01:05:56 -0800214 RTC_DCHECK(IsConsistent());
215 size_ = 0;
kwiberga4ac4782016-04-29 08:00:22 -0700216 return AppendData<U>(max_elements, std::forward<F>(setter));
ossub01c7812016-02-24 01:05:56 -0800217 }
218
kwiberga4ac4782016-04-29 08:00:22 -0700219 // The AppendData functions add data to the end of the buffer. They accept
ossub01c7812016-02-24 01:05:56 -0800220 // the same input types as the constructors.
kwiberga4ac4782016-04-29 08:00:22 -0700221 template <typename U,
222 typename std::enable_if<
223 internal::BufferCompat<T, U>::value>::type* = nullptr>
224 void AppendData(const U* data, size_t size) {
kwiberge3d99222016-03-01 01:57:38 -0800225 RTC_DCHECK(IsConsistent());
Karl Wiberg94784372015-04-20 14:03:07 +0200226 const size_t new_size = size_ + size;
kwibergc8535972016-06-20 04:47:39 -0700227 EnsureCapacityWithHeadroom(new_size, true);
kwiberga4ac4782016-04-29 08:00:22 -0700228 static_assert(sizeof(T) == sizeof(U), "");
229 std::memcpy(data_.get() + size_, data, size * sizeof(U));
Karl Wiberg94784372015-04-20 14:03:07 +0200230 size_ = new_size;
kwiberge3d99222016-03-01 01:57:38 -0800231 RTC_DCHECK(IsConsistent());
Karl Wiberg94784372015-04-20 14:03:07 +0200232 }
ossub01c7812016-02-24 01:05:56 -0800233
kwiberga4ac4782016-04-29 08:00:22 -0700234 template <typename U,
235 size_t N,
236 typename std::enable_if<
237 internal::BufferCompat<T, U>::value>::type* = nullptr>
238 void AppendData(const U (&array)[N]) {
Karl Wiberg94784372015-04-20 14:03:07 +0200239 AppendData(array, N);
240 }
ossub01c7812016-02-24 01:05:56 -0800241
kwiberga4ac4782016-04-29 08:00:22 -0700242 void AppendData(const BufferT& buf) { AppendData(buf.data(), buf.size()); }
Karl Wiberg94784372015-04-20 14:03:07 +0200243
sprang52033d62016-06-02 02:43:32 -0700244 template <typename U,
245 typename std::enable_if<
246 internal::BufferCompat<T, U>::value>::type* = nullptr>
247 void AppendData(const U& item) {
248 AppendData(&item, 1);
249 }
250
kwiberga4ac4782016-04-29 08:00:22 -0700251 // Append at most |max_elements| to the end of the buffer, using the function
252 // |setter|, which should have the following signature:
253 // size_t setter(ArrayView<U> view)
ossub01c7812016-02-24 01:05:56 -0800254 // |setter| is given an appropriately typed ArrayView of the area in which to
255 // write the data (i.e. starting at the former end of the buffer) and should
kwiberga4ac4782016-04-29 08:00:22 -0700256 // return the number of elements actually written. This number must be <=
257 // |max_elements|.
258 template <typename U = T,
259 typename F,
260 typename std::enable_if<
261 internal::BufferCompat<T, U>::value>::type* = nullptr>
262 size_t AppendData(size_t max_elements, F&& setter) {
ossub01c7812016-02-24 01:05:56 -0800263 RTC_DCHECK(IsConsistent());
264 const size_t old_size = size_;
kwiberga4ac4782016-04-29 08:00:22 -0700265 SetSize(old_size + max_elements);
266 U* base_ptr = data<U>() + old_size;
267 size_t written_elements = setter(rtc::ArrayView<U>(base_ptr, max_elements));
ossub01c7812016-02-24 01:05:56 -0800268
kwiberga4ac4782016-04-29 08:00:22 -0700269 RTC_CHECK_LE(written_elements, max_elements);
270 size_ = old_size + written_elements;
ossub01c7812016-02-24 01:05:56 -0800271 RTC_DCHECK(IsConsistent());
kwiberga4ac4782016-04-29 08:00:22 -0700272 return written_elements;
ossub01c7812016-02-24 01:05:56 -0800273 }
274
Karl Wiberg94784372015-04-20 14:03:07 +0200275 // Sets the size of the buffer. If the new size is smaller than the old, the
276 // buffer contents will be kept but truncated; if the new size is greater,
277 // the existing contents will be kept and the new space will be
278 // uninitialized.
kwiberg@webrtc.orgeebcab52015-03-24 09:19:06 +0000279 void SetSize(size_t size) {
kwibergc8535972016-06-20 04:47:39 -0700280 EnsureCapacityWithHeadroom(size, true);
kwiberg@webrtc.orgeebcab52015-03-24 09:19:06 +0000281 size_ = size;
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000282 }
Karl Wiberg94784372015-04-20 14:03:07 +0200283
284 // Ensure that the buffer size can be increased to at least capacity without
285 // further reallocation. (Of course, this operation might need to reallocate
286 // the buffer.)
287 void EnsureCapacity(size_t capacity) {
kwibergc8535972016-06-20 04:47:39 -0700288 // Don't allocate extra headroom, since the user is asking for a specific
289 // capacity.
290 EnsureCapacityWithHeadroom(capacity, false);
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000291 }
292
ossu728012e2016-02-19 02:38:32 -0800293 // Resets the buffer to zero size without altering capacity. Works even if the
294 // buffer has been moved from.
Karl Wiberg94784372015-04-20 14:03:07 +0200295 void Clear() {
Karl Wiberg94784372015-04-20 14:03:07 +0200296 size_ = 0;
kwiberge3d99222016-03-01 01:57:38 -0800297 RTC_DCHECK(IsConsistent());
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000298 }
299
Karl Wiberg94784372015-04-20 14:03:07 +0200300 // Swaps two buffers. Also works for buffers that have been moved from.
kwiberga4ac4782016-04-29 08:00:22 -0700301 friend void swap(BufferT& a, BufferT& b) {
Karl Wiberg94784372015-04-20 14:03:07 +0200302 using std::swap;
303 swap(a.size_, b.size_);
304 swap(a.capacity_, b.capacity_);
305 swap(a.data_, b.data_);
306 }
307
308 private:
kwibergc8535972016-06-20 04:47:39 -0700309 void EnsureCapacityWithHeadroom(size_t capacity, bool extra_headroom) {
310 RTC_DCHECK(IsConsistent());
311 if (capacity <= capacity_)
312 return;
313
314 // If the caller asks for extra headroom, ensure that the new capacity is
315 // >= 1.5 times the old capacity. Any constant > 1 is sufficient to prevent
316 // quadratic behavior; as to why we pick 1.5 in particular, see
317 // https://github.com/facebook/folly/blob/master/folly/docs/FBVector.md and
318 // http://www.gahcep.com/cpp-internals-stl-vector-part-1/.
319 const size_t new_capacity =
320 extra_headroom ? std::max(capacity, capacity_ + capacity_ / 2)
321 : capacity;
322
323 std::unique_ptr<T[]> new_data(new T[new_capacity]);
324 std::memcpy(new_data.get(), data_.get(), size_ * sizeof(T));
325 data_ = std::move(new_data);
326 capacity_ = new_capacity;
327 RTC_DCHECK(IsConsistent());
328 }
329
Karl Wiberg94784372015-04-20 14:03:07 +0200330 // Precondition for all methods except Clear and the destructor.
331 // Postcondition for all methods except move construction and move
332 // assignment, which leave the moved-from object in a possibly inconsistent
333 // state.
334 bool IsConsistent() const {
335 return (data_ || capacity_ == 0) && capacity_ >= size_;
336 }
337
338 // Called when *this has been moved from. Conceptually it's a no-op, but we
339 // can mutate the state slightly to help subsequent sanity checks catch bugs.
340 void OnMovedFrom() {
341#ifdef NDEBUG
342 // Make *this consistent and empty. Shouldn't be necessary, but better safe
343 // than sorry.
344 size_ = 0;
345 capacity_ = 0;
346#else
347 // Ensure that *this is always inconsistent, to provoke bugs.
348 size_ = 1;
349 capacity_ = 0;
350#endif
351 }
352
kwiberg@webrtc.orgeebcab52015-03-24 09:19:06 +0000353 size_t size_;
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000354 size_t capacity_;
kwiberga4ac4782016-04-29 08:00:22 -0700355 std::unique_ptr<T[]> data_;
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000356};
357
kwiberga4ac4782016-04-29 08:00:22 -0700358// By far the most common sort of buffer.
359using Buffer = BufferT<uint8_t>;
360
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000361} // namespace rtc
362
363#endif // WEBRTC_BASE_BUFFER_H_