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