array_view.h 12 KB

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