You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

434 lines
14 KiB

​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
  1. /*
  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. #ifndef RTC_BASE_BUFFER_H_
  11. #define RTC_BASE_BUFFER_H_
  12. #include <stdint.h>
  13. #include <algorithm>
  14. #include <cstring>
  15. #include <memory>
  16. #include <type_traits>
  17. #include <utility>
  18. #include "api/array_view.h"
  19. #include "rtc_base/checks.h"
  20. #include "rtc_base/type_traits.h"
  21. #include "rtc_base/zero_memory.h"
  22. namespace rtc {
  23. namespace internal {
  24. // (Internal; please don't use outside this file.) Determines if elements of
  25. // type U are compatible with a BufferT<T>. For most types, we just ignore
  26. // top-level const and forbid top-level volatile and require T and U to be
  27. // otherwise equal, but all byte-sized integers (notably char, int8_t, and
  28. // uint8_t) are compatible with each other. (Note: We aim to get rid of this
  29. // behavior, and treat all types the same.)
  30. template <typename T, typename U>
  31. struct BufferCompat {
  32. static constexpr bool value =
  33. !std::is_volatile<U>::value &&
  34. ((std::is_integral<T>::value && sizeof(T) == 1)
  35. ? (std::is_integral<U>::value && sizeof(U) == 1)
  36. : (std::is_same<T, typename std::remove_const<U>::type>::value));
  37. };
  38. } // namespace internal
  39. // Basic buffer class, can be grown and shrunk dynamically.
  40. // Unlike std::string/vector, does not initialize data when increasing size.
  41. // If "ZeroOnFree" is true, any memory is explicitly cleared before releasing.
  42. // The type alias "ZeroOnFreeBuffer" below should be used instead of setting
  43. // "ZeroOnFree" in the template manually to "true".
  44. template <typename T, bool ZeroOnFree = false>
  45. class BufferT {
  46. // We want T's destructor and default constructor to be trivial, i.e. perform
  47. // no action, so that we don't have to touch the memory we allocate and
  48. // deallocate. And we want T to be trivially copyable, so that we can copy T
  49. // instances with std::memcpy. This is precisely the definition of a trivial
  50. // type.
  51. static_assert(std::is_trivial<T>::value, "T must be a trivial type.");
  52. // This class relies heavily on being able to mutate its data.
  53. static_assert(!std::is_const<T>::value, "T may not be const");
  54. public:
  55. using value_type = T;
  56. // An empty BufferT.
  57. BufferT() : size_(0), capacity_(0), data_(nullptr) {
  58. RTC_DCHECK(IsConsistent());
  59. }
  60. // Disable copy construction and copy assignment, since copying a buffer is
  61. // expensive enough that we want to force the user to be explicit about it.
  62. BufferT(const BufferT&) = delete;
  63. BufferT& operator=(const BufferT&) = delete;
  64. BufferT(BufferT&& buf)
  65. : size_(buf.size()),
  66. capacity_(buf.capacity()),
  67. data_(std::move(buf.data_)) {
  68. RTC_DCHECK(IsConsistent());
  69. buf.OnMovedFrom();
  70. }
  71. // Construct a buffer with the specified number of uninitialized elements.
  72. explicit BufferT(size_t size) : BufferT(size, size) {}
  73. BufferT(size_t size, size_t capacity)
  74. : size_(size),
  75. capacity_(std::max(size, capacity)),
  76. data_(capacity_ > 0 ? new T[capacity_] : nullptr) {
  77. RTC_DCHECK(IsConsistent());
  78. }
  79. // Construct a buffer and copy the specified number of elements into it.
  80. template <typename U,
  81. typename std::enable_if<
  82. internal::BufferCompat<T, U>::value>::type* = nullptr>
  83. BufferT(const U* data, size_t size) : BufferT(data, size, size) {}
  84. template <typename U,
  85. typename std::enable_if<
  86. internal::BufferCompat<T, U>::value>::type* = nullptr>
  87. BufferT(U* data, size_t size, size_t capacity) : BufferT(size, capacity) {
  88. static_assert(sizeof(T) == sizeof(U), "");
  89. std::memcpy(data_.get(), data, size * sizeof(U));
  90. }
  91. // Construct a buffer from the contents of an array.
  92. template <typename U,
  93. size_t N,
  94. typename std::enable_if<
  95. internal::BufferCompat<T, U>::value>::type* = nullptr>
  96. BufferT(U (&array)[N]) : BufferT(array, N) {}
  97. ~BufferT() { MaybeZeroCompleteBuffer(); }
  98. // Get a pointer to the data. Just .data() will give you a (const) T*, but if
  99. // T is a byte-sized integer, you may also use .data<U>() for any other
  100. // byte-sized integer U.
  101. template <typename U = T,
  102. typename std::enable_if<
  103. internal::BufferCompat<T, U>::value>::type* = nullptr>
  104. const U* data() const {
  105. RTC_DCHECK(IsConsistent());
  106. return reinterpret_cast<U*>(data_.get());
  107. }
  108. template <typename U = T,
  109. typename std::enable_if<
  110. internal::BufferCompat<T, U>::value>::type* = nullptr>
  111. U* data() {
  112. RTC_DCHECK(IsConsistent());
  113. return reinterpret_cast<U*>(data_.get());
  114. }
  115. bool empty() const {
  116. RTC_DCHECK(IsConsistent());
  117. return size_ == 0;
  118. }
  119. size_t size() const {
  120. RTC_DCHECK(IsConsistent());
  121. return size_;
  122. }
  123. size_t capacity() const {
  124. RTC_DCHECK(IsConsistent());
  125. return capacity_;
  126. }
  127. BufferT& operator=(BufferT&& buf) {
  128. RTC_DCHECK(buf.IsConsistent());
  129. MaybeZeroCompleteBuffer();
  130. size_ = buf.size_;
  131. capacity_ = buf.capacity_;
  132. using std::swap;
  133. swap(data_, buf.data_);
  134. buf.data_.reset();
  135. buf.OnMovedFrom();
  136. return *this;
  137. }
  138. bool operator==(const BufferT& buf) const {
  139. RTC_DCHECK(IsConsistent());
  140. if (size_ != buf.size_) {
  141. return false;
  142. }
  143. if (std::is_integral<T>::value) {
  144. // Optimization.
  145. return std::memcmp(data_.get(), buf.data_.get(), size_ * sizeof(T)) == 0;
  146. }
  147. for (size_t i = 0; i < size_; ++i) {
  148. if (data_[i] != buf.data_[i]) {
  149. return false;
  150. }
  151. }
  152. return true;
  153. }
  154. bool operator!=(const BufferT& buf) const { return !(*this == buf); }
  155. T& operator[](size_t index) {
  156. RTC_DCHECK_LT(index, size_);
  157. return data()[index];
  158. }
  159. T operator[](size_t index) const {
  160. RTC_DCHECK_LT(index, size_);
  161. return data()[index];
  162. }
  163. T* begin() { return data(); }
  164. T* end() { return data() + size(); }
  165. const T* begin() const { return data(); }
  166. const T* end() const { return data() + size(); }
  167. const T* cbegin() const { return data(); }
  168. const T* cend() const { return data() + size(); }
  169. // The SetData functions replace the contents of the buffer. They accept the
  170. // same input types as the constructors.
  171. template <typename U,
  172. typename std::enable_if<
  173. internal::BufferCompat<T, U>::value>::type* = nullptr>
  174. void SetData(const U* data, size_t size) {
  175. RTC_DCHECK(IsConsistent());
  176. const size_t old_size = size_;
  177. size_ = 0;
  178. AppendData(data, size);
  179. if (ZeroOnFree && size_ < old_size) {
  180. ZeroTrailingData(old_size - size_);
  181. }
  182. }
  183. template <typename U,
  184. size_t N,
  185. typename std::enable_if<
  186. internal::BufferCompat<T, U>::value>::type* = nullptr>
  187. void SetData(const U (&array)[N]) {
  188. SetData(array, N);
  189. }
  190. template <typename W,
  191. typename std::enable_if<
  192. HasDataAndSize<const W, const T>::value>::type* = nullptr>
  193. void SetData(const W& w) {
  194. SetData(w.data(), w.size());
  195. }
  196. // Replaces the data in the buffer with at most |max_elements| of data, using
  197. // the function |setter|, which should have the following signature:
  198. //
  199. // size_t setter(ArrayView<U> view)
  200. //
  201. // |setter| is given an appropriately typed ArrayView of length exactly
  202. // |max_elements| that describes the area where it should write the data; it
  203. // should return the number of elements actually written. (If it doesn't fill
  204. // the whole ArrayView, it should leave the unused space at the end.)
  205. template <typename U = T,
  206. typename F,
  207. typename std::enable_if<
  208. internal::BufferCompat<T, U>::value>::type* = nullptr>
  209. size_t SetData(size_t max_elements, F&& setter) {
  210. RTC_DCHECK(IsConsistent());
  211. const size_t old_size = size_;
  212. size_ = 0;
  213. const size_t written = AppendData<U>(max_elements, std::forward<F>(setter));
  214. if (ZeroOnFree && size_ < old_size) {
  215. ZeroTrailingData(old_size - size_);
  216. }
  217. return written;
  218. }
  219. // The AppendData functions add data to the end of the buffer. They accept
  220. // the same input types as the constructors.
  221. 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) {
  225. RTC_DCHECK(IsConsistent());
  226. const size_t new_size = size_ + size;
  227. EnsureCapacityWithHeadroom(new_size, true);
  228. static_assert(sizeof(T) == sizeof(U), "");
  229. std::memcpy(data_.get() + size_, data, size * sizeof(U));
  230. size_ = new_size;
  231. RTC_DCHECK(IsConsistent());
  232. }
  233. template <typename U,
  234. size_t N,
  235. typename std::enable_if<
  236. internal::BufferCompat<T, U>::value>::type* = nullptr>
  237. void AppendData(const U (&array)[N]) {
  238. AppendData(array, N);
  239. }
  240. template <typename W,
  241. typename std::enable_if<
  242. HasDataAndSize<const W, const T>::value>::type* = nullptr>
  243. void AppendData(const W& w) {
  244. AppendData(w.data(), w.size());
  245. }
  246. template <typename U,
  247. typename std::enable_if<
  248. internal::BufferCompat<T, U>::value>::type* = nullptr>
  249. void AppendData(const U& item) {
  250. AppendData(&item, 1);
  251. }
  252. // Appends at most |max_elements| to the end of the buffer, using the function
  253. // |setter|, which should have the following signature:
  254. //
  255. // size_t setter(ArrayView<U> view)
  256. //
  257. // |setter| is given an appropriately typed ArrayView of length exactly
  258. // |max_elements| that describes the area where it should write the data; it
  259. // should return the number of elements actually written. (If it doesn't fill
  260. // the whole ArrayView, it should leave the unused space at the end.)
  261. template <typename U = T,
  262. typename F,
  263. typename std::enable_if<
  264. internal::BufferCompat<T, U>::value>::type* = nullptr>
  265. size_t AppendData(size_t max_elements, F&& setter) {
  266. RTC_DCHECK(IsConsistent());
  267. const size_t old_size = size_;
  268. SetSize(old_size + max_elements);
  269. U* base_ptr = data<U>() + old_size;
  270. size_t written_elements = setter(rtc::ArrayView<U>(base_ptr, max_elements));
  271. RTC_CHECK_LE(written_elements, max_elements);
  272. size_ = old_size + written_elements;
  273. RTC_DCHECK(IsConsistent());
  274. return written_elements;
  275. }
  276. // Sets the size of the buffer. If the new size is smaller than the old, the
  277. // buffer contents will be kept but truncated; if the new size is greater,
  278. // the existing contents will be kept and the new space will be
  279. // uninitialized.
  280. void SetSize(size_t size) {
  281. const size_t old_size = size_;
  282. EnsureCapacityWithHeadroom(size, true);
  283. size_ = size;
  284. if (ZeroOnFree && size_ < old_size) {
  285. ZeroTrailingData(old_size - size_);
  286. }
  287. }
  288. // Ensure that the buffer size can be increased to at least capacity without
  289. // further reallocation. (Of course, this operation might need to reallocate
  290. // the buffer.)
  291. void EnsureCapacity(size_t capacity) {
  292. // Don't allocate extra headroom, since the user is asking for a specific
  293. // capacity.
  294. EnsureCapacityWithHeadroom(capacity, false);
  295. }
  296. // Resets the buffer to zero size without altering capacity. Works even if the
  297. // buffer has been moved from.
  298. void Clear() {
  299. MaybeZeroCompleteBuffer();
  300. size_ = 0;
  301. RTC_DCHECK(IsConsistent());
  302. }
  303. // Swaps two buffers. Also works for buffers that have been moved from.
  304. friend void swap(BufferT& a, BufferT& b) {
  305. using std::swap;
  306. swap(a.size_, b.size_);
  307. swap(a.capacity_, b.capacity_);
  308. swap(a.data_, b.data_);
  309. }
  310. private:
  311. void EnsureCapacityWithHeadroom(size_t capacity, bool extra_headroom) {
  312. RTC_DCHECK(IsConsistent());
  313. if (capacity <= capacity_)
  314. return;
  315. // If the caller asks for extra headroom, ensure that the new capacity is
  316. // >= 1.5 times the old capacity. Any constant > 1 is sufficient to prevent
  317. // quadratic behavior; as to why we pick 1.5 in particular, see
  318. // https://github.com/facebook/folly/blob/master/folly/docs/FBVector.md and
  319. // http://www.gahcep.com/cpp-internals-stl-vector-part-1/.
  320. const size_t new_capacity =
  321. extra_headroom ? std::max(capacity, capacity_ + capacity_ / 2)
  322. : capacity;
  323. std::unique_ptr<T[]> new_data(new T[new_capacity]);
  324. std::memcpy(new_data.get(), data_.get(), size_ * sizeof(T));
  325. MaybeZeroCompleteBuffer();
  326. data_ = std::move(new_data);
  327. capacity_ = new_capacity;
  328. RTC_DCHECK(IsConsistent());
  329. }
  330. // Zero the complete buffer if template argument "ZeroOnFree" is true.
  331. void MaybeZeroCompleteBuffer() {
  332. if (ZeroOnFree && capacity_ > 0) {
  333. // It would be sufficient to only zero "size_" elements, as all other
  334. // methods already ensure that the unused capacity contains no sensitive
  335. // data---but better safe than sorry.
  336. ExplicitZeroMemory(data_.get(), capacity_ * sizeof(T));
  337. }
  338. }
  339. // Zero the first "count" elements of unused capacity.
  340. void ZeroTrailingData(size_t count) {
  341. RTC_DCHECK(IsConsistent());
  342. RTC_DCHECK_LE(count, capacity_ - size_);
  343. ExplicitZeroMemory(data_.get() + size_, count * sizeof(T));
  344. }
  345. // Precondition for all methods except Clear, operator= and the destructor.
  346. // Postcondition for all methods except move construction and move
  347. // assignment, which leave the moved-from object in a possibly inconsistent
  348. // state.
  349. bool IsConsistent() const {
  350. return (data_ || capacity_ == 0) && capacity_ >= size_;
  351. }
  352. // Called when *this has been moved from. Conceptually it's a no-op, but we
  353. // can mutate the state slightly to help subsequent sanity checks catch bugs.
  354. void OnMovedFrom() {
  355. RTC_DCHECK(!data_); // Our heap block should have been stolen.
  356. #if RTC_DCHECK_IS_ON
  357. // Ensure that *this is always inconsistent, to provoke bugs.
  358. size_ = 1;
  359. capacity_ = 0;
  360. #else
  361. // Make *this consistent and empty. Shouldn't be necessary, but better safe
  362. // than sorry.
  363. size_ = 0;
  364. capacity_ = 0;
  365. #endif
  366. }
  367. size_t size_;
  368. size_t capacity_;
  369. std::unique_ptr<T[]> data_;
  370. };
  371. // By far the most common sort of buffer.
  372. using Buffer = BufferT<uint8_t>;
  373. // A buffer that zeros memory before releasing it.
  374. template <typename T>
  375. using ZeroOnFreeBuffer = BufferT<T, true>;
  376. } // namespace rtc
  377. #endif // RTC_BASE_BUFFER_H_