blob: 6ae49f7a8f74e07816d362f5f1032b043f5f1c68 [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"
kwibergd3134032016-09-05 07:46:20 -070022#include "webrtc/base/type_traits.h"
henrike@webrtc.orgf0488722014-05-13 18:00:26 +000023
24namespace rtc {
25
Karl Wiberg94784372015-04-20 14:03:07 +020026namespace internal {
27
kwiberga4ac4782016-04-29 08:00:22 -070028// (Internal; please don't use outside this file.) Determines if elements of
29// type U are compatible with a BufferT<T>. For most types, we just ignore
30// top-level const and forbid top-level volatile and require T and U to be
31// otherwise equal, but all byte-sized integers (notably char, int8_t, and
32// uint8_t) are compatible with each other. (Note: We aim to get rid of this
33// behavior, and treat all types the same.)
34template <typename T, typename U>
35struct BufferCompat {
36 static constexpr bool value =
37 !std::is_volatile<U>::value &&
38 ((std::is_integral<T>::value && sizeof(T) == 1)
39 ? (std::is_integral<U>::value && sizeof(U) == 1)
40 : (std::is_same<T, typename std::remove_const<U>::type>::value));
Karl Wiberg94784372015-04-20 14:03:07 +020041};
42
43} // namespace internal
44
henrike@webrtc.orgf0488722014-05-13 18:00:26 +000045// Basic buffer class, can be grown and shrunk dynamically.
kwiberga4ac4782016-04-29 08:00:22 -070046// Unlike std::string/vector, does not initialize data when increasing size.
47template <typename T>
48class BufferT {
49 // We want T's destructor and default constructor to be trivial, i.e. perform
50 // no action, so that we don't have to touch the memory we allocate and
51 // deallocate. And we want T to be trivially copyable, so that we can copy T
52 // instances with std::memcpy. This is precisely the definition of a trivial
53 // type.
54 static_assert(std::is_trivial<T>::value, "T must be a trivial type.");
55
56 // This class relies heavily on being able to mutate its data.
57 static_assert(!std::is_const<T>::value, "T may not be const");
58
henrike@webrtc.orgf0488722014-05-13 18:00:26 +000059 public:
kwiberga4ac4782016-04-29 08:00:22 -070060 // An empty BufferT.
61 BufferT() : size_(0), capacity_(0), data_(nullptr) {
62 RTC_DCHECK(IsConsistent());
63 }
Karl Wiberg94784372015-04-20 14:03:07 +020064
kwiberga4ac4782016-04-29 08:00:22 -070065 // Disable copy construction and copy assignment, since copying a buffer is
66 // expensive enough that we want to force the user to be explicit about it.
67 BufferT(const BufferT&) = delete;
68 BufferT& operator=(const BufferT&) = delete;
Karl Wiberg94784372015-04-20 14:03:07 +020069
kwiberga4ac4782016-04-29 08:00:22 -070070 BufferT(BufferT&& buf)
71 : size_(buf.size()),
72 capacity_(buf.capacity()),
73 data_(std::move(buf.data_)) {
74 RTC_DCHECK(IsConsistent());
75 buf.OnMovedFrom();
76 }
ossub01c7812016-02-24 01:05:56 -080077
kwiberga4ac4782016-04-29 08:00:22 -070078 // Construct a buffer with the specified number of uninitialized elements.
79 explicit BufferT(size_t size) : BufferT(size, size) {}
80
81 BufferT(size_t size, size_t capacity)
82 : size_(size),
83 capacity_(std::max(size, capacity)),
84 data_(new T[capacity_]) {
85 RTC_DCHECK(IsConsistent());
86 }
87
88 // Construct a buffer and copy the specified number of elements into it.
89 template <typename U,
90 typename std::enable_if<
91 internal::BufferCompat<T, U>::value>::type* = nullptr>
92 BufferT(const U* data, size_t size) : BufferT(data, size, size) {}
93
94 template <typename U,
95 typename std::enable_if<
96 internal::BufferCompat<T, U>::value>::type* = nullptr>
97 BufferT(U* data, size_t size, size_t capacity) : BufferT(size, capacity) {
98 static_assert(sizeof(T) == sizeof(U), "");
99 std::memcpy(data_.get(), data, size * sizeof(U));
Karl Wiberg94784372015-04-20 14:03:07 +0200100 }
101
102 // Construct a buffer from the contents of an array.
kwiberga4ac4782016-04-29 08:00:22 -0700103 template <typename U,
104 size_t N,
105 typename std::enable_if<
106 internal::BufferCompat<T, U>::value>::type* = nullptr>
107 BufferT(U (&array)[N]) : BufferT(array, N) {}
Karl Wiberg94784372015-04-20 14:03:07 +0200108
kwiberga4ac4782016-04-29 08:00:22 -0700109 // Get a pointer to the data. Just .data() will give you a (const) T*, but if
110 // T is a byte-sized integer, you may also use .data<U>() for any other
111 // byte-sized integer U.
112 template <typename U = T,
113 typename std::enable_if<
114 internal::BufferCompat<T, U>::value>::type* = nullptr>
115 const U* data() const {
kwiberge3d99222016-03-01 01:57:38 -0800116 RTC_DCHECK(IsConsistent());
kwiberga4ac4782016-04-29 08:00:22 -0700117 return reinterpret_cast<U*>(data_.get());
Karl Wiberg94784372015-04-20 14:03:07 +0200118 }
ossub01c7812016-02-24 01:05:56 -0800119
kwiberga4ac4782016-04-29 08:00:22 -0700120 template <typename U = T,
121 typename std::enable_if<
122 internal::BufferCompat<T, U>::value>::type* = nullptr>
123 U* data() {
kwiberge3d99222016-03-01 01:57:38 -0800124 RTC_DCHECK(IsConsistent());
kwiberga4ac4782016-04-29 08:00:22 -0700125 return reinterpret_cast<U*>(data_.get());
Karl Wiberg94784372015-04-20 14:03:07 +0200126 }
127
ossu5955e242016-08-31 08:40:04 -0700128 bool empty() const {
129 RTC_DCHECK(IsConsistent());
130 return size_ == 0;
131 }
132
Karl Wiberg94784372015-04-20 14:03:07 +0200133 size_t size() const {
kwiberge3d99222016-03-01 01:57:38 -0800134 RTC_DCHECK(IsConsistent());
Karl Wiberg94784372015-04-20 14:03:07 +0200135 return size_;
136 }
ossub01c7812016-02-24 01:05:56 -0800137
Karl Wiberg94784372015-04-20 14:03:07 +0200138 size_t capacity() const {
kwiberge3d99222016-03-01 01:57:38 -0800139 RTC_DCHECK(IsConsistent());
Karl Wiberg94784372015-04-20 14:03:07 +0200140 return capacity_;
141 }
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000142
kwiberga4ac4782016-04-29 08:00:22 -0700143 BufferT& operator=(BufferT&& buf) {
kwiberge3d99222016-03-01 01:57:38 -0800144 RTC_DCHECK(IsConsistent());
145 RTC_DCHECK(buf.IsConsistent());
Karl Wiberg94784372015-04-20 14:03:07 +0200146 size_ = buf.size_;
147 capacity_ = buf.capacity_;
kwiberg0eb15ed2015-12-17 03:04:15 -0800148 data_ = std::move(buf.data_);
Karl Wiberg94784372015-04-20 14:03:07 +0200149 buf.OnMovedFrom();
150 return *this;
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000151 }
152
kwiberga4ac4782016-04-29 08:00:22 -0700153 bool operator==(const BufferT& buf) const {
kwiberge3d99222016-03-01 01:57:38 -0800154 RTC_DCHECK(IsConsistent());
kwiberga4ac4782016-04-29 08:00:22 -0700155 if (size_ != buf.size_) {
156 return false;
157 }
158 if (std::is_integral<T>::value) {
159 // Optimization.
160 return std::memcmp(data_.get(), buf.data_.get(), size_ * sizeof(T)) == 0;
161 }
162 for (size_t i = 0; i < size_; ++i) {
163 if (data_[i] != buf.data_[i]) {
164 return false;
165 }
166 }
167 return true;
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000168 }
Karl Wiberg94784372015-04-20 14:03:07 +0200169
kwiberga4ac4782016-04-29 08:00:22 -0700170 bool operator!=(const BufferT& buf) const { return !(*this == buf); }
Karl Wiberg94784372015-04-20 14:03:07 +0200171
kwiberga4ac4782016-04-29 08:00:22 -0700172 T& operator[](size_t index) {
ossub9338ac2016-02-29 09:36:37 -0800173 RTC_DCHECK_LT(index, size_);
174 return data()[index];
175 }
176
kwiberga4ac4782016-04-29 08:00:22 -0700177 T operator[](size_t index) const {
ossub9338ac2016-02-29 09:36:37 -0800178 RTC_DCHECK_LT(index, size_);
179 return data()[index];
180 }
181
ossub01c7812016-02-24 01:05:56 -0800182 // The SetData functions replace the contents of the buffer. They accept the
183 // same input types as the constructors.
kwiberga4ac4782016-04-29 08:00:22 -0700184 template <typename U,
185 typename std::enable_if<
186 internal::BufferCompat<T, U>::value>::type* = nullptr>
187 void SetData(const U* data, size_t size) {
kwiberge3d99222016-03-01 01:57:38 -0800188 RTC_DCHECK(IsConsistent());
Karl Wiberg94784372015-04-20 14:03:07 +0200189 size_ = 0;
190 AppendData(data, size);
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000191 }
ossub01c7812016-02-24 01:05:56 -0800192
kwiberga4ac4782016-04-29 08:00:22 -0700193 template <typename U,
194 size_t N,
195 typename std::enable_if<
196 internal::BufferCompat<T, U>::value>::type* = nullptr>
197 void SetData(const U (&array)[N]) {
Karl Wiberg94784372015-04-20 14:03:07 +0200198 SetData(array, N);
199 }
ossub01c7812016-02-24 01:05:56 -0800200
kwibergd3134032016-09-05 07:46:20 -0700201 template <typename W,
202 typename std::enable_if<
203 HasDataAndSize<const W, const T>::value>::type* = nullptr>
204 void SetData(const W& w) {
205 SetData(w.data(), w.size());
206 }
Karl Wiberg94784372015-04-20 14:03:07 +0200207
kwiberga4ac4782016-04-29 08:00:22 -0700208 // Replace the data in the buffer with at most |max_elements| of data, using
209 // the function |setter|, which should have the following signature:
210 // size_t setter(ArrayView<U> view)
ossub01c7812016-02-24 01:05:56 -0800211 // |setter| is given an appropriately typed ArrayView of the area in which to
212 // write the data (i.e. starting at the beginning of the buffer) and should
kwiberga4ac4782016-04-29 08:00:22 -0700213 // return the number of elements actually written. This number must be <=
214 // |max_elements|.
215 template <typename U = T,
216 typename F,
217 typename std::enable_if<
218 internal::BufferCompat<T, U>::value>::type* = nullptr>
219 size_t SetData(size_t max_elements, F&& setter) {
ossub01c7812016-02-24 01:05:56 -0800220 RTC_DCHECK(IsConsistent());
221 size_ = 0;
kwiberga4ac4782016-04-29 08:00:22 -0700222 return AppendData<U>(max_elements, std::forward<F>(setter));
ossub01c7812016-02-24 01:05:56 -0800223 }
224
kwiberga4ac4782016-04-29 08:00:22 -0700225 // The AppendData functions add data to the end of the buffer. They accept
ossub01c7812016-02-24 01:05:56 -0800226 // the same input types as the constructors.
kwiberga4ac4782016-04-29 08:00:22 -0700227 template <typename U,
228 typename std::enable_if<
229 internal::BufferCompat<T, U>::value>::type* = nullptr>
230 void AppendData(const U* data, size_t size) {
kwiberge3d99222016-03-01 01:57:38 -0800231 RTC_DCHECK(IsConsistent());
Karl Wiberg94784372015-04-20 14:03:07 +0200232 const size_t new_size = size_ + size;
kwibergc8535972016-06-20 04:47:39 -0700233 EnsureCapacityWithHeadroom(new_size, true);
kwiberga4ac4782016-04-29 08:00:22 -0700234 static_assert(sizeof(T) == sizeof(U), "");
235 std::memcpy(data_.get() + size_, data, size * sizeof(U));
Karl Wiberg94784372015-04-20 14:03:07 +0200236 size_ = new_size;
kwiberge3d99222016-03-01 01:57:38 -0800237 RTC_DCHECK(IsConsistent());
Karl Wiberg94784372015-04-20 14:03:07 +0200238 }
ossub01c7812016-02-24 01:05:56 -0800239
kwiberga4ac4782016-04-29 08:00:22 -0700240 template <typename U,
241 size_t N,
242 typename std::enable_if<
243 internal::BufferCompat<T, U>::value>::type* = nullptr>
244 void AppendData(const U (&array)[N]) {
Karl Wiberg94784372015-04-20 14:03:07 +0200245 AppendData(array, N);
246 }
ossub01c7812016-02-24 01:05:56 -0800247
kwibergd3134032016-09-05 07:46:20 -0700248 template <typename W,
249 typename std::enable_if<
250 HasDataAndSize<const W, const T>::value>::type* = nullptr>
251 void AppendData(const W& w) {
252 AppendData(w.data(), w.size());
253 }
Karl Wiberg94784372015-04-20 14:03:07 +0200254
sprang52033d62016-06-02 02:43:32 -0700255 template <typename U,
256 typename std::enable_if<
257 internal::BufferCompat<T, U>::value>::type* = nullptr>
258 void AppendData(const U& item) {
259 AppendData(&item, 1);
260 }
261
kwiberga4ac4782016-04-29 08:00:22 -0700262 // Append at most |max_elements| to the end of the buffer, using the function
263 // |setter|, which should have the following signature:
264 // size_t setter(ArrayView<U> view)
ossub01c7812016-02-24 01:05:56 -0800265 // |setter| is given an appropriately typed ArrayView of the area in which to
266 // write the data (i.e. starting at the former end of the buffer) and should
kwiberga4ac4782016-04-29 08:00:22 -0700267 // return the number of elements actually written. This number must be <=
268 // |max_elements|.
269 template <typename U = T,
270 typename F,
271 typename std::enable_if<
272 internal::BufferCompat<T, U>::value>::type* = nullptr>
273 size_t AppendData(size_t max_elements, F&& setter) {
ossub01c7812016-02-24 01:05:56 -0800274 RTC_DCHECK(IsConsistent());
275 const size_t old_size = size_;
kwiberga4ac4782016-04-29 08:00:22 -0700276 SetSize(old_size + max_elements);
277 U* base_ptr = data<U>() + old_size;
278 size_t written_elements = setter(rtc::ArrayView<U>(base_ptr, max_elements));
ossub01c7812016-02-24 01:05:56 -0800279
kwiberga4ac4782016-04-29 08:00:22 -0700280 RTC_CHECK_LE(written_elements, max_elements);
281 size_ = old_size + written_elements;
ossub01c7812016-02-24 01:05:56 -0800282 RTC_DCHECK(IsConsistent());
kwiberga4ac4782016-04-29 08:00:22 -0700283 return written_elements;
ossub01c7812016-02-24 01:05:56 -0800284 }
285
Karl Wiberg94784372015-04-20 14:03:07 +0200286 // Sets the size of the buffer. If the new size is smaller than the old, the
287 // buffer contents will be kept but truncated; if the new size is greater,
288 // the existing contents will be kept and the new space will be
289 // uninitialized.
kwiberg@webrtc.orgeebcab52015-03-24 09:19:06 +0000290 void SetSize(size_t size) {
kwibergc8535972016-06-20 04:47:39 -0700291 EnsureCapacityWithHeadroom(size, true);
kwiberg@webrtc.orgeebcab52015-03-24 09:19:06 +0000292 size_ = size;
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000293 }
Karl Wiberg94784372015-04-20 14:03:07 +0200294
295 // Ensure that the buffer size can be increased to at least capacity without
296 // further reallocation. (Of course, this operation might need to reallocate
297 // the buffer.)
298 void EnsureCapacity(size_t capacity) {
kwibergc8535972016-06-20 04:47:39 -0700299 // Don't allocate extra headroom, since the user is asking for a specific
300 // capacity.
301 EnsureCapacityWithHeadroom(capacity, false);
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000302 }
303
ossu728012e2016-02-19 02:38:32 -0800304 // Resets the buffer to zero size without altering capacity. Works even if the
305 // buffer has been moved from.
Karl Wiberg94784372015-04-20 14:03:07 +0200306 void Clear() {
Karl Wiberg94784372015-04-20 14:03:07 +0200307 size_ = 0;
kwiberge3d99222016-03-01 01:57:38 -0800308 RTC_DCHECK(IsConsistent());
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000309 }
310
Karl Wiberg94784372015-04-20 14:03:07 +0200311 // Swaps two buffers. Also works for buffers that have been moved from.
kwiberga4ac4782016-04-29 08:00:22 -0700312 friend void swap(BufferT& a, BufferT& b) {
Karl Wiberg94784372015-04-20 14:03:07 +0200313 using std::swap;
314 swap(a.size_, b.size_);
315 swap(a.capacity_, b.capacity_);
316 swap(a.data_, b.data_);
317 }
318
319 private:
kwibergc8535972016-06-20 04:47:39 -0700320 void EnsureCapacityWithHeadroom(size_t capacity, bool extra_headroom) {
321 RTC_DCHECK(IsConsistent());
322 if (capacity <= capacity_)
323 return;
324
325 // If the caller asks for extra headroom, ensure that the new capacity is
326 // >= 1.5 times the old capacity. Any constant > 1 is sufficient to prevent
327 // quadratic behavior; as to why we pick 1.5 in particular, see
328 // https://github.com/facebook/folly/blob/master/folly/docs/FBVector.md and
329 // http://www.gahcep.com/cpp-internals-stl-vector-part-1/.
330 const size_t new_capacity =
331 extra_headroom ? std::max(capacity, capacity_ + capacity_ / 2)
332 : capacity;
333
334 std::unique_ptr<T[]> new_data(new T[new_capacity]);
335 std::memcpy(new_data.get(), data_.get(), size_ * sizeof(T));
336 data_ = std::move(new_data);
337 capacity_ = new_capacity;
338 RTC_DCHECK(IsConsistent());
339 }
340
Karl Wiberg94784372015-04-20 14:03:07 +0200341 // Precondition for all methods except Clear and the destructor.
342 // Postcondition for all methods except move construction and move
343 // assignment, which leave the moved-from object in a possibly inconsistent
344 // state.
345 bool IsConsistent() const {
346 return (data_ || capacity_ == 0) && capacity_ >= size_;
347 }
348
349 // Called when *this has been moved from. Conceptually it's a no-op, but we
350 // can mutate the state slightly to help subsequent sanity checks catch bugs.
351 void OnMovedFrom() {
guidou8f901062016-10-03 08:32:31 -0700352#ifdef NDEBUG
Karl Wiberg94784372015-04-20 14:03:07 +0200353 // Make *this consistent and empty. Shouldn't be necessary, but better safe
354 // than sorry.
355 size_ = 0;
356 capacity_ = 0;
357#else
358 // Ensure that *this is always inconsistent, to provoke bugs.
359 size_ = 1;
360 capacity_ = 0;
361#endif
362 }
363
kwiberg@webrtc.orgeebcab52015-03-24 09:19:06 +0000364 size_t size_;
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000365 size_t capacity_;
kwiberga4ac4782016-04-29 08:00:22 -0700366 std::unique_ptr<T[]> data_;
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000367};
368
kwiberga4ac4782016-04-29 08:00:22 -0700369// By far the most common sort of buffer.
370using Buffer = BufferT<uint8_t>;
371
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000372} // namespace rtc
373
374#endif // WEBRTC_BASE_BUFFER_H_