array_view.h 12 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328
  1. /*
  2. * Copyright 2015 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 API_ARRAY_VIEW_H_
  11. #define API_ARRAY_VIEW_H_
  12. #include <algorithm>
  13. #include <array>
  14. #include <iterator>
  15. #include <type_traits>
  16. #include "rtc_base/checks.h"
  17. #include "rtc_base/type_traits.h"
  18. namespace rtc {
  19. // tl;dr: rtc::ArrayView is the same thing as gsl::span from the Guideline
  20. // Support Library.
  21. //
  22. // Many functions read from or write to arrays. The obvious way to do this is
  23. // to use two arguments, a pointer to the first element and an element count:
  24. //
  25. // bool Contains17(const int* arr, size_t size) {
  26. // for (size_t i = 0; i < size; ++i) {
  27. // if (arr[i] == 17)
  28. // return true;
  29. // }
  30. // return false;
  31. // }
  32. //
  33. // This is flexible, since it doesn't matter how the array is stored (C array,
  34. // std::vector, rtc::Buffer, ...), but it's error-prone because the caller has
  35. // to correctly specify the array length:
  36. //
  37. // Contains17(arr, arraysize(arr)); // C array
  38. // Contains17(arr.data(), arr.size()); // std::vector
  39. // Contains17(arr, size); // pointer + size
  40. // ...
  41. //
  42. // It's also kind of messy to have two separate arguments for what is
  43. // conceptually a single thing.
  44. //
  45. // Enter rtc::ArrayView<T>. It contains a T pointer (to an array it doesn't
  46. // own) and a count, and supports the basic things you'd expect, such as
  47. // indexing and iteration. It allows us to write our function like this:
  48. //
  49. // bool Contains17(rtc::ArrayView<const int> arr) {
  50. // for (auto e : arr) {
  51. // if (e == 17)
  52. // return true;
  53. // }
  54. // return false;
  55. // }
  56. //
  57. // And even better, because a bunch of things will implicitly convert to
  58. // ArrayView, we can call it like this:
  59. //
  60. // Contains17(arr); // C array
  61. // Contains17(arr); // std::vector
  62. // Contains17(rtc::ArrayView<int>(arr, size)); // pointer + size
  63. // Contains17(nullptr); // nullptr -> empty ArrayView
  64. // ...
  65. //
  66. // ArrayView<T> stores both a pointer and a size, but you may also use
  67. // ArrayView<T, N>, which has a size that's fixed at compile time (which means
  68. // it only has to store the pointer).
  69. //
  70. // One important point is that ArrayView<T> and ArrayView<const T> are
  71. // different types, which allow and don't allow mutation of the array elements,
  72. // respectively. The implicit conversions work just like you'd hope, so that
  73. // e.g. vector<int> will convert to either ArrayView<int> or ArrayView<const
  74. // int>, but const vector<int> will convert only to ArrayView<const int>.
  75. // (ArrayView itself can be the source type in such conversions, so
  76. // ArrayView<int> will convert to ArrayView<const int>.)
  77. //
  78. // Note: ArrayView is tiny (just a pointer and a count if variable-sized, just
  79. // a pointer if fix-sized) and trivially copyable, so it's probably cheaper to
  80. // pass it by value than by const reference.
  81. namespace impl {
  82. // Magic constant for indicating that the size of an ArrayView is variable
  83. // instead of fixed.
  84. enum : std::ptrdiff_t { kArrayViewVarSize = -4711 };
  85. // Base class for ArrayViews of fixed nonzero size.
  86. template <typename T, std::ptrdiff_t Size>
  87. class ArrayViewBase {
  88. static_assert(Size > 0, "ArrayView size must be variable or non-negative");
  89. public:
  90. ArrayViewBase(T* data, size_t size) : data_(data) {}
  91. static constexpr size_t size() { return Size; }
  92. static constexpr bool empty() { return false; }
  93. T* data() const { return data_; }
  94. protected:
  95. static constexpr bool fixed_size() { return true; }
  96. private:
  97. T* data_;
  98. };
  99. // Specialized base class for ArrayViews of fixed zero size.
  100. template <typename T>
  101. class ArrayViewBase<T, 0> {
  102. public:
  103. explicit ArrayViewBase(T* data, size_t size) {}
  104. static constexpr size_t size() { return 0; }
  105. static constexpr bool empty() { return true; }
  106. T* data() const { return nullptr; }
  107. protected:
  108. static constexpr bool fixed_size() { return true; }
  109. };
  110. // Specialized base class for ArrayViews of variable size.
  111. template <typename T>
  112. class ArrayViewBase<T, impl::kArrayViewVarSize> {
  113. public:
  114. ArrayViewBase(T* data, size_t size)
  115. : data_(size == 0 ? nullptr : data), size_(size) {}
  116. size_t size() const { return size_; }
  117. bool empty() const { return size_ == 0; }
  118. T* data() const { return data_; }
  119. protected:
  120. static constexpr bool fixed_size() { return false; }
  121. private:
  122. T* data_;
  123. size_t size_;
  124. };
  125. } // namespace impl
  126. template <typename T, std::ptrdiff_t Size = impl::kArrayViewVarSize>
  127. class ArrayView final : public impl::ArrayViewBase<T, Size> {
  128. public:
  129. using value_type = T;
  130. using const_iterator = const T*;
  131. // Construct an ArrayView from a pointer and a length.
  132. template <typename U>
  133. ArrayView(U* data, size_t size)
  134. : impl::ArrayViewBase<T, Size>::ArrayViewBase(data, size) {
  135. RTC_DCHECK_EQ(size == 0 ? nullptr : data, this->data());
  136. RTC_DCHECK_EQ(size, this->size());
  137. RTC_DCHECK_EQ(!this->data(),
  138. this->size() == 0); // data is null iff size == 0.
  139. }
  140. // Construct an empty ArrayView. Note that fixed-size ArrayViews of size > 0
  141. // cannot be empty.
  142. ArrayView() : ArrayView(nullptr, 0) {}
  143. ArrayView(std::nullptr_t) // NOLINT
  144. : ArrayView() {}
  145. ArrayView(std::nullptr_t, size_t size)
  146. : ArrayView(static_cast<T*>(nullptr), size) {
  147. static_assert(Size == 0 || Size == impl::kArrayViewVarSize, "");
  148. RTC_DCHECK_EQ(0, size);
  149. }
  150. // Construct an ArrayView from a C-style array.
  151. template <typename U, size_t N>
  152. ArrayView(U (&array)[N]) // NOLINT
  153. : ArrayView(array, N) {
  154. static_assert(Size == N || Size == impl::kArrayViewVarSize,
  155. "Array size must match ArrayView size");
  156. }
  157. // (Only if size is fixed.) Construct a fixed size ArrayView<T, N> from a
  158. // non-const std::array instance. For an ArrayView with variable size, the
  159. // used ctor is ArrayView(U& u) instead.
  160. template <typename U,
  161. size_t N,
  162. typename std::enable_if<
  163. Size == static_cast<std::ptrdiff_t>(N)>::type* = nullptr>
  164. ArrayView(std::array<U, N>& u) // NOLINT
  165. : ArrayView(u.data(), u.size()) {}
  166. // (Only if size is fixed.) Construct a fixed size ArrayView<T, N> where T is
  167. // const from a const(expr) std::array instance. For an ArrayView with
  168. // variable size, the used ctor is ArrayView(U& u) instead.
  169. template <typename U,
  170. size_t N,
  171. typename std::enable_if<
  172. Size == static_cast<std::ptrdiff_t>(N)>::type* = nullptr>
  173. ArrayView(const std::array<U, N>& u) // NOLINT
  174. : ArrayView(u.data(), u.size()) {}
  175. // (Only if size is fixed.) Construct an ArrayView from any type U that has a
  176. // static constexpr size() method whose return value is equal to Size, and a
  177. // data() method whose return value converts implicitly to T*. In particular,
  178. // this means we allow conversion from ArrayView<T, N> to ArrayView<const T,
  179. // N>, but not the other way around. We also don't allow conversion from
  180. // ArrayView<T> to ArrayView<T, N>, or from ArrayView<T, M> to ArrayView<T,
  181. // N> when M != N.
  182. template <
  183. typename U,
  184. typename std::enable_if<Size != impl::kArrayViewVarSize &&
  185. HasDataAndSize<U, T>::value>::type* = nullptr>
  186. ArrayView(U& u) // NOLINT
  187. : ArrayView(u.data(), u.size()) {
  188. static_assert(U::size() == Size, "Sizes must match exactly");
  189. }
  190. template <
  191. typename U,
  192. typename std::enable_if<Size != impl::kArrayViewVarSize &&
  193. HasDataAndSize<U, T>::value>::type* = nullptr>
  194. ArrayView(const U& u) // NOLINT(runtime/explicit)
  195. : ArrayView(u.data(), u.size()) {
  196. static_assert(U::size() == Size, "Sizes must match exactly");
  197. }
  198. // (Only if size is variable.) Construct an ArrayView from any type U that
  199. // has a size() method whose return value converts implicitly to size_t, and
  200. // a data() method whose return value converts implicitly to T*. In
  201. // particular, this means we allow conversion from ArrayView<T> to
  202. // ArrayView<const T>, but not the other way around. Other allowed
  203. // conversions include
  204. // ArrayView<T, N> to ArrayView<T> or ArrayView<const T>,
  205. // std::vector<T> to ArrayView<T> or ArrayView<const T>,
  206. // const std::vector<T> to ArrayView<const T>,
  207. // rtc::Buffer to ArrayView<uint8_t> or ArrayView<const uint8_t>, and
  208. // const rtc::Buffer to ArrayView<const uint8_t>.
  209. template <
  210. typename U,
  211. typename std::enable_if<Size == impl::kArrayViewVarSize &&
  212. HasDataAndSize<U, T>::value>::type* = nullptr>
  213. ArrayView(U& u) // NOLINT
  214. : ArrayView(u.data(), u.size()) {}
  215. template <
  216. typename U,
  217. typename std::enable_if<Size == impl::kArrayViewVarSize &&
  218. HasDataAndSize<U, T>::value>::type* = nullptr>
  219. ArrayView(const U& u) // NOLINT(runtime/explicit)
  220. : ArrayView(u.data(), u.size()) {}
  221. // Indexing and iteration. These allow mutation even if the ArrayView is
  222. // const, because the ArrayView doesn't own the array. (To prevent mutation,
  223. // use a const element type.)
  224. T& operator[](size_t idx) const {
  225. RTC_DCHECK_LT(idx, this->size());
  226. RTC_DCHECK(this->data());
  227. return this->data()[idx];
  228. }
  229. T* begin() const { return this->data(); }
  230. T* end() const { return this->data() + this->size(); }
  231. const T* cbegin() const { return this->data(); }
  232. const T* cend() const { return this->data() + this->size(); }
  233. std::reverse_iterator<T*> rbegin() const {
  234. return std::make_reverse_iterator(end());
  235. }
  236. std::reverse_iterator<T*> rend() const {
  237. return std::make_reverse_iterator(begin());
  238. }
  239. std::reverse_iterator<const T*> crbegin() const {
  240. return std::make_reverse_iterator(cend());
  241. }
  242. std::reverse_iterator<const T*> crend() const {
  243. return std::make_reverse_iterator(cbegin());
  244. }
  245. ArrayView<T> subview(size_t offset, size_t size) const {
  246. return offset < this->size()
  247. ? ArrayView<T>(this->data() + offset,
  248. std::min(size, this->size() - offset))
  249. : ArrayView<T>();
  250. }
  251. ArrayView<T> subview(size_t offset) const {
  252. return subview(offset, this->size());
  253. }
  254. };
  255. // Comparing two ArrayViews compares their (pointer,size) pairs; it does *not*
  256. // dereference the pointers.
  257. template <typename T, std::ptrdiff_t Size1, std::ptrdiff_t Size2>
  258. bool operator==(const ArrayView<T, Size1>& a, const ArrayView<T, Size2>& b) {
  259. return a.data() == b.data() && a.size() == b.size();
  260. }
  261. template <typename T, std::ptrdiff_t Size1, std::ptrdiff_t Size2>
  262. bool operator!=(const ArrayView<T, Size1>& a, const ArrayView<T, Size2>& b) {
  263. return !(a == b);
  264. }
  265. // Variable-size ArrayViews are the size of two pointers; fixed-size ArrayViews
  266. // are the size of one pointer. (And as a special case, fixed-size ArrayViews
  267. // of size 0 require no storage.)
  268. static_assert(sizeof(ArrayView<int>) == 2 * sizeof(int*), "");
  269. static_assert(sizeof(ArrayView<int, 17>) == sizeof(int*), "");
  270. static_assert(std::is_empty<ArrayView<int, 0>>::value, "");
  271. template <typename T>
  272. inline ArrayView<T> MakeArrayView(T* data, size_t size) {
  273. return ArrayView<T>(data, size);
  274. }
  275. // Only for primitive types that have the same size and aligment.
  276. // Allow reinterpret cast of the array view to another primitive type of the
  277. // same size.
  278. // Template arguments order is (U, T, Size) to allow deduction of the template
  279. // arguments in client calls: reinterpret_array_view<target_type>(array_view).
  280. template <typename U, typename T, std::ptrdiff_t Size>
  281. inline ArrayView<U, Size> reinterpret_array_view(ArrayView<T, Size> view) {
  282. static_assert(sizeof(U) == sizeof(T) && alignof(U) == alignof(T),
  283. "ArrayView reinterpret_cast is only supported for casting "
  284. "between views that represent the same chunk of memory.");
  285. static_assert(
  286. std::is_fundamental<T>::value && std::is_fundamental<U>::value,
  287. "ArrayView reinterpret_cast is only supported for casting between "
  288. "fundamental types.");
  289. return ArrayView<U, Size>(reinterpret_cast<U*>(view.data()), view.size());
  290. }
  291. } // namespace rtc
  292. #endif // API_ARRAY_VIEW_H_