1 ///////////////////////////////////////////////////////////////////////////////
3 // Copyright (c) 2015 Microsoft Corporation. All rights reserved.
5 // This code is licensed under the MIT License (MIT).
7 // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
8 // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
9 // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
10 // AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
11 // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
12 // OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
15 ///////////////////////////////////////////////////////////////////////////////
18 // https://github.com/Microsoft/GSL/blob/3819df6e378ffccf0e29465afe99c3b324c2aa70/include/gsl/span
20 // https://github.com/Microsoft/GSL/blob/3819df6e378ffccf0e29465afe99c3b324c2aa70/include/gsl/gsl_util
22 #ifndef mozilla_Span_h
23 #define mozilla_Span_h
30 #include <type_traits>
33 #include "mozilla/Array.h"
34 #include "mozilla/Assertions.h"
35 #include "mozilla/Casting.h"
36 #include "mozilla/IntegerTypeTraits.h"
37 #include "mozilla/UniquePtr.h"
41 // Stuff from gsl_util
43 // narrow_cast(): a searchable way to do narrowing casts of values
44 template <class T
, class U
>
45 inline constexpr T
narrow_cast(U
&& u
) {
46 return static_cast<T
>(std::forward
<U
>(u
));
51 // [views.constants], constants
52 // This was -1 in gsl::span, but using size_t for sizes instead of ptrdiff_t
53 // and reserving a magic value that realistically doesn't occur in
54 // compile-time-constant Span sizes makes things a lot less messy in terms of
55 // comparison between signed and unsigned.
56 constexpr const size_t dynamic_extent
= std::numeric_limits
<size_t>::max();
58 template <class ElementType
, size_t Extent
= dynamic_extent
>
61 // implementation details
62 namespace span_details
{
65 struct is_span_oracle
: std::false_type
{};
67 template <class ElementType
, size_t Extent
>
68 struct is_span_oracle
<mozilla::Span
<ElementType
, Extent
>> : std::true_type
{};
71 struct is_span
: public is_span_oracle
<std::remove_cv_t
<T
>> {};
74 struct is_std_array_oracle
: std::false_type
{};
76 template <class ElementType
, size_t Extent
>
77 struct is_std_array_oracle
<std::array
<ElementType
, Extent
>> : std::true_type
{};
80 struct is_std_array
: public is_std_array_oracle
<std::remove_cv_t
<T
>> {};
82 template <size_t From
, size_t To
>
83 struct is_allowed_extent_conversion
84 : public std::integral_constant
<bool, From
== To
||
85 From
== mozilla::dynamic_extent
||
86 To
== mozilla::dynamic_extent
> {};
88 template <class From
, class To
>
89 struct is_allowed_element_type_conversion
90 : public std::integral_constant
<
91 bool, std::is_convertible_v
<From (*)[], To (*)[]>> {};
93 struct SpanKnownBounds
{};
95 template <class SpanT
, bool IsConst
>
97 using element_type_
= typename
SpanT::element_type
;
99 template <class ElementType
, size_t Extent
>
100 friend class ::mozilla::Span
;
103 using iterator_category
= std::random_access_iterator_tag
;
104 using value_type
= std::remove_const_t
<element_type_
>;
105 using difference_type
= typename
SpanT::index_type
;
108 std::conditional_t
<IsConst
, const element_type_
, element_type_
>&;
109 using pointer
= std::add_pointer_t
<reference
>;
111 constexpr span_iterator() : span_iterator(nullptr, 0, SpanKnownBounds
{}) {}
113 constexpr span_iterator(const SpanT
* span
, typename
SpanT::index_type index
)
114 : span_(span
), index_(index
) {
115 MOZ_RELEASE_ASSERT(span
== nullptr ||
116 (index_
>= 0 && index
<= span_
->Length()));
120 // For whatever reason, the compiler doesn't like optimizing away the above
121 // MOZ_RELEASE_ASSERT when `span_iterator` is constructed for
122 // obviously-correct cases like `span.begin()` or `span.end()`. We provide
123 // this private constructor for such cases.
124 constexpr span_iterator(const SpanT
* span
, typename
SpanT::index_type index
,
126 : span_(span
), index_(index
) {}
129 // `other` is already correct by construction; we do not need to go through
130 // the release assert above. Put differently, this constructor is effectively
131 // a copy constructor and therefore needs no assertions.
132 friend class span_iterator
<SpanT
, true>;
133 constexpr MOZ_IMPLICIT
span_iterator(const span_iterator
<SpanT
, false>& other
)
134 : span_(other
.span_
), index_(other
.index_
) {}
136 constexpr span_iterator
<SpanT
, IsConst
>& operator=(
137 const span_iterator
<SpanT
, IsConst
>&) = default;
139 constexpr reference
operator*() const {
140 MOZ_RELEASE_ASSERT(span_
);
141 return (*span_
)[index_
];
144 constexpr pointer
operator->() const {
145 MOZ_RELEASE_ASSERT(span_
);
146 return &((*span_
)[index_
]);
149 constexpr span_iterator
& operator++() {
154 constexpr span_iterator
operator++(int) {
160 constexpr span_iterator
& operator--() {
165 constexpr span_iterator
operator--(int) {
171 constexpr span_iterator
operator+(difference_type n
) const {
176 constexpr span_iterator
& operator+=(difference_type n
) {
177 MOZ_RELEASE_ASSERT(span_
&& (index_
+ n
) >= 0 &&
178 (index_
+ n
) <= span_
->Length());
183 constexpr span_iterator
operator-(difference_type n
) const {
188 constexpr span_iterator
& operator-=(difference_type n
) { return *this += -n
; }
190 constexpr difference_type
operator-(const span_iterator
& rhs
) const {
191 MOZ_RELEASE_ASSERT(span_
== rhs
.span_
);
192 return index_
- rhs
.index_
;
195 constexpr reference
operator[](difference_type n
) const {
199 constexpr friend bool operator==(const span_iterator
& lhs
,
200 const span_iterator
& rhs
) {
201 // Iterators from different spans are uncomparable. A diagnostic assertion
202 // should be enough to check this, though. To ensure that no iterators from
203 // different spans are ever considered equal, still compare them in release
205 MOZ_DIAGNOSTIC_ASSERT(lhs
.span_
== rhs
.span_
);
206 return lhs
.index_
== rhs
.index_
&& lhs
.span_
== rhs
.span_
;
209 constexpr friend bool operator!=(const span_iterator
& lhs
,
210 const span_iterator
& rhs
) {
211 return !(lhs
== rhs
);
214 constexpr friend bool operator<(const span_iterator
& lhs
,
215 const span_iterator
& rhs
) {
216 MOZ_DIAGNOSTIC_ASSERT(lhs
.span_
== rhs
.span_
);
217 return lhs
.index_
< rhs
.index_
;
220 constexpr friend bool operator<=(const span_iterator
& lhs
,
221 const span_iterator
& rhs
) {
225 constexpr friend bool operator>(const span_iterator
& lhs
,
226 const span_iterator
& rhs
) {
230 constexpr friend bool operator>=(const span_iterator
& lhs
,
231 const span_iterator
& rhs
) {
235 void swap(span_iterator
& rhs
) {
236 std::swap(index_
, rhs
.index_
);
237 std::swap(span_
, rhs
.span_
);
245 template <class Span
, bool IsConst
>
246 inline constexpr span_iterator
<Span
, IsConst
> operator+(
247 typename span_iterator
<Span
, IsConst
>::difference_type n
,
248 const span_iterator
<Span
, IsConst
>& rhs
) {
252 template <size_t Ext
>
255 using index_type
= size_t;
257 static_assert(Ext
>= 0, "A fixed-size Span must be >= 0 in size.");
259 constexpr extent_type() = default;
261 template <index_type Other
>
262 constexpr MOZ_IMPLICIT
extent_type(extent_type
<Other
> ext
) {
264 Other
== Ext
|| Other
== dynamic_extent
,
265 "Mismatch between fixed-size extent and size of initializing data.");
266 MOZ_RELEASE_ASSERT(ext
.size() == Ext
);
269 constexpr MOZ_IMPLICIT
extent_type(index_type length
) {
270 MOZ_RELEASE_ASSERT(length
== Ext
);
273 constexpr index_type
size() const { return Ext
; }
277 class extent_type
<dynamic_extent
> {
279 using index_type
= size_t;
281 template <index_type Other
>
282 explicit constexpr extent_type(extent_type
<Other
> ext
) : size_(ext
.size()) {}
284 explicit constexpr extent_type(index_type length
) : size_(length
) {}
286 constexpr index_type
size() const { return size_
; }
291 } // namespace span_details
294 * Span - slices for C++
296 * Span implements Rust's slice concept for C++. It's called "Span" instead of
297 * "Slice" to follow the naming used in C++ Core Guidelines.
299 * A Span wraps a pointer and a length that identify a non-owning view to a
300 * contiguous block of memory of objects of the same type. Various types,
301 * including (pre-decay) C arrays, XPCOM strings, nsTArray, mozilla::Array,
302 * mozilla::Range and contiguous standard-library containers, auto-convert
303 * into Spans when attempting to pass them as arguments to methods that take
304 * Spans. (Span itself autoconverts into mozilla::Range.)
306 * Like Rust's slices, Span provides safety against out-of-bounds access by
307 * performing run-time bound checks. However, unlike Rust's slices, Span
308 * cannot provide safety against use-after-free.
310 * (Note: Span is like Rust's slice only conceptually. Due to the lack of
311 * ABI guarantees, you should still decompose spans/slices to raw pointer
312 * and length parts when crossing the FFI. The Elements() and data() methods
313 * are guaranteed to return a non-null pointer even for zero-length spans,
314 * so the pointer can be used as a raw part of a Rust slice without further
317 * In addition to having constructors (with the support of deduction guides)
318 * that take various well-known types, a Span for an arbitrary type can be
319 * constructed from a pointer and a length or a pointer and another pointer
320 * pointing just past the last element.
322 * A Span<const char> or Span<const char16_t> can be obtained for const char*
323 * or const char16_t pointing to a zero-terminated string using the
324 * MakeStringSpan() function (which treats a nullptr argument equivalently
325 * to the empty string). Corresponding implicit constructor does not exist
326 * in order to avoid accidental construction in cases where const char* or
327 * const char16_t* do not point to a zero-terminated string.
329 * Span has methods that follow the Mozilla naming style and methods that
330 * don't. The methods that follow the Mozilla naming style are meant to be
331 * used directly from Mozilla code. The methods that don't are meant for
332 * integration with C++11 range-based loops and with meta-programming that
333 * expects the same methods that are found on the standard-library
334 * containers. For example, to decompose a Span into its parts in Mozilla
335 * code, use Elements() and Length() (as with nsTArray) instead of data()
336 * and size() (as with std::vector).
338 * The pointer and length wrapped by a Span cannot be changed after a Span has
339 * been created. When new values are required, simply create a new Span. Span
340 * has a method called Subspan() that works analogously to the Substring()
341 * method of XPCOM strings taking a start index and an optional length. As a
342 * Mozilla extension (relative to Microsoft's gsl::span that mozilla::Span is
343 * based on), Span has methods From(start), To(end) and FromTo(start, end)
344 * that correspond to Rust's &slice[start..], &slice[..end] and
345 * &slice[start..end], respectively. (That is, the end index is the index of
346 * the first element not to be included in the new subspan.)
348 * When indicating a Span that's only read from, const goes inside the type
349 * parameter. Don't put const in front of Span. That is:
350 * size_t ReadsFromOneSpanAndWritesToAnother(Span<const uint8_t> aReadFrom,
351 * Span<uint8_t> aWrittenTo);
353 * Any Span<const T> can be viewed as Span<const uint8_t> using the function
354 * AsBytes(). Any Span<T> can be viewed as Span<uint8_t> using the function
357 * Note that iterators from different Span instances are uncomparable, even if
358 * they refer to the same memory. This also applies to any spans derived via
361 template <class ElementType
, size_t Extent
/* = dynamic_extent */>
364 // constants and types
365 using element_type
= ElementType
;
366 using index_type
= size_t;
367 using pointer
= element_type
*;
368 using reference
= element_type
&;
371 span_details::span_iterator
<Span
<ElementType
, Extent
>, false>;
372 using const_iterator
=
373 span_details::span_iterator
<Span
<ElementType
, Extent
>, true>;
374 using reverse_iterator
= std::reverse_iterator
<iterator
>;
375 using const_reverse_iterator
= std::reverse_iterator
<const_iterator
>;
377 constexpr static const index_type extent
= Extent
;
379 // [Span.cons], Span constructors, copy, assignment, and destructor
380 // "Dependent" is needed to make "std::enable_if_t<(Dependent ||
381 // Extent == 0 || Extent == dynamic_extent)>" SFINAE,
383 // "std::enable_if_t<(Extent == 0 || Extent == dynamic_extent)>" is
384 // ill-formed when Extent is neither of the extreme values.
386 * Constructor with no args.
388 template <bool Dependent
= false,
389 class = std::enable_if_t
<(Dependent
|| Extent
== 0 ||
390 Extent
== dynamic_extent
)>>
391 constexpr Span() : storage_(nullptr, span_details::extent_type
<0>()) {}
394 * Constructor for nullptr.
396 constexpr MOZ_IMPLICIT
Span(std::nullptr_t
) : Span() {}
399 * Constructor for pointer and length.
401 constexpr Span(pointer aPtr
, index_type aLength
) : storage_(aPtr
, aLength
) {}
404 * Constructor for start pointer and pointer past end.
406 constexpr Span(pointer aStartPtr
, pointer aEndPtr
)
407 : storage_(aStartPtr
, std::distance(aStartPtr
, aEndPtr
)) {}
410 * Constructor for pair of Span iterators.
412 template <typename OtherElementType
, size_t OtherExtent
, bool IsConst
>
414 span_details::span_iterator
<Span
<OtherElementType
, OtherExtent
>, IsConst
>
416 span_details::span_iterator
<Span
<OtherElementType
, OtherExtent
>, IsConst
>
418 : storage_(aBegin
== aEnd
? nullptr : &*aBegin
, aEnd
- aBegin
) {}
421 * Constructor for C array.
424 constexpr MOZ_IMPLICIT
Span(element_type (&aArr
)[N
])
425 : storage_(&aArr
[0], span_details::extent_type
<N
>()) {}
427 // Implicit constructors for char* and char16_t* pointers are deleted in order
428 // to avoid accidental construction in cases where a pointer does not point to
429 // a zero-terminated string. A Span<const char> or Span<const char16_t> can be
430 // obtained for const char* or const char16_t pointing to a zero-terminated
431 // string using the MakeStringSpan() function.
432 // (This must be a template because otherwise it will prevent the previous
433 // array constructor to match because an array decays to a pointer. This only
434 // exists to point to the above explanation, since there's no other
435 // constructor that would match.)
438 typename
= std::enable_if_t
<
439 std::is_pointer_v
<T
> &&
440 (std::is_same_v
<std::remove_const_t
<std::decay_t
<T
>>, char> ||
441 std::is_same_v
<std::remove_const_t
<std::decay_t
<T
>>, char16_t
>)>>
442 Span(T
& aStr
) = delete;
445 * Constructor for std::array.
448 class ArrayElementType
= std::remove_const_t
<element_type
>>
449 constexpr MOZ_IMPLICIT
Span(std::array
<ArrayElementType
, N
>& aArr
)
450 : storage_(&aArr
[0], span_details::extent_type
<N
>()) {}
453 * Constructor for const std::array.
456 constexpr MOZ_IMPLICIT
Span(
457 const std::array
<std::remove_const_t
<element_type
>, N
>& aArr
)
458 : storage_(&aArr
[0], span_details::extent_type
<N
>()) {}
461 * Constructor for mozilla::Array.
464 class ArrayElementType
= std::remove_const_t
<element_type
>>
465 constexpr MOZ_IMPLICIT
Span(mozilla::Array
<ArrayElementType
, N
>& aArr
)
466 : storage_(&aArr
[0], span_details::extent_type
<N
>()) {}
469 * Constructor for const mozilla::Array.
472 constexpr MOZ_IMPLICIT
Span(
473 const mozilla::Array
<std::remove_const_t
<element_type
>, N
>& aArr
)
474 : storage_(&aArr
[0], span_details::extent_type
<N
>()) {}
477 * Constructor for mozilla::UniquePtr holding an array and length.
479 template <class ArrayElementType
= std::add_pointer
<element_type
>>
480 constexpr Span(const mozilla::UniquePtr
<ArrayElementType
>& aPtr
,
482 : storage_(aPtr
.get(), aLength
) {}
484 // NB: the SFINAE here uses .data() as a incomplete/imperfect proxy for the
485 // requirement on Container to be a contiguous sequence container.
487 * Constructor for standard-library containers.
491 class Dummy
= std::enable_if_t
<
492 !std::is_const_v
<Container
> &&
493 !span_details::is_span
<Container
>::value
&&
494 !span_details::is_std_array
<Container
>::value
&&
495 std::is_convertible_v
<typename
Container::pointer
, pointer
> &&
496 std::is_convertible_v
<typename
Container::pointer
,
497 decltype(std::declval
<Container
>().data())>,
499 constexpr MOZ_IMPLICIT
Span(Container
& cont
, Dummy
* = nullptr)
500 : Span(cont
.data(), ReleaseAssertedCast
<index_type
>(cont
.size())) {}
503 * Constructor for standard-library containers (const version).
507 class = std::enable_if_t
<
508 std::is_const_v
<element_type
> &&
509 !span_details::is_span
<Container
>::value
&&
510 std::is_convertible_v
<typename
Container::pointer
, pointer
> &&
511 std::is_convertible_v
<typename
Container::pointer
,
512 decltype(std::declval
<Container
>().data())>>>
513 constexpr MOZ_IMPLICIT
Span(const Container
& cont
)
514 : Span(cont
.data(), ReleaseAssertedCast
<index_type
>(cont
.size())) {}
516 // NB: the SFINAE here uses .Elements() as a incomplete/imperfect proxy for
517 // the requirement on Container to be a contiguous sequence container.
519 * Constructor for contiguous Mozilla containers.
523 class = std::enable_if_t
<
524 !std::is_const_v
<Container
> &&
525 !span_details::is_span
<Container
>::value
&&
526 !span_details::is_std_array
<Container
>::value
&&
527 std::is_convertible_v
<typename
Container::elem_type
*, pointer
> &&
528 std::is_convertible_v
<
529 typename
Container::elem_type
*,
530 decltype(std::declval
<Container
>().Elements())>>>
531 constexpr MOZ_IMPLICIT
Span(Container
& cont
, void* = nullptr)
532 : Span(cont
.Elements(), ReleaseAssertedCast
<index_type
>(cont
.Length())) {}
535 * Constructor for contiguous Mozilla containers (const version).
539 class = std::enable_if_t
<
540 std::is_const_v
<element_type
> &&
541 !span_details::is_span
<Container
>::value
&&
542 std::is_convertible_v
<typename
Container::elem_type
*, pointer
> &&
543 std::is_convertible_v
<
544 typename
Container::elem_type
*,
545 decltype(std::declval
<Container
>().Elements())>>>
546 constexpr MOZ_IMPLICIT
Span(const Container
& cont
, void* = nullptr)
547 : Span(cont
.Elements(), ReleaseAssertedCast
<index_type
>(cont
.Length())) {}
550 * Constructor from other Span.
552 constexpr Span(const Span
& other
) = default;
555 * Constructor from other Span.
557 constexpr Span(Span
&& other
) = default;
560 * Constructor from other Span with conversion of element type.
563 class OtherElementType
, size_t OtherExtent
,
564 class = std::enable_if_t
<span_details::is_allowed_extent_conversion
<
565 OtherExtent
, Extent
>::value
&&
566 span_details::is_allowed_element_type_conversion
<
567 OtherElementType
, element_type
>::value
>>
568 constexpr MOZ_IMPLICIT
Span(const Span
<OtherElementType
, OtherExtent
>& other
)
569 : storage_(other
.data(),
570 span_details::extent_type
<OtherExtent
>(other
.size())) {}
573 * Constructor from other Span with conversion of element type.
576 class OtherElementType
, size_t OtherExtent
,
577 class = std::enable_if_t
<span_details::is_allowed_extent_conversion
<
578 OtherExtent
, Extent
>::value
&&
579 span_details::is_allowed_element_type_conversion
<
580 OtherElementType
, element_type
>::value
>>
581 constexpr MOZ_IMPLICIT
Span(Span
<OtherElementType
, OtherExtent
>&& other
)
582 : storage_(other
.data(),
583 span_details::extent_type
<OtherExtent
>(other
.size())) {}
586 constexpr Span
& operator=(const Span
& other
) = default;
588 constexpr Span
& operator=(Span
&& other
) = default;
590 // [Span.sub], Span subviews
592 * Subspan with first N elements with compile-time N.
594 template <size_t Count
>
595 constexpr Span
<element_type
, Count
> First() const {
596 MOZ_RELEASE_ASSERT(Count
<= size());
597 return {data(), Count
};
601 * Subspan with last N elements with compile-time N.
603 template <size_t Count
>
604 constexpr Span
<element_type
, Count
> Last() const {
605 const size_t len
= size();
606 MOZ_RELEASE_ASSERT(Count
<= len
);
607 return {data() + (len
- Count
), Count
};
611 * Subspan with compile-time start index and length.
613 template <size_t Offset
, size_t Count
= dynamic_extent
>
614 constexpr Span
<element_type
, Count
> Subspan() const {
615 const size_t len
= size();
616 MOZ_RELEASE_ASSERT(Offset
<= len
&&
617 (Count
== dynamic_extent
|| (Offset
+ Count
<= len
)));
618 return {data() + Offset
, Count
== dynamic_extent
? len
- Offset
: Count
};
622 * Subspan with first N elements with run-time N.
624 constexpr Span
<element_type
, dynamic_extent
> First(index_type aCount
) const {
625 MOZ_RELEASE_ASSERT(aCount
<= size());
626 return {data(), aCount
};
630 * Subspan with last N elements with run-time N.
632 constexpr Span
<element_type
, dynamic_extent
> Last(index_type aCount
) const {
633 const size_t len
= size();
634 MOZ_RELEASE_ASSERT(aCount
<= len
);
635 return {data() + (len
- aCount
), aCount
};
639 * Subspan with run-time start index and length.
641 constexpr Span
<element_type
, dynamic_extent
> Subspan(
642 index_type aStart
, index_type aLength
= dynamic_extent
) const {
643 const size_t len
= size();
644 MOZ_RELEASE_ASSERT(aStart
<= len
&& (aLength
== dynamic_extent
||
645 (aStart
+ aLength
<= len
)));
646 return {data() + aStart
,
647 aLength
== dynamic_extent
? len
- aStart
: aLength
};
651 * Subspan with run-time start index. (Rust's &foo[start..])
653 constexpr Span
<element_type
, dynamic_extent
> From(index_type aStart
) const {
654 return Subspan(aStart
);
658 * Subspan with run-time exclusive end index. (Rust's &foo[..end])
660 constexpr Span
<element_type
, dynamic_extent
> To(index_type aEnd
) const {
661 return Subspan(0, aEnd
);
665 * Subspan with run-time start index and exclusive end index.
666 * (Rust's &foo[start..end])
668 constexpr Span
<element_type
, dynamic_extent
> FromTo(index_type aStart
,
669 index_type aEnd
) const {
670 MOZ_RELEASE_ASSERT(aStart
<= aEnd
);
671 return Subspan(aStart
, aEnd
- aStart
);
674 // [Span.obs], Span observers
676 * Number of elements in the span.
678 constexpr index_type
Length() const { return size(); }
681 * Number of elements in the span (standard-libray duck typing version).
683 constexpr index_type
size() const { return storage_
.size(); }
686 * Size of the span in bytes.
688 constexpr index_type
LengthBytes() const { return size_bytes(); }
691 * Size of the span in bytes (standard-library naming style version).
693 constexpr index_type
size_bytes() const {
694 return size() * narrow_cast
<index_type
>(sizeof(element_type
));
698 * Checks if the the length of the span is zero.
700 constexpr bool IsEmpty() const { return empty(); }
703 * Checks if the the length of the span is zero (standard-libray duck
706 constexpr bool empty() const { return size() == 0; }
708 // [Span.elem], Span element access
709 constexpr reference
operator[](index_type idx
) const {
710 MOZ_RELEASE_ASSERT(idx
< storage_
.size());
715 * Access element of span by index (standard-library duck typing version).
717 constexpr reference
at(index_type idx
) const { return this->operator[](idx
); }
719 constexpr reference
operator()(index_type idx
) const {
720 return this->operator[](idx
);
724 * Pointer to the first element of the span. The return value is never
725 * nullptr, not ever for zero-length spans, so it can be passed as-is
726 * to std::slice::from_raw_parts() in Rust.
728 constexpr pointer
Elements() const { return data(); }
731 * Pointer to the first element of the span (standard-libray duck typing
732 * version). The return value is never nullptr, not ever for zero-length
733 * spans, so it can be passed as-is to std::slice::from_raw_parts() in Rust.
735 constexpr pointer
data() const { return storage_
.data(); }
737 // [Span.iter], Span iterator support
738 iterator
begin() const { return {this, 0, span_details::SpanKnownBounds
{}}; }
739 iterator
end() const {
740 return {this, Length(), span_details::SpanKnownBounds
{}};
743 const_iterator
cbegin() const {
744 return {this, 0, span_details::SpanKnownBounds
{}};
746 const_iterator
cend() const {
747 return {this, Length(), span_details::SpanKnownBounds
{}};
750 reverse_iterator
rbegin() const { return reverse_iterator
{end()}; }
751 reverse_iterator
rend() const { return reverse_iterator
{begin()}; }
753 const_reverse_iterator
crbegin() const {
754 return const_reverse_iterator
{cend()};
756 const_reverse_iterator
crend() const {
757 return const_reverse_iterator
{cbegin()};
760 template <size_t SplitPoint
>
761 constexpr std::pair
<Span
<ElementType
, SplitPoint
>,
762 Span
<ElementType
, Extent
- SplitPoint
>>
764 static_assert(Extent
!= dynamic_extent
);
765 static_assert(SplitPoint
<= Extent
);
766 return {First
<SplitPoint
>(), Last
<Extent
- SplitPoint
>()};
769 constexpr std::pair
<Span
<ElementType
, dynamic_extent
>,
770 Span
<ElementType
, dynamic_extent
>>
771 SplitAt(const index_type aSplitPoint
) const {
772 MOZ_RELEASE_ASSERT(aSplitPoint
<= Length());
773 return {First(aSplitPoint
), Last(Length() - aSplitPoint
)};
776 constexpr Span
<std::add_const_t
<ElementType
>, Extent
> AsConst() const {
777 return {Elements(), Length()};
781 // this implementation detail class lets us take advantage of the
782 // empty base class optimization to pay for only storage of a single
783 // pointer in the case of fixed-size Spans
784 template <class ExtentType
>
785 class storage_type
: public ExtentType
{
787 template <class OtherExtentType
>
788 constexpr storage_type(pointer elements
, OtherExtentType ext
)
790 // Replace nullptr with aligned bogus pointer for Rust slice
791 // compatibility. See
792 // https://doc.rust-lang.org/std/slice/fn.from_raw_parts.html
794 data_(elements
? elements
795 : reinterpret_cast<pointer
>(alignof(element_type
))) {
796 const size_t extentSize
= ExtentType::size();
797 MOZ_RELEASE_ASSERT((!elements
&& extentSize
== 0) ||
798 (elements
&& extentSize
!= dynamic_extent
));
801 constexpr pointer
data() const { return data_
; }
807 storage_type
<span_details::extent_type
<Extent
>> storage_
;
810 template <typename T
, size_t OtherExtent
, bool IsConst
>
811 Span(span_details::span_iterator
<Span
<T
, OtherExtent
>, IsConst
> aBegin
,
812 span_details::span_iterator
<Span
<T
, OtherExtent
>, IsConst
> aEnd
)
813 -> Span
<std::conditional_t
<IsConst
, std::add_const_t
<T
>, T
>>;
815 template <typename T
, size_t Extent
>
816 Span(T (&)[Extent
]) -> Span
<T
, Extent
>;
818 template <class Container
>
819 Span(Container
&) -> Span
<typename
Container::value_type
>;
821 template <class Container
>
822 Span(const Container
&) -> Span
<const typename
Container::value_type
>;
824 template <typename T
, size_t Extent
>
825 Span(mozilla::Array
<T
, Extent
>&) -> Span
<T
, Extent
>;
827 template <typename T
, size_t Extent
>
828 Span(const mozilla::Array
<T
, Extent
>&) -> Span
<const T
, Extent
>;
830 // [Span.comparison], Span comparison operators
831 template <class ElementType
, size_t FirstExtent
, size_t SecondExtent
>
832 inline constexpr bool operator==(const Span
<ElementType
, FirstExtent
>& l
,
833 const Span
<ElementType
, SecondExtent
>& r
) {
834 return (l
.size() == r
.size()) &&
835 std::equal(l
.data(), l
.data() + l
.size(), r
.data());
838 template <class ElementType
, size_t Extent
>
839 inline constexpr bool operator!=(const Span
<ElementType
, Extent
>& l
,
840 const Span
<ElementType
, Extent
>& r
) {
844 template <class ElementType
, size_t Extent
>
845 inline constexpr bool operator<(const Span
<ElementType
, Extent
>& l
,
846 const Span
<ElementType
, Extent
>& r
) {
847 return std::lexicographical_compare(l
.data(), l
.data() + l
.size(), r
.data(),
848 r
.data() + r
.size());
851 template <class ElementType
, size_t Extent
>
852 inline constexpr bool operator<=(const Span
<ElementType
, Extent
>& l
,
853 const Span
<ElementType
, Extent
>& r
) {
857 template <class ElementType
, size_t Extent
>
858 inline constexpr bool operator>(const Span
<ElementType
, Extent
>& l
,
859 const Span
<ElementType
, Extent
>& r
) {
863 template <class ElementType
, size_t Extent
>
864 inline constexpr bool operator>=(const Span
<ElementType
, Extent
>& l
,
865 const Span
<ElementType
, Extent
>& r
) {
869 namespace span_details
{
870 // if we only supported compilers with good constexpr support then
871 // this pair of classes could collapse down to a constexpr function
873 // we should use a narrow_cast<> to go to size_t, but older compilers may not
874 // see it as constexpr and so will fail compilation of the template
875 template <class ElementType
, size_t Extent
>
876 struct calculate_byte_size
877 : std::integral_constant
<size_t,
878 static_cast<size_t>(sizeof(ElementType
) *
879 static_cast<size_t>(Extent
))> {
882 template <class ElementType
>
883 struct calculate_byte_size
<ElementType
, dynamic_extent
>
884 : std::integral_constant
<size_t, dynamic_extent
> {};
885 } // namespace span_details
887 // [Span.objectrep], views of object representation
889 * View span as Span<const uint8_t>.
891 template <class ElementType
, size_t Extent
>
893 span_details::calculate_byte_size
<ElementType
, Extent
>::value
>
894 AsBytes(Span
<ElementType
, Extent
> s
) {
895 return {reinterpret_cast<const uint8_t*>(s
.data()), s
.size_bytes()};
899 * View span as Span<uint8_t>.
901 template <class ElementType
, size_t Extent
,
902 class = std::enable_if_t
<!std::is_const_v
<ElementType
>>>
903 Span
<uint8_t, span_details::calculate_byte_size
<ElementType
, Extent
>::value
>
904 AsWritableBytes(Span
<ElementType
, Extent
> s
) {
905 return {reinterpret_cast<uint8_t*>(s
.data()), s
.size_bytes()};
909 * View a span of uint8_t as a span of char.
911 inline Span
<const char> AsChars(Span
<const uint8_t> s
) {
912 return {reinterpret_cast<const char*>(s
.data()), s
.size()};
916 * View a writable span of uint8_t as a span of char.
918 inline Span
<char> AsWritableChars(Span
<uint8_t> s
) {
919 return {reinterpret_cast<char*>(s
.data()), s
.size()};
923 * Create span from a zero-terminated C string. nullptr is
924 * treated as the empty string.
926 constexpr Span
<const char> MakeStringSpan(const char* aZeroTerminated
) {
927 if (!aZeroTerminated
) {
928 return Span
<const char>();
930 return Span
<const char>(aZeroTerminated
,
931 std::char_traits
<char>::length(aZeroTerminated
));
935 * Create span from a zero-terminated UTF-16 C string. nullptr is
936 * treated as the empty string.
938 constexpr Span
<const char16_t
> MakeStringSpan(const char16_t
* aZeroTerminated
) {
939 if (!aZeroTerminated
) {
940 return Span
<const char16_t
>();
942 return Span
<const char16_t
>(
943 aZeroTerminated
, std::char_traits
<char16_t
>::length(aZeroTerminated
));
946 } // namespace mozilla
948 #endif // mozilla_Span_h