span.h 18 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495
  1. // Copyright 2017 The Chromium Authors. All rights reserved.
  2. // Use of this source code is governed by a BSD-style license that can be
  3. // found in the LICENSE file.
  4. #ifndef BASE_CONTAINERS_SPAN_H_
  5. #define BASE_CONTAINERS_SPAN_H_
  6. #include <stddef.h>
  7. #include <algorithm>
  8. #include <array>
  9. #include <iterator>
  10. #include <limits>
  11. #include <type_traits>
  12. #include <utility>
  13. #include "base/check_op.h"
  14. #include "base/containers/checked_iterators.h"
  15. #include "base/macros.h"
  16. #include "base/stl_util.h"
  17. #include "base/template_util.h"
  18. namespace base {
  19. // [views.constants]
  20. constexpr size_t dynamic_extent = std::numeric_limits<size_t>::max();
  21. template <typename T, size_t Extent = dynamic_extent>
  22. class span;
  23. namespace internal {
  24. template <size_t I>
  25. using size_constant = std::integral_constant<size_t, I>;
  26. template <typename T>
  27. struct ExtentImpl : size_constant<dynamic_extent> {};
  28. template <typename T, size_t N>
  29. struct ExtentImpl<T[N]> : size_constant<N> {};
  30. template <typename T, size_t N>
  31. struct ExtentImpl<std::array<T, N>> : size_constant<N> {};
  32. template <typename T, size_t N>
  33. struct ExtentImpl<base::span<T, N>> : size_constant<N> {};
  34. template <typename T>
  35. using Extent = ExtentImpl<std::remove_cv_t<std::remove_reference_t<T>>>;
  36. template <typename T>
  37. struct IsSpanImpl : std::false_type {};
  38. template <typename T, size_t Extent>
  39. struct IsSpanImpl<span<T, Extent>> : std::true_type {};
  40. template <typename T>
  41. using IsNotSpan = negation<IsSpanImpl<std::decay_t<T>>>;
  42. template <typename T>
  43. struct IsStdArrayImpl : std::false_type {};
  44. template <typename T, size_t N>
  45. struct IsStdArrayImpl<std::array<T, N>> : std::true_type {};
  46. template <typename T>
  47. using IsNotStdArray = negation<IsStdArrayImpl<std::decay_t<T>>>;
  48. template <typename T>
  49. using IsNotCArray = negation<std::is_array<std::remove_reference_t<T>>>;
  50. template <typename From, typename To>
  51. using IsLegalDataConversion = std::is_convertible<From (*)[], To (*)[]>;
  52. template <typename Container, typename T>
  53. using ContainerHasConvertibleData = IsLegalDataConversion<
  54. std::remove_pointer_t<decltype(base::data(std::declval<Container>()))>,
  55. T>;
  56. template <typename Container>
  57. using ContainerHasIntegralSize =
  58. std::is_integral<decltype(base::size(std::declval<Container>()))>;
  59. template <typename From, size_t FromExtent, typename To, size_t ToExtent>
  60. using EnableIfLegalSpanConversion =
  61. std::enable_if_t<(ToExtent == dynamic_extent || ToExtent == FromExtent) &&
  62. IsLegalDataConversion<From, To>::value>;
  63. // SFINAE check if Array can be converted to a span<T>.
  64. template <typename Array, typename T, size_t Extent>
  65. using EnableIfSpanCompatibleArray =
  66. std::enable_if_t<(Extent == dynamic_extent ||
  67. Extent == internal::Extent<Array>::value) &&
  68. ContainerHasConvertibleData<Array, T>::value>;
  69. // SFINAE check if Container can be converted to a span<T>.
  70. template <typename Container, typename T>
  71. using IsSpanCompatibleContainer =
  72. conjunction<IsNotSpan<Container>,
  73. IsNotStdArray<Container>,
  74. IsNotCArray<Container>,
  75. ContainerHasConvertibleData<Container, T>,
  76. ContainerHasIntegralSize<Container>>;
  77. template <typename Container, typename T>
  78. using EnableIfSpanCompatibleContainer =
  79. std::enable_if_t<IsSpanCompatibleContainer<Container, T>::value>;
  80. template <typename Container, typename T, size_t Extent>
  81. using EnableIfSpanCompatibleContainerAndSpanIsDynamic =
  82. std::enable_if_t<IsSpanCompatibleContainer<Container, T>::value &&
  83. Extent == dynamic_extent>;
  84. // A helper template for storing the size of a span. Spans with static extents
  85. // don't require additional storage, since the extent itself is specified in the
  86. // template parameter.
  87. template <size_t Extent>
  88. class ExtentStorage {
  89. public:
  90. constexpr explicit ExtentStorage(size_t size) noexcept {}
  91. constexpr size_t size() const noexcept { return Extent; }
  92. };
  93. // Specialization of ExtentStorage for dynamic extents, which do require
  94. // explicit storage for the size.
  95. template <>
  96. struct ExtentStorage<dynamic_extent> {
  97. constexpr explicit ExtentStorage(size_t size) noexcept : size_(size) {}
  98. constexpr size_t size() const noexcept { return size_; }
  99. private:
  100. size_t size_;
  101. };
  102. // must_not_be_dynamic_extent prevents |dynamic_extent| from being returned in a
  103. // constexpr context.
  104. template <size_t kExtent>
  105. constexpr size_t must_not_be_dynamic_extent() {
  106. static_assert(
  107. kExtent != dynamic_extent,
  108. "EXTENT should only be used for containers with a static extent.");
  109. return kExtent;
  110. }
  111. } // namespace internal
  112. // A span is a value type that represents an array of elements of type T. Since
  113. // it only consists of a pointer to memory with an associated size, it is very
  114. // light-weight. It is cheap to construct, copy, move and use spans, so that
  115. // users are encouraged to use it as a pass-by-value parameter. A span does not
  116. // own the underlying memory, so care must be taken to ensure that a span does
  117. // not outlive the backing store.
  118. //
  119. // span is somewhat analogous to StringPiece, but with arbitrary element types,
  120. // allowing mutation if T is non-const.
  121. //
  122. // span is implicitly convertible from C++ arrays, as well as most [1]
  123. // container-like types that provide a data() and size() method (such as
  124. // std::vector<T>). A mutable span<T> can also be implicitly converted to an
  125. // immutable span<const T>.
  126. //
  127. // Consider using a span for functions that take a data pointer and size
  128. // parameter: it allows the function to still act on an array-like type, while
  129. // allowing the caller code to be a bit more concise.
  130. //
  131. // For read-only data access pass a span<const T>: the caller can supply either
  132. // a span<const T> or a span<T>, while the callee will have a read-only view.
  133. // For read-write access a mutable span<T> is required.
  134. //
  135. // Without span:
  136. // Read-Only:
  137. // // std::string HexEncode(const uint8_t* data, size_t size);
  138. // std::vector<uint8_t> data_buffer = GenerateData();
  139. // std::string r = HexEncode(data_buffer.data(), data_buffer.size());
  140. //
  141. // Mutable:
  142. // // ssize_t SafeSNPrintf(char* buf, size_t N, const char* fmt, Args...);
  143. // char str_buffer[100];
  144. // SafeSNPrintf(str_buffer, sizeof(str_buffer), "Pi ~= %lf", 3.14);
  145. //
  146. // With span:
  147. // Read-Only:
  148. // // std::string HexEncode(base::span<const uint8_t> data);
  149. // std::vector<uint8_t> data_buffer = GenerateData();
  150. // std::string r = HexEncode(data_buffer);
  151. //
  152. // Mutable:
  153. // // ssize_t SafeSNPrintf(base::span<char>, const char* fmt, Args...);
  154. // char str_buffer[100];
  155. // SafeSNPrintf(str_buffer, "Pi ~= %lf", 3.14);
  156. //
  157. // Spans with "const" and pointers
  158. // -------------------------------
  159. //
  160. // Const and pointers can get confusing. Here are vectors of pointers and their
  161. // corresponding spans:
  162. //
  163. // const std::vector<int*> => base::span<int* const>
  164. // std::vector<const int*> => base::span<const int*>
  165. // const std::vector<const int*> => base::span<const int* const>
  166. //
  167. // Differences from the C++20 draft
  168. // --------------------------------
  169. //
  170. // http://eel.is/c++draft/views contains the latest C++20 draft of std::span.
  171. // Chromium tries to follow the draft as close as possible. Differences between
  172. // the draft and the implementation are documented in subsections below.
  173. //
  174. // Differences from [span.objectrep]:
  175. // - as_bytes() and as_writable_bytes() return spans of uint8_t instead of
  176. // std::byte (std::byte is a C++17 feature)
  177. //
  178. // Differences from [span.cons]:
  179. // - Constructing a static span (i.e. Extent != dynamic_extent) from a dynamic
  180. // sized container (e.g. std::vector) requires an explicit conversion (in the
  181. // C++20 draft this is simply UB)
  182. //
  183. // Differences from [span.obs]:
  184. // - empty() is marked with WARN_UNUSED_RESULT instead of [[nodiscard]]
  185. // ([[nodiscard]] is a C++17 feature)
  186. //
  187. // Furthermore, all constructors and methods are marked noexcept due to the lack
  188. // of exceptions in Chromium.
  189. //
  190. // Due to the lack of class template argument deduction guides in C++14
  191. // appropriate make_span() utility functions are provided.
  192. // [span], class template span
  193. template <typename T, size_t Extent>
  194. class span : public internal::ExtentStorage<Extent> {
  195. private:
  196. using ExtentStorage = internal::ExtentStorage<Extent>;
  197. public:
  198. using element_type = T;
  199. using value_type = std::remove_cv_t<T>;
  200. using size_type = size_t;
  201. using difference_type = ptrdiff_t;
  202. using pointer = T*;
  203. using reference = T&;
  204. using iterator = CheckedContiguousIterator<T>;
  205. // TODO(https://crbug.com/828324): Drop the const_iterator typedef once gMock
  206. // supports containers without this nested type.
  207. using const_iterator = iterator;
  208. using reverse_iterator = std::reverse_iterator<iterator>;
  209. static constexpr size_t extent = Extent;
  210. // [span.cons], span constructors, copy, assignment, and destructor
  211. constexpr span() noexcept : ExtentStorage(0), data_(nullptr) {
  212. static_assert(Extent == dynamic_extent || Extent == 0, "Invalid Extent");
  213. }
  214. constexpr span(T* data, size_t size) noexcept
  215. : ExtentStorage(size), data_(data) {
  216. CHECK(Extent == dynamic_extent || Extent == size);
  217. }
  218. // Artificially templatized to break ambiguity for span(ptr, 0).
  219. template <typename = void>
  220. constexpr span(T* begin, T* end) noexcept : span(begin, end - begin) {
  221. // Note: CHECK_LE is not constexpr, hence regular CHECK must be used.
  222. CHECK(begin <= end);
  223. }
  224. template <
  225. size_t N,
  226. typename = internal::EnableIfSpanCompatibleArray<T (&)[N], T, Extent>>
  227. constexpr span(T (&array)[N]) noexcept : span(base::data(array), N) {}
  228. template <
  229. typename U,
  230. size_t N,
  231. typename =
  232. internal::EnableIfSpanCompatibleArray<std::array<U, N>&, T, Extent>>
  233. constexpr span(std::array<U, N>& array) noexcept
  234. : span(base::data(array), N) {}
  235. template <typename U,
  236. size_t N,
  237. typename = internal::
  238. EnableIfSpanCompatibleArray<const std::array<U, N>&, T, Extent>>
  239. constexpr span(const std::array<U, N>& array) noexcept
  240. : span(base::data(array), N) {}
  241. // Conversion from a container that has compatible base::data() and integral
  242. // base::size().
  243. template <
  244. typename Container,
  245. typename =
  246. internal::EnableIfSpanCompatibleContainerAndSpanIsDynamic<Container&,
  247. T,
  248. Extent>>
  249. constexpr span(Container& container) noexcept
  250. : span(base::data(container), base::size(container)) {}
  251. template <
  252. typename Container,
  253. typename = internal::EnableIfSpanCompatibleContainerAndSpanIsDynamic<
  254. const Container&,
  255. T,
  256. Extent>>
  257. constexpr span(const Container& container) noexcept
  258. : span(base::data(container), base::size(container)) {}
  259. constexpr span(const span& other) noexcept = default;
  260. // Conversions from spans of compatible types and extents: this allows a
  261. // span<T> to be seamlessly used as a span<const T>, but not the other way
  262. // around. If extent is not dynamic, OtherExtent has to be equal to Extent.
  263. template <
  264. typename U,
  265. size_t OtherExtent,
  266. typename =
  267. internal::EnableIfLegalSpanConversion<U, OtherExtent, T, Extent>>
  268. constexpr span(const span<U, OtherExtent>& other)
  269. : span(other.data(), other.size()) {}
  270. constexpr span& operator=(const span& other) noexcept = default;
  271. ~span() noexcept = default;
  272. // [span.sub], span subviews
  273. template <size_t Count>
  274. constexpr span<T, Count> first() const noexcept {
  275. static_assert(Count <= Extent, "Count must not exceed Extent");
  276. CHECK(Extent != dynamic_extent || Count <= size());
  277. return {data(), Count};
  278. }
  279. template <size_t Count>
  280. constexpr span<T, Count> last() const noexcept {
  281. static_assert(Count <= Extent, "Count must not exceed Extent");
  282. CHECK(Extent != dynamic_extent || Count <= size());
  283. return {data() + (size() - Count), Count};
  284. }
  285. template <size_t Offset, size_t Count = dynamic_extent>
  286. constexpr span<T,
  287. (Count != dynamic_extent
  288. ? Count
  289. : (Extent != dynamic_extent ? Extent - Offset
  290. : dynamic_extent))>
  291. subspan() const noexcept {
  292. static_assert(Offset <= Extent, "Offset must not exceed Extent");
  293. static_assert(Count == dynamic_extent || Count <= Extent - Offset,
  294. "Count must not exceed Extent - Offset");
  295. CHECK(Extent != dynamic_extent || Offset <= size());
  296. CHECK(Extent != dynamic_extent || Count == dynamic_extent ||
  297. Count <= size() - Offset);
  298. return {data() + Offset, Count != dynamic_extent ? Count : size() - Offset};
  299. }
  300. constexpr span<T, dynamic_extent> first(size_t count) const noexcept {
  301. // Note: CHECK_LE is not constexpr, hence regular CHECK must be used.
  302. CHECK(count <= size());
  303. return {data(), count};
  304. }
  305. constexpr span<T, dynamic_extent> last(size_t count) const noexcept {
  306. // Note: CHECK_LE is not constexpr, hence regular CHECK must be used.
  307. CHECK(count <= size());
  308. return {data() + (size() - count), count};
  309. }
  310. constexpr span<T, dynamic_extent> subspan(size_t offset,
  311. size_t count = dynamic_extent) const
  312. noexcept {
  313. // Note: CHECK_LE is not constexpr, hence regular CHECK must be used.
  314. CHECK(offset <= size());
  315. CHECK(count == dynamic_extent || count <= size() - offset);
  316. return {data() + offset, count != dynamic_extent ? count : size() - offset};
  317. }
  318. // [span.obs], span observers
  319. constexpr size_t size() const noexcept { return ExtentStorage::size(); }
  320. constexpr size_t size_bytes() const noexcept { return size() * sizeof(T); }
  321. constexpr bool empty() const noexcept WARN_UNUSED_RESULT {
  322. return size() == 0;
  323. }
  324. // [span.elem], span element access
  325. constexpr T& operator[](size_t idx) const noexcept {
  326. // Note: CHECK_LT is not constexpr, hence regular CHECK must be used.
  327. CHECK(idx < size());
  328. return *(data() + idx);
  329. }
  330. constexpr T& front() const noexcept {
  331. static_assert(Extent == dynamic_extent || Extent > 0,
  332. "Extent must not be 0");
  333. CHECK(Extent != dynamic_extent || !empty());
  334. return *data();
  335. }
  336. constexpr T& back() const noexcept {
  337. static_assert(Extent == dynamic_extent || Extent > 0,
  338. "Extent must not be 0");
  339. CHECK(Extent != dynamic_extent || !empty());
  340. return *(data() + size() - 1);
  341. }
  342. constexpr T* data() const noexcept { return data_; }
  343. // [span.iter], span iterator support
  344. constexpr iterator begin() const noexcept {
  345. return iterator(data_, data_ + size());
  346. }
  347. constexpr iterator end() const noexcept {
  348. return iterator(data_, data_ + size(), data_ + size());
  349. }
  350. constexpr reverse_iterator rbegin() const noexcept {
  351. return reverse_iterator(end());
  352. }
  353. constexpr reverse_iterator rend() const noexcept {
  354. return reverse_iterator(begin());
  355. }
  356. private:
  357. T* data_;
  358. };
  359. // span<T, Extent>::extent can not be declared inline prior to C++17, hence this
  360. // definition is required.
  361. template <class T, size_t Extent>
  362. constexpr size_t span<T, Extent>::extent;
  363. // [span.objectrep], views of object representation
  364. template <typename T, size_t X>
  365. span<const uint8_t, (X == dynamic_extent ? dynamic_extent : sizeof(T) * X)>
  366. as_bytes(span<T, X> s) noexcept {
  367. return {reinterpret_cast<const uint8_t*>(s.data()), s.size_bytes()};
  368. }
  369. template <typename T,
  370. size_t X,
  371. typename = std::enable_if_t<!std::is_const<T>::value>>
  372. span<uint8_t, (X == dynamic_extent ? dynamic_extent : sizeof(T) * X)>
  373. as_writable_bytes(span<T, X> s) noexcept {
  374. return {reinterpret_cast<uint8_t*>(s.data()), s.size_bytes()};
  375. }
  376. // Type-deducing helpers for constructing a span.
  377. template <int&... ExplicitArgumentBarrier, typename T>
  378. constexpr span<T> make_span(T* data, size_t size) noexcept {
  379. return {data, size};
  380. }
  381. template <int&... ExplicitArgumentBarrier, typename T>
  382. constexpr span<T> make_span(T* begin, T* end) noexcept {
  383. return {begin, end};
  384. }
  385. // make_span utility function that deduces both the span's value_type and extent
  386. // from the passed in argument.
  387. //
  388. // Usage: auto span = base::make_span(...);
  389. template <int&... ExplicitArgumentBarrier, typename Container>
  390. constexpr auto make_span(Container&& container) noexcept {
  391. using T =
  392. std::remove_pointer_t<decltype(base::data(std::declval<Container>()))>;
  393. using Extent = internal::Extent<Container>;
  394. return span<T, Extent::value>(std::forward<Container>(container));
  395. }
  396. // make_span utility function that allows callers to explicit specify the span's
  397. // extent, the value_type is deduced automatically. This is useful when passing
  398. // a dynamically sized container to a method expecting static spans, when the
  399. // container is known to have the correct size.
  400. //
  401. // Note: This will CHECK that N indeed matches size(container).
  402. //
  403. // Usage: auto static_span = base::make_span<N>(...);
  404. template <size_t N, int&... ExplicitArgumentBarrier, typename Container>
  405. constexpr auto make_span(Container&& container) noexcept {
  406. using T =
  407. std::remove_pointer_t<decltype(base::data(std::declval<Container>()))>;
  408. return span<T, N>(base::data(container), base::size(container));
  409. }
  410. } // namespace base
  411. // EXTENT returns the size of any type that can be converted to a |base::span|
  412. // with definite extent, i.e. everything that is a contiguous storage of some
  413. // sort with static size. Specifically, this works for std::array in a constexpr
  414. // context. Note:
  415. // * |base::size| should be preferred for plain arrays.
  416. // * In run-time contexts, functions such as |std::array::size| should be
  417. // preferred.
  418. #define EXTENT(x) \
  419. ::base::internal::must_not_be_dynamic_extent<decltype( \
  420. ::base::make_span(x))::extent>()
  421. #endif // BASE_CONTAINERS_SPAN_H_