xref: /aosp_15_r20/external/pytorch/c10/util/ArrayRef.h (revision da0073e96a02ea20f0ac840b70461e3646d07c45)
1 //===--- ArrayRef.h - Array Reference Wrapper -------------------*- C++ -*-===//
2 //
3 //                     The LLVM Compiler Infrastructure
4 //
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
7 //
8 //===----------------------------------------------------------------------===//
9 
10 // ATen: modified from llvm::ArrayRef.
11 // removed llvm-specific functionality
12 // removed some implicit const -> non-const conversions that rely on
13 // complicated std::enable_if meta-programming
14 // removed a bunch of slice variants for simplicity...
15 
16 #pragma once
17 
18 #include <c10/macros/Macros.h>
19 #include <c10/util/Deprecated.h>
20 #include <c10/util/Exception.h>
21 #include <c10/util/SmallVector.h>
22 
23 #include <array>
24 #include <cstddef>
25 #include <cstdint>
26 #include <initializer_list>
27 #include <iterator>
28 #include <ostream>
29 #include <type_traits>
30 #include <vector>
31 
32 namespace c10 {
33 /// ArrayRef - Represent a constant reference to an array (0 or more elements
34 /// consecutively in memory), i.e. a start pointer and a length.  It allows
35 /// various APIs to take consecutive elements easily and conveniently.
36 ///
37 /// This class does not own the underlying data, it is expected to be used in
38 /// situations where the data resides in some other buffer, whose lifetime
39 /// extends past that of the ArrayRef. For this reason, it is not in general
40 /// safe to store an ArrayRef.
41 ///
42 /// This is intended to be trivially copyable, so it should be passed by
43 /// value.
44 template <typename T>
45 class ArrayRef final {
46  public:
47   using iterator = const T*;
48   using const_iterator = const T*;
49   using size_type = size_t;
50   using value_type = T;
51 
52   using reverse_iterator = std::reverse_iterator<iterator>;
53 
54  private:
55   /// The start of the array, in an external buffer.
56   const T* Data;
57 
58   /// The number of elements.
59   size_type Length;
60 
debugCheckNullptrInvariant()61   void debugCheckNullptrInvariant() {
62     TORCH_INTERNAL_ASSERT_DEBUG_ONLY(
63         Data != nullptr || Length == 0,
64         "created ArrayRef with nullptr and non-zero length! std::optional relies on this being illegal");
65   }
66 
67  public:
68   /// @name Constructors
69   /// @{
70 
71   /// Construct an empty ArrayRef.
ArrayRef()72   /* implicit */ constexpr ArrayRef() : Data(nullptr), Length(0) {}
73 
74   /// Construct an ArrayRef from a single element.
75   // TODO Make this explicit
ArrayRef(const T & OneElt)76   constexpr ArrayRef(const T& OneElt) : Data(&OneElt), Length(1) {}
77 
78   /// Construct an ArrayRef from a pointer and length.
ArrayRef(const T * data,size_t length)79   C10_HOST_CONSTEXPR_EXCEPT_WIN_CUDA ArrayRef(const T* data, size_t length)
80       : Data(data), Length(length) {
81     debugCheckNullptrInvariant();
82   }
83 
84   /// Construct an ArrayRef from a range.
ArrayRef(const T * begin,const T * end)85   C10_HOST_CONSTEXPR_EXCEPT_WIN_CUDA ArrayRef(const T* begin, const T* end)
86       : Data(begin), Length(end - begin) {
87     debugCheckNullptrInvariant();
88   }
89 
90   /// Construct an ArrayRef from a SmallVector. This is templated in order to
91   /// avoid instantiating SmallVectorTemplateCommon<T> whenever we
92   /// copy-construct an ArrayRef.
93   template <typename U>
ArrayRef(const SmallVectorTemplateCommon<T,U> & Vec)94   /* implicit */ ArrayRef(const SmallVectorTemplateCommon<T, U>& Vec)
95       : Data(Vec.data()), Length(Vec.size()) {
96     debugCheckNullptrInvariant();
97   }
98 
99   template <
100       typename Container,
101       typename = std::enable_if_t<std::is_same_v<
102           std::remove_const_t<decltype(std::declval<Container>().data())>,
103           T*>>>
ArrayRef(const Container & container)104   /* implicit */ ArrayRef(const Container& container)
105       : Data(container.data()), Length(container.size()) {
106     debugCheckNullptrInvariant();
107   }
108 
109   /// Construct an ArrayRef from a std::vector.
110   // The enable_if stuff here makes sure that this isn't used for
111   // std::vector<bool>, because ArrayRef can't work on a std::vector<bool>
112   // bitfield.
113   template <typename A>
ArrayRef(const std::vector<T,A> & Vec)114   /* implicit */ ArrayRef(const std::vector<T, A>& Vec)
115       : Data(Vec.data()), Length(Vec.size()) {
116     static_assert(
117         !std::is_same<T, bool>::value,
118         "ArrayRef<bool> cannot be constructed from a std::vector<bool> bitfield.");
119   }
120 
121   /// Construct an ArrayRef from a std::array
122   template <size_t N>
ArrayRef(const std::array<T,N> & Arr)123   /* implicit */ constexpr ArrayRef(const std::array<T, N>& Arr)
124       : Data(Arr.data()), Length(N) {}
125 
126   /// Construct an ArrayRef from a C array.
127   template <size_t N>
128   // NOLINTNEXTLINE(*c-arrays*)
ArrayRef(const T (& Arr)[N])129   /* implicit */ constexpr ArrayRef(const T (&Arr)[N]) : Data(Arr), Length(N) {}
130 
131   /// Construct an ArrayRef from a std::initializer_list.
ArrayRef(const std::initializer_list<T> & Vec)132   /* implicit */ constexpr ArrayRef(const std::initializer_list<T>& Vec)
133       : Data(
134             std::begin(Vec) == std::end(Vec) ? static_cast<T*>(nullptr)
135                                              : std::begin(Vec)),
136         Length(Vec.size()) {}
137 
138   /// @}
139   /// @name Simple Operations
140   /// @{
141 
begin()142   constexpr iterator begin() const {
143     return Data;
144   }
end()145   constexpr iterator end() const {
146     return Data + Length;
147   }
148 
149   // These are actually the same as iterator, since ArrayRef only
150   // gives you const iterators.
cbegin()151   constexpr const_iterator cbegin() const {
152     return Data;
153   }
cend()154   constexpr const_iterator cend() const {
155     return Data + Length;
156   }
157 
rbegin()158   constexpr reverse_iterator rbegin() const {
159     return reverse_iterator(end());
160   }
rend()161   constexpr reverse_iterator rend() const {
162     return reverse_iterator(begin());
163   }
164 
165   /// empty - Check if the array is empty.
empty()166   constexpr bool empty() const {
167     return Length == 0;
168   }
169 
data()170   constexpr const T* data() const {
171     return Data;
172   }
173 
174   /// size - Get the array size.
size()175   constexpr size_t size() const {
176     return Length;
177   }
178 
179   /// front - Get the first element.
front()180   C10_HOST_CONSTEXPR_EXCEPT_WIN_CUDA const T& front() const {
181     TORCH_CHECK(
182         !empty(), "ArrayRef: attempted to access front() of empty list");
183     return Data[0];
184   }
185 
186   /// back - Get the last element.
back()187   C10_HOST_CONSTEXPR_EXCEPT_WIN_CUDA const T& back() const {
188     TORCH_CHECK(!empty(), "ArrayRef: attempted to access back() of empty list");
189     return Data[Length - 1];
190   }
191 
192   /// equals - Check for element-wise equality.
equals(ArrayRef RHS)193   constexpr bool equals(ArrayRef RHS) const {
194     return Length == RHS.Length && std::equal(begin(), end(), RHS.begin());
195   }
196 
197   /// slice(n, m) - Take M elements of the array starting at element N
slice(size_t N,size_t M)198   C10_HOST_CONSTEXPR_EXCEPT_WIN_CUDA ArrayRef<T> slice(size_t N, size_t M)
199       const {
200     TORCH_CHECK(
201         N + M <= size(),
202         "ArrayRef: invalid slice, N = ",
203         N,
204         "; M = ",
205         M,
206         "; size = ",
207         size());
208     return ArrayRef<T>(data() + N, M);
209   }
210 
211   /// slice(n) - Chop off the first N elements of the array.
slice(size_t N)212   C10_HOST_CONSTEXPR_EXCEPT_WIN_CUDA ArrayRef<T> slice(size_t N) const {
213     TORCH_CHECK(
214         N <= size(), "ArrayRef: invalid slice, N = ", N, "; size = ", size());
215     return slice(N, size() - N);
216   }
217 
218   /// @}
219   /// @name Operator Overloads
220   /// @{
221   constexpr const T& operator[](size_t Index) const {
222     return Data[Index];
223   }
224 
225   /// Vector compatibility
at(size_t Index)226   C10_HOST_CONSTEXPR_EXCEPT_WIN_CUDA const T& at(size_t Index) const {
227     TORCH_CHECK(
228         Index < Length,
229         "ArrayRef: invalid index Index = ",
230         Index,
231         "; Length = ",
232         Length);
233     return Data[Index];
234   }
235 
236   /// Disallow accidental assignment from a temporary.
237   ///
238   /// The declaration here is extra complicated so that "arrayRef = {}"
239   /// continues to select the move assignment operator.
240   template <typename U>
241   std::enable_if_t<std::is_same_v<U, T>, ArrayRef<T>>& operator=(
242       // NOLINTNEXTLINE(cppcoreguidelines-missing-std-forward)
243       U&& Temporary) = delete;
244 
245   /// Disallow accidental assignment from a temporary.
246   ///
247   /// The declaration here is extra complicated so that "arrayRef = {}"
248   /// continues to select the move assignment operator.
249   template <typename U>
250   std::enable_if_t<std::is_same_v<U, T>, ArrayRef<T>>& operator=(
251       std::initializer_list<U>) = delete;
252 
253   /// @}
254   /// @name Expensive Operations
255   /// @{
vec()256   std::vector<T> vec() const {
257     return std::vector<T>(Data, Data + Length);
258   }
259 
260   /// @}
261 };
262 
263 template <typename T>
264 std::ostream& operator<<(std::ostream& out, ArrayRef<T> list) {
265   int i = 0;
266   out << "[";
267   for (const auto& e : list) {
268     if (i++ > 0)
269       out << ", ";
270     out << e;
271   }
272   out << "]";
273   return out;
274 }
275 
276 /// @name ArrayRef Convenience constructors
277 /// @{
278 
279 /// Construct an ArrayRef from a single element.
280 template <typename T>
makeArrayRef(const T & OneElt)281 ArrayRef<T> makeArrayRef(const T& OneElt) {
282   return OneElt;
283 }
284 
285 /// Construct an ArrayRef from a pointer and length.
286 template <typename T>
makeArrayRef(const T * data,size_t length)287 ArrayRef<T> makeArrayRef(const T* data, size_t length) {
288   return ArrayRef<T>(data, length);
289 }
290 
291 /// Construct an ArrayRef from a range.
292 template <typename T>
makeArrayRef(const T * begin,const T * end)293 ArrayRef<T> makeArrayRef(const T* begin, const T* end) {
294   return ArrayRef<T>(begin, end);
295 }
296 
297 /// Construct an ArrayRef from a SmallVector.
298 template <typename T>
makeArrayRef(const SmallVectorImpl<T> & Vec)299 ArrayRef<T> makeArrayRef(const SmallVectorImpl<T>& Vec) {
300   return Vec;
301 }
302 
303 /// Construct an ArrayRef from a SmallVector.
304 template <typename T, unsigned N>
makeArrayRef(const SmallVector<T,N> & Vec)305 ArrayRef<T> makeArrayRef(const SmallVector<T, N>& Vec) {
306   return Vec;
307 }
308 
309 /// Construct an ArrayRef from a std::vector.
310 template <typename T>
makeArrayRef(const std::vector<T> & Vec)311 ArrayRef<T> makeArrayRef(const std::vector<T>& Vec) {
312   return Vec;
313 }
314 
315 /// Construct an ArrayRef from a std::array.
316 template <typename T, std::size_t N>
makeArrayRef(const std::array<T,N> & Arr)317 ArrayRef<T> makeArrayRef(const std::array<T, N>& Arr) {
318   return Arr;
319 }
320 
321 /// Construct an ArrayRef from an ArrayRef (no-op) (const)
322 template <typename T>
makeArrayRef(const ArrayRef<T> & Vec)323 ArrayRef<T> makeArrayRef(const ArrayRef<T>& Vec) {
324   return Vec;
325 }
326 
327 /// Construct an ArrayRef from an ArrayRef (no-op)
328 template <typename T>
makeArrayRef(ArrayRef<T> & Vec)329 ArrayRef<T>& makeArrayRef(ArrayRef<T>& Vec) {
330   return Vec;
331 }
332 
333 /// Construct an ArrayRef from a C array.
334 template <typename T, size_t N>
335 // NOLINTNEXTLINE(*c-arrays*)
makeArrayRef(const T (& Arr)[N])336 ArrayRef<T> makeArrayRef(const T (&Arr)[N]) {
337   return ArrayRef<T>(Arr);
338 }
339 
340 // WARNING: Template instantiation will NOT be willing to do an implicit
341 // conversions to get you to an c10::ArrayRef, which is why we need so
342 // many overloads.
343 
344 template <typename T>
345 bool operator==(c10::ArrayRef<T> a1, c10::ArrayRef<T> a2) {
346   return a1.equals(a2);
347 }
348 
349 template <typename T>
350 bool operator!=(c10::ArrayRef<T> a1, c10::ArrayRef<T> a2) {
351   return !a1.equals(a2);
352 }
353 
354 template <typename T>
355 bool operator==(const std::vector<T>& a1, c10::ArrayRef<T> a2) {
356   return c10::ArrayRef<T>(a1).equals(a2);
357 }
358 
359 template <typename T>
360 bool operator!=(const std::vector<T>& a1, c10::ArrayRef<T> a2) {
361   return !c10::ArrayRef<T>(a1).equals(a2);
362 }
363 
364 template <typename T>
365 bool operator==(c10::ArrayRef<T> a1, const std::vector<T>& a2) {
366   return a1.equals(c10::ArrayRef<T>(a2));
367 }
368 
369 template <typename T>
370 bool operator!=(c10::ArrayRef<T> a1, const std::vector<T>& a2) {
371   return !a1.equals(c10::ArrayRef<T>(a2));
372 }
373 
374 using IntArrayRef = ArrayRef<int64_t>;
375 
376 // This alias is deprecated because it doesn't make ownership
377 // semantics obvious.  Use IntArrayRef instead!
378 C10_DEFINE_DEPRECATED_USING(IntList, ArrayRef<int64_t>)
379 
380 } // namespace c10
381