blob: 545ddb2be7cc91df5b2b695948d1610abe9fe331 [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
127 size_t size() const {
kwiberge3d99222016-03-01 01:57:38 -0800128 RTC_DCHECK(IsConsistent());
Karl Wiberg94784372015-04-20 14:03:07 +0200129 return size_;
130 }
ossub01c7812016-02-24 01:05:56 -0800131
Karl Wiberg94784372015-04-20 14:03:07 +0200132 size_t capacity() const {
kwiberge3d99222016-03-01 01:57:38 -0800133 RTC_DCHECK(IsConsistent());
Karl Wiberg94784372015-04-20 14:03:07 +0200134 return capacity_;
135 }
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000136
kwiberga4ac4782016-04-29 08:00:22 -0700137 BufferT& operator=(BufferT&& buf) {
kwiberge3d99222016-03-01 01:57:38 -0800138 RTC_DCHECK(IsConsistent());
139 RTC_DCHECK(buf.IsConsistent());
Karl Wiberg94784372015-04-20 14:03:07 +0200140 size_ = buf.size_;
141 capacity_ = buf.capacity_;
kwiberg0eb15ed2015-12-17 03:04:15 -0800142 data_ = std::move(buf.data_);
Karl Wiberg94784372015-04-20 14:03:07 +0200143 buf.OnMovedFrom();
144 return *this;
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000145 }
146
kwiberga4ac4782016-04-29 08:00:22 -0700147 bool operator==(const BufferT& buf) const {
kwiberge3d99222016-03-01 01:57:38 -0800148 RTC_DCHECK(IsConsistent());
kwiberga4ac4782016-04-29 08:00:22 -0700149 if (size_ != buf.size_) {
150 return false;
151 }
152 if (std::is_integral<T>::value) {
153 // Optimization.
154 return std::memcmp(data_.get(), buf.data_.get(), size_ * sizeof(T)) == 0;
155 }
156 for (size_t i = 0; i < size_; ++i) {
157 if (data_[i] != buf.data_[i]) {
158 return false;
159 }
160 }
161 return true;
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000162 }
Karl Wiberg94784372015-04-20 14:03:07 +0200163
kwiberga4ac4782016-04-29 08:00:22 -0700164 bool operator!=(const BufferT& buf) const { return !(*this == buf); }
Karl Wiberg94784372015-04-20 14:03:07 +0200165
kwiberga4ac4782016-04-29 08:00:22 -0700166 T& operator[](size_t index) {
ossub9338ac2016-02-29 09:36:37 -0800167 RTC_DCHECK_LT(index, size_);
168 return data()[index];
169 }
170
kwiberga4ac4782016-04-29 08:00:22 -0700171 T operator[](size_t index) const {
ossub9338ac2016-02-29 09:36:37 -0800172 RTC_DCHECK_LT(index, size_);
173 return data()[index];
174 }
175
ossub01c7812016-02-24 01:05:56 -0800176 // The SetData functions replace the contents of the buffer. They accept the
177 // same input types as the constructors.
kwiberga4ac4782016-04-29 08:00:22 -0700178 template <typename U,
179 typename std::enable_if<
180 internal::BufferCompat<T, U>::value>::type* = nullptr>
181 void SetData(const U* data, size_t size) {
kwiberge3d99222016-03-01 01:57:38 -0800182 RTC_DCHECK(IsConsistent());
Karl Wiberg94784372015-04-20 14:03:07 +0200183 size_ = 0;
184 AppendData(data, size);
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000185 }
ossub01c7812016-02-24 01:05:56 -0800186
kwiberga4ac4782016-04-29 08:00:22 -0700187 template <typename U,
188 size_t N,
189 typename std::enable_if<
190 internal::BufferCompat<T, U>::value>::type* = nullptr>
191 void SetData(const U (&array)[N]) {
Karl Wiberg94784372015-04-20 14:03:07 +0200192 SetData(array, N);
193 }
ossub01c7812016-02-24 01:05:56 -0800194
kwiberga4ac4782016-04-29 08:00:22 -0700195 void SetData(const BufferT& buf) { SetData(buf.data(), buf.size()); }
Karl Wiberg94784372015-04-20 14:03:07 +0200196
kwiberga4ac4782016-04-29 08:00:22 -0700197 // Replace the data in the buffer with at most |max_elements| of data, using
198 // the function |setter|, which should have the following signature:
199 // size_t setter(ArrayView<U> view)
ossub01c7812016-02-24 01:05:56 -0800200 // |setter| is given an appropriately typed ArrayView of the area in which to
201 // write the data (i.e. starting at the beginning of the buffer) and should
kwiberga4ac4782016-04-29 08:00:22 -0700202 // return the number of elements actually written. This number must be <=
203 // |max_elements|.
204 template <typename U = T,
205 typename F,
206 typename std::enable_if<
207 internal::BufferCompat<T, U>::value>::type* = nullptr>
208 size_t SetData(size_t max_elements, F&& setter) {
ossub01c7812016-02-24 01:05:56 -0800209 RTC_DCHECK(IsConsistent());
210 size_ = 0;
kwiberga4ac4782016-04-29 08:00:22 -0700211 return AppendData<U>(max_elements, std::forward<F>(setter));
ossub01c7812016-02-24 01:05:56 -0800212 }
213
kwiberga4ac4782016-04-29 08:00:22 -0700214 // The AppendData functions add data to the end of the buffer. They accept
ossub01c7812016-02-24 01:05:56 -0800215 // the same input types as the constructors.
kwiberga4ac4782016-04-29 08:00:22 -0700216 template <typename U,
217 typename std::enable_if<
218 internal::BufferCompat<T, U>::value>::type* = nullptr>
219 void AppendData(const U* data, size_t size) {
kwiberge3d99222016-03-01 01:57:38 -0800220 RTC_DCHECK(IsConsistent());
Karl Wiberg94784372015-04-20 14:03:07 +0200221 const size_t new_size = size_ + size;
kwibergc8535972016-06-20 04:47:39 -0700222 EnsureCapacityWithHeadroom(new_size, true);
kwiberga4ac4782016-04-29 08:00:22 -0700223 static_assert(sizeof(T) == sizeof(U), "");
224 std::memcpy(data_.get() + size_, data, size * sizeof(U));
Karl Wiberg94784372015-04-20 14:03:07 +0200225 size_ = new_size;
kwiberge3d99222016-03-01 01:57:38 -0800226 RTC_DCHECK(IsConsistent());
Karl Wiberg94784372015-04-20 14:03:07 +0200227 }
ossub01c7812016-02-24 01:05:56 -0800228
kwiberga4ac4782016-04-29 08:00:22 -0700229 template <typename U,
230 size_t N,
231 typename std::enable_if<
232 internal::BufferCompat<T, U>::value>::type* = nullptr>
233 void AppendData(const U (&array)[N]) {
Karl Wiberg94784372015-04-20 14:03:07 +0200234 AppendData(array, N);
235 }
ossub01c7812016-02-24 01:05:56 -0800236
kwiberga4ac4782016-04-29 08:00:22 -0700237 void AppendData(const BufferT& buf) { AppendData(buf.data(), buf.size()); }
Karl Wiberg94784372015-04-20 14:03:07 +0200238
sprang52033d62016-06-02 02:43:32 -0700239 template <typename U,
240 typename std::enable_if<
241 internal::BufferCompat<T, U>::value>::type* = nullptr>
242 void AppendData(const U& item) {
243 AppendData(&item, 1);
244 }
245
kwiberga4ac4782016-04-29 08:00:22 -0700246 // Append at most |max_elements| to the end of the buffer, using the function
247 // |setter|, which should have the following signature:
248 // size_t setter(ArrayView<U> view)
ossub01c7812016-02-24 01:05:56 -0800249 // |setter| is given an appropriately typed ArrayView of the area in which to
250 // write the data (i.e. starting at the former end of the buffer) and should
kwiberga4ac4782016-04-29 08:00:22 -0700251 // return the number of elements actually written. This number must be <=
252 // |max_elements|.
253 template <typename U = T,
254 typename F,
255 typename std::enable_if<
256 internal::BufferCompat<T, U>::value>::type* = nullptr>
257 size_t AppendData(size_t max_elements, F&& setter) {
ossub01c7812016-02-24 01:05:56 -0800258 RTC_DCHECK(IsConsistent());
259 const size_t old_size = size_;
kwiberga4ac4782016-04-29 08:00:22 -0700260 SetSize(old_size + max_elements);
261 U* base_ptr = data<U>() + old_size;
262 size_t written_elements = setter(rtc::ArrayView<U>(base_ptr, max_elements));
ossub01c7812016-02-24 01:05:56 -0800263
kwiberga4ac4782016-04-29 08:00:22 -0700264 RTC_CHECK_LE(written_elements, max_elements);
265 size_ = old_size + written_elements;
ossub01c7812016-02-24 01:05:56 -0800266 RTC_DCHECK(IsConsistent());
kwiberga4ac4782016-04-29 08:00:22 -0700267 return written_elements;
ossub01c7812016-02-24 01:05:56 -0800268 }
269
Karl Wiberg94784372015-04-20 14:03:07 +0200270 // Sets the size of the buffer. If the new size is smaller than the old, the
271 // buffer contents will be kept but truncated; if the new size is greater,
272 // the existing contents will be kept and the new space will be
273 // uninitialized.
kwiberg@webrtc.orgeebcab52015-03-24 09:19:06 +0000274 void SetSize(size_t size) {
kwibergc8535972016-06-20 04:47:39 -0700275 EnsureCapacityWithHeadroom(size, true);
kwiberg@webrtc.orgeebcab52015-03-24 09:19:06 +0000276 size_ = size;
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000277 }
Karl Wiberg94784372015-04-20 14:03:07 +0200278
279 // Ensure that the buffer size can be increased to at least capacity without
280 // further reallocation. (Of course, this operation might need to reallocate
281 // the buffer.)
282 void EnsureCapacity(size_t capacity) {
kwibergc8535972016-06-20 04:47:39 -0700283 // Don't allocate extra headroom, since the user is asking for a specific
284 // capacity.
285 EnsureCapacityWithHeadroom(capacity, false);
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000286 }
287
ossu728012e2016-02-19 02:38:32 -0800288 // Resets the buffer to zero size without altering capacity. Works even if the
289 // buffer has been moved from.
Karl Wiberg94784372015-04-20 14:03:07 +0200290 void Clear() {
Karl Wiberg94784372015-04-20 14:03:07 +0200291 size_ = 0;
kwiberge3d99222016-03-01 01:57:38 -0800292 RTC_DCHECK(IsConsistent());
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000293 }
294
Karl Wiberg94784372015-04-20 14:03:07 +0200295 // Swaps two buffers. Also works for buffers that have been moved from.
kwiberga4ac4782016-04-29 08:00:22 -0700296 friend void swap(BufferT& a, BufferT& b) {
Karl Wiberg94784372015-04-20 14:03:07 +0200297 using std::swap;
298 swap(a.size_, b.size_);
299 swap(a.capacity_, b.capacity_);
300 swap(a.data_, b.data_);
301 }
302
303 private:
kwibergc8535972016-06-20 04:47:39 -0700304 void EnsureCapacityWithHeadroom(size_t capacity, bool extra_headroom) {
305 RTC_DCHECK(IsConsistent());
306 if (capacity <= capacity_)
307 return;
308
309 // If the caller asks for extra headroom, ensure that the new capacity is
310 // >= 1.5 times the old capacity. Any constant > 1 is sufficient to prevent
311 // quadratic behavior; as to why we pick 1.5 in particular, see
312 // https://github.com/facebook/folly/blob/master/folly/docs/FBVector.md and
313 // http://www.gahcep.com/cpp-internals-stl-vector-part-1/.
314 const size_t new_capacity =
315 extra_headroom ? std::max(capacity, capacity_ + capacity_ / 2)
316 : capacity;
317
318 std::unique_ptr<T[]> new_data(new T[new_capacity]);
319 std::memcpy(new_data.get(), data_.get(), size_ * sizeof(T));
320 data_ = std::move(new_data);
321 capacity_ = new_capacity;
322 RTC_DCHECK(IsConsistent());
323 }
324
Karl Wiberg94784372015-04-20 14:03:07 +0200325 // Precondition for all methods except Clear and the destructor.
326 // Postcondition for all methods except move construction and move
327 // assignment, which leave the moved-from object in a possibly inconsistent
328 // state.
329 bool IsConsistent() const {
330 return (data_ || capacity_ == 0) && capacity_ >= size_;
331 }
332
333 // Called when *this has been moved from. Conceptually it's a no-op, but we
334 // can mutate the state slightly to help subsequent sanity checks catch bugs.
335 void OnMovedFrom() {
336#ifdef NDEBUG
337 // Make *this consistent and empty. Shouldn't be necessary, but better safe
338 // than sorry.
339 size_ = 0;
340 capacity_ = 0;
341#else
342 // Ensure that *this is always inconsistent, to provoke bugs.
343 size_ = 1;
344 capacity_ = 0;
345#endif
346 }
347
kwiberg@webrtc.orgeebcab52015-03-24 09:19:06 +0000348 size_t size_;
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000349 size_t capacity_;
kwiberga4ac4782016-04-29 08:00:22 -0700350 std::unique_ptr<T[]> data_;
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000351};
352
kwiberga4ac4782016-04-29 08:00:22 -0700353// By far the most common sort of buffer.
354using Buffer = BufferT<uint8_t>;
355
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000356} // namespace rtc
357
358#endif // WEBRTC_BASE_BUFFER_H_