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