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