blob: 4948aaeff34ad58aef8518f00ef0f10675dd168a [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"
Henrik Kjellanderec78f1c2017-06-29 07:52:50 +020023
24namespace rtc {
25
26namespace internal {
27
28// (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));
41};
42
43} // namespace internal
44
45// Basic buffer class, can be grown and shrunk dynamically.
46// 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
59 public:
60 using value_type = T;
61
62 // An empty BufferT.
63 BufferT() : size_(0), capacity_(0), data_(nullptr) {
64 RTC_DCHECK(IsConsistent());
65 }
66
67 // Disable copy construction and copy assignment, since copying a buffer is
68 // expensive enough that we want to force the user to be explicit about it.
69 BufferT(const BufferT&) = delete;
70 BufferT& operator=(const BufferT&) = delete;
71
72 BufferT(BufferT&& buf)
73 : size_(buf.size()),
74 capacity_(buf.capacity()),
75 data_(std::move(buf.data_)) {
76 RTC_DCHECK(IsConsistent());
77 buf.OnMovedFrom();
78 }
79
80 // Construct a buffer with the specified number of uninitialized elements.
81 explicit BufferT(size_t size) : BufferT(size, size) {}
82
83 BufferT(size_t size, size_t capacity)
84 : size_(size),
85 capacity_(std::max(size, capacity)),
86 data_(new T[capacity_]) {
87 RTC_DCHECK(IsConsistent());
88 }
89
90 // Construct a buffer and copy the specified number of elements into it.
91 template <typename U,
92 typename std::enable_if<
93 internal::BufferCompat<T, U>::value>::type* = nullptr>
94 BufferT(const U* data, size_t size) : BufferT(data, size, size) {}
95
96 template <typename U,
97 typename std::enable_if<
98 internal::BufferCompat<T, U>::value>::type* = nullptr>
99 BufferT(U* data, size_t size, size_t capacity) : BufferT(size, capacity) {
100 static_assert(sizeof(T) == sizeof(U), "");
101 std::memcpy(data_.get(), data, size * sizeof(U));
102 }
103
104 // Construct a buffer from the contents of an array.
105 template <typename U,
106 size_t N,
107 typename std::enable_if<
108 internal::BufferCompat<T, U>::value>::type* = nullptr>
109 BufferT(U (&array)[N]) : BufferT(array, N) {}
110
111 // Get a pointer to the data. Just .data() will give you a (const) T*, but if
112 // T is a byte-sized integer, you may also use .data<U>() for any other
113 // byte-sized integer U.
114 template <typename U = T,
115 typename std::enable_if<
116 internal::BufferCompat<T, U>::value>::type* = nullptr>
117 const U* data() const {
118 RTC_DCHECK(IsConsistent());
119 return reinterpret_cast<U*>(data_.get());
120 }
121
122 template <typename U = T,
123 typename std::enable_if<
124 internal::BufferCompat<T, U>::value>::type* = nullptr>
125 U* data() {
126 RTC_DCHECK(IsConsistent());
127 return reinterpret_cast<U*>(data_.get());
128 }
129
130 bool empty() const {
131 RTC_DCHECK(IsConsistent());
132 return size_ == 0;
133 }
134
135 size_t size() const {
136 RTC_DCHECK(IsConsistent());
137 return size_;
138 }
139
140 size_t capacity() const {
141 RTC_DCHECK(IsConsistent());
142 return capacity_;
143 }
144
145 BufferT& operator=(BufferT&& buf) {
146 RTC_DCHECK(IsConsistent());
147 RTC_DCHECK(buf.IsConsistent());
148 size_ = buf.size_;
149 capacity_ = buf.capacity_;
150 data_ = std::move(buf.data_);
151 buf.OnMovedFrom();
152 return *this;
153 }
154
155 bool operator==(const BufferT& buf) const {
156 RTC_DCHECK(IsConsistent());
157 if (size_ != buf.size_) {
158 return false;
159 }
160 if (std::is_integral<T>::value) {
161 // Optimization.
162 return std::memcmp(data_.get(), buf.data_.get(), size_ * sizeof(T)) == 0;
163 }
164 for (size_t i = 0; i < size_; ++i) {
165 if (data_[i] != buf.data_[i]) {
166 return false;
167 }
168 }
169 return true;
170 }
171
172 bool operator!=(const BufferT& buf) const { return !(*this == buf); }
173
174 T& operator[](size_t index) {
175 RTC_DCHECK_LT(index, size_);
176 return data()[index];
177 }
178
179 T operator[](size_t index) const {
180 RTC_DCHECK_LT(index, size_);
181 return data()[index];
182 }
183
184 T* begin() { return data(); }
185 T* end() { return data() + size(); }
186 const T* begin() const { return data(); }
187 const T* end() const { return data() + size(); }
188 const T* cbegin() const { return data(); }
189 const T* cend() const { return data() + size(); }
190
191 // The SetData functions replace the contents of the buffer. They accept the
192 // same input types as the constructors.
193 template <typename U,
194 typename std::enable_if<
195 internal::BufferCompat<T, U>::value>::type* = nullptr>
196 void SetData(const U* data, size_t size) {
197 RTC_DCHECK(IsConsistent());
198 size_ = 0;
199 AppendData(data, size);
200 }
201
202 template <typename U,
203 size_t N,
204 typename std::enable_if<
205 internal::BufferCompat<T, U>::value>::type* = nullptr>
206 void SetData(const U (&array)[N]) {
207 SetData(array, N);
208 }
209
210 template <typename W,
211 typename std::enable_if<
212 HasDataAndSize<const W, const T>::value>::type* = nullptr>
213 void SetData(const W& w) {
214 SetData(w.data(), w.size());
215 }
216
217 // Replace the data in the buffer with at most |max_elements| of data, using
218 // the function |setter|, which should have the following signature:
219 // size_t setter(ArrayView<U> view)
220 // |setter| is given an appropriately typed ArrayView of the area in which to
221 // write the data (i.e. starting at the beginning of the buffer) and should
222 // return the number of elements actually written. This number must be <=
223 // |max_elements|.
224 template <typename U = T,
225 typename F,
226 typename std::enable_if<
227 internal::BufferCompat<T, U>::value>::type* = nullptr>
228 size_t SetData(size_t max_elements, F&& setter) {
229 RTC_DCHECK(IsConsistent());
230 size_ = 0;
231 return AppendData<U>(max_elements, std::forward<F>(setter));
232 }
233
234 // The AppendData functions add data to the end of the buffer. They accept
235 // the same input types as the constructors.
236 template <typename U,
237 typename std::enable_if<
238 internal::BufferCompat<T, U>::value>::type* = nullptr>
239 void AppendData(const U* data, size_t size) {
240 RTC_DCHECK(IsConsistent());
241 const size_t new_size = size_ + size;
242 EnsureCapacityWithHeadroom(new_size, true);
243 static_assert(sizeof(T) == sizeof(U), "");
244 std::memcpy(data_.get() + size_, data, size * sizeof(U));
245 size_ = new_size;
246 RTC_DCHECK(IsConsistent());
247 }
248
249 template <typename U,
250 size_t N,
251 typename std::enable_if<
252 internal::BufferCompat<T, U>::value>::type* = nullptr>
253 void AppendData(const U (&array)[N]) {
254 AppendData(array, N);
255 }
256
257 template <typename W,
258 typename std::enable_if<
259 HasDataAndSize<const W, const T>::value>::type* = nullptr>
260 void AppendData(const W& w) {
261 AppendData(w.data(), w.size());
262 }
263
264 template <typename U,
265 typename std::enable_if<
266 internal::BufferCompat<T, U>::value>::type* = nullptr>
267 void AppendData(const U& item) {
268 AppendData(&item, 1);
269 }
270
271 // Append at most |max_elements| to the end of the buffer, using the function
272 // |setter|, which should have the following signature:
273 // size_t setter(ArrayView<U> view)
274 // |setter| is given an appropriately typed ArrayView of the area in which to
275 // write the data (i.e. starting at the former end of the buffer) and should
276 // return the number of elements actually written. This number must be <=
277 // |max_elements|.
278 template <typename U = T,
279 typename F,
280 typename std::enable_if<
281 internal::BufferCompat<T, U>::value>::type* = nullptr>
282 size_t AppendData(size_t max_elements, F&& setter) {
283 RTC_DCHECK(IsConsistent());
284 const size_t old_size = size_;
285 SetSize(old_size + max_elements);
286 U* base_ptr = data<U>() + old_size;
287 size_t written_elements = setter(rtc::ArrayView<U>(base_ptr, max_elements));
288
289 RTC_CHECK_LE(written_elements, max_elements);
290 size_ = old_size + written_elements;
291 RTC_DCHECK(IsConsistent());
292 return written_elements;
293 }
294
295 // Sets the size of the buffer. If the new size is smaller than the old, the
296 // buffer contents will be kept but truncated; if the new size is greater,
297 // the existing contents will be kept and the new space will be
298 // uninitialized.
299 void SetSize(size_t size) {
300 EnsureCapacityWithHeadroom(size, true);
301 size_ = size;
302 }
303
304 // Ensure that the buffer size can be increased to at least capacity without
305 // further reallocation. (Of course, this operation might need to reallocate
306 // the buffer.)
307 void EnsureCapacity(size_t capacity) {
308 // Don't allocate extra headroom, since the user is asking for a specific
309 // capacity.
310 EnsureCapacityWithHeadroom(capacity, false);
311 }
312
313 // Resets the buffer to zero size without altering capacity. Works even if the
314 // buffer has been moved from.
315 void Clear() {
316 size_ = 0;
317 RTC_DCHECK(IsConsistent());
318 }
319
320 // Swaps two buffers. Also works for buffers that have been moved from.
321 friend void swap(BufferT& a, BufferT& b) {
322 using std::swap;
323 swap(a.size_, b.size_);
324 swap(a.capacity_, b.capacity_);
325 swap(a.data_, b.data_);
326 }
327
328 private:
329 void EnsureCapacityWithHeadroom(size_t capacity, bool extra_headroom) {
330 RTC_DCHECK(IsConsistent());
331 if (capacity <= capacity_)
332 return;
333
334 // If the caller asks for extra headroom, ensure that the new capacity is
335 // >= 1.5 times the old capacity. Any constant > 1 is sufficient to prevent
336 // quadratic behavior; as to why we pick 1.5 in particular, see
337 // https://github.com/facebook/folly/blob/master/folly/docs/FBVector.md and
338 // http://www.gahcep.com/cpp-internals-stl-vector-part-1/.
339 const size_t new_capacity =
340 extra_headroom ? std::max(capacity, capacity_ + capacity_ / 2)
341 : capacity;
342
343 std::unique_ptr<T[]> new_data(new T[new_capacity]);
344 std::memcpy(new_data.get(), data_.get(), size_ * sizeof(T));
345 data_ = std::move(new_data);
346 capacity_ = new_capacity;
347 RTC_DCHECK(IsConsistent());
348 }
349
350 // Precondition for all methods except Clear and the destructor.
351 // Postcondition for all methods except move construction and move
352 // assignment, which leave the moved-from object in a possibly inconsistent
353 // state.
354 bool IsConsistent() const {
355 return (data_ || capacity_ == 0) && capacity_ >= size_;
356 }
357
358 // Called when *this has been moved from. Conceptually it's a no-op, but we
359 // can mutate the state slightly to help subsequent sanity checks catch bugs.
360 void OnMovedFrom() {
361#if RTC_DCHECK_IS_ON
362 // Make *this consistent and empty. Shouldn't be necessary, but better safe
363 // than sorry.
364 size_ = 0;
365 capacity_ = 0;
366#else
367 // Ensure that *this is always inconsistent, to provoke bugs.
368 size_ = 1;
369 capacity_ = 0;
370#endif
371 }
372
373 size_t size_;
374 size_t capacity_;
375 std::unique_ptr<T[]> data_;
376};
377
378// By far the most common sort of buffer.
379using Buffer = BufferT<uint8_t>;
380
381} // namespace rtc
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000382
Mirko Bonadei92ea95e2017-09-15 06:47:31 +0200383#endif // RTC_BASE_BUFFER_H_