Source code

Revision control

Other Tools

1
///////////////////////////////////////////////////////////////////////////////
2
//
3
// Copyright (c) 2015 Microsoft Corporation. All rights reserved.
4
//
5
// This code is licensed under the MIT License (MIT).
6
//
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
13
// THE SOFTWARE.
14
//
15
///////////////////////////////////////////////////////////////////////////////
16
17
// Adapted from
19
// and
21
22
#ifndef mozilla_Span_h
23
#define mozilla_Span_h
24
25
#include <algorithm>
26
#include <array>
27
#include <cstring>
28
#include <iterator>
29
#include <limits>
30
#include <utility>
31
32
#include "mozilla/Array.h"
33
#include "mozilla/Assertions.h"
34
#include "mozilla/Casting.h"
35
#include "mozilla/IntegerTypeTraits.h"
36
#include "mozilla/TypeTraits.h"
37
#include "mozilla/UniquePtr.h"
38
39
namespace mozilla {
40
41
// Stuff from gsl_util
42
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));
47
}
48
49
// end gsl_util
50
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();
57
58
template <class ElementType, size_t Extent = dynamic_extent>
59
class Span;
60
61
// implementation details
62
namespace span_details {
63
64
inline size_t strlen16(const char16_t* aZeroTerminated) {
65
size_t len = 0;
66
while (*(aZeroTerminated++)) {
67
len++;
68
}
69
return len;
70
}
71
72
// C++14 types that we don't have because we build as C++11.
73
template <class T>
74
using remove_cv_t = typename mozilla::RemoveCV<T>::Type;
75
template <class T>
76
using remove_const_t = typename mozilla::RemoveConst<T>::Type;
77
template <bool B, class T, class F>
78
using conditional_t = typename mozilla::Conditional<B, T, F>::Type;
79
template <class T>
80
using add_pointer_t = typename mozilla::AddPointer<T>::Type;
81
template <bool B, class T = void>
82
using enable_if_t = typename mozilla::EnableIf<B, T>::Type;
83
84
template <class T>
85
struct is_span_oracle : mozilla::FalseType {};
86
87
template <class ElementType, size_t Extent>
88
struct is_span_oracle<mozilla::Span<ElementType, Extent>> : mozilla::TrueType {
89
};
90
91
template <class T>
92
struct is_span : public is_span_oracle<remove_cv_t<T>> {};
93
94
template <class T>
95
struct is_std_array_oracle : mozilla::FalseType {};
96
97
template <class ElementType, size_t Extent>
98
struct is_std_array_oracle<std::array<ElementType, Extent>>
99
: mozilla::TrueType {};
100
101
template <class T>
102
struct is_std_array : public is_std_array_oracle<remove_cv_t<T>> {};
103
104
template <size_t From, size_t To>
105
struct is_allowed_extent_conversion
106
: public mozilla::IntegralConstant<
107
bool, From == To || From == mozilla::dynamic_extent ||
108
To == mozilla::dynamic_extent> {};
109
110
template <class From, class To>
111
struct is_allowed_element_type_conversion
112
: public mozilla::IntegralConstant<
113
bool, mozilla::IsConvertible<From (*)[], To (*)[]>::value> {};
114
115
template <class Span, bool IsConst>
116
class span_iterator {
117
using element_type_ = typename Span::element_type;
118
119
public:
120
using iterator_category = std::random_access_iterator_tag;
121
using value_type = remove_const_t<element_type_>;
122
using difference_type = typename Span::index_type;
123
124
using reference = conditional_t<IsConst, const element_type_, element_type_>&;
125
using pointer = add_pointer_t<reference>;
126
127
constexpr span_iterator() : span_iterator(nullptr, 0) {}
128
129
constexpr span_iterator(const Span* span, typename Span::index_type index)
130
: span_(span), index_(index) {
131
MOZ_RELEASE_ASSERT(span == nullptr ||
132
(index_ >= 0 && index <= span_->Length()));
133
}
134
135
friend class span_iterator<Span, true>;
136
constexpr MOZ_IMPLICIT span_iterator(const span_iterator<Span, false>& other)
137
: span_iterator(other.span_, other.index_) {}
138
139
constexpr span_iterator<Span, IsConst>& operator=(
140
const span_iterator<Span, IsConst>&) = default;
141
142
constexpr reference operator*() const {
143
MOZ_RELEASE_ASSERT(span_);
144
return (*span_)[index_];
145
}
146
147
constexpr pointer operator->() const {
148
MOZ_RELEASE_ASSERT(span_);
149
return &((*span_)[index_]);
150
}
151
152
constexpr span_iterator& operator++() {
153
MOZ_RELEASE_ASSERT(span_ && index_ >= 0 && index_ < span_->Length());
154
++index_;
155
return *this;
156
}
157
158
constexpr span_iterator operator++(int) {
159
auto ret = *this;
160
++(*this);
161
return ret;
162
}
163
164
constexpr span_iterator& operator--() {
165
MOZ_RELEASE_ASSERT(span_ && index_ > 0 && index_ <= span_->Length());
166
--index_;
167
return *this;
168
}
169
170
constexpr span_iterator operator--(int) {
171
auto ret = *this;
172
--(*this);
173
return ret;
174
}
175
176
constexpr span_iterator operator+(difference_type n) const {
177
auto ret = *this;
178
return ret += n;
179
}
180
181
constexpr span_iterator& operator+=(difference_type n) {
182
MOZ_RELEASE_ASSERT(span_ && (index_ + n) >= 0 &&
183
(index_ + n) <= span_->Length());
184
index_ += n;
185
return *this;
186
}
187
188
constexpr span_iterator operator-(difference_type n) const {
189
auto ret = *this;
190
return ret -= n;
191
}
192
193
constexpr span_iterator& operator-=(difference_type n)
194
195
{
196
return *this += -n;
197
}
198
199
constexpr difference_type operator-(const span_iterator& rhs) const {
200
MOZ_RELEASE_ASSERT(span_ == rhs.span_);
201
return index_ - rhs.index_;
202
}
203
204
constexpr reference operator[](difference_type n) const {
205
return *(*this + n);
206
}
207
208
constexpr friend bool operator==(const span_iterator& lhs,
209
const span_iterator& rhs) {
210
return lhs.span_ == rhs.span_ && lhs.index_ == rhs.index_;
211
}
212
213
constexpr friend bool operator!=(const span_iterator& lhs,
214
const span_iterator& rhs) {
215
return !(lhs == rhs);
216
}
217
218
constexpr friend bool operator<(const span_iterator& lhs,
219
const span_iterator& rhs) {
220
MOZ_RELEASE_ASSERT(lhs.span_ == rhs.span_);
221
return lhs.index_ < rhs.index_;
222
}
223
224
constexpr friend bool operator<=(const span_iterator& lhs,
225
const span_iterator& rhs) {
226
return !(rhs < lhs);
227
}
228
229
constexpr friend bool operator>(const span_iterator& lhs,
230
const span_iterator& rhs) {
231
return rhs < lhs;
232
}
233
234
constexpr friend bool operator>=(const span_iterator& lhs,
235
const span_iterator& rhs) {
236
return !(rhs > lhs);
237
}
238
239
void swap(span_iterator& rhs) {
240
std::swap(index_, rhs.index_);
241
std::swap(span_, rhs.span_);
242
}
243
244
protected:
245
const Span* span_;
246
size_t index_;
247
};
248
249
template <class Span, bool IsConst>
250
inline constexpr span_iterator<Span, IsConst> operator+(
251
typename span_iterator<Span, IsConst>::difference_type n,
252
const span_iterator<Span, IsConst>& rhs) {
253
return rhs + n;
254
}
255
256
template <size_t Ext>
257
class extent_type {
258
public:
259
using index_type = size_t;
260
261
static_assert(Ext >= 0, "A fixed-size Span must be >= 0 in size.");
262
263
constexpr extent_type() {}
264
265
template <index_type Other>
266
constexpr MOZ_IMPLICIT extent_type(extent_type<Other> ext) {
267
static_assert(
268
Other == Ext || Other == dynamic_extent,
269
"Mismatch between fixed-size extent and size of initializing data.");
270
MOZ_RELEASE_ASSERT(ext.size() == Ext);
271
}
272
273
constexpr MOZ_IMPLICIT extent_type(index_type length) {
274
MOZ_RELEASE_ASSERT(length == Ext);
275
}
276
277
constexpr index_type size() const { return Ext; }
278
};
279
280
template <>
281
class extent_type<dynamic_extent> {
282
public:
283
using index_type = size_t;
284
285
template <index_type Other>
286
explicit constexpr extent_type(extent_type<Other> ext) : size_(ext.size()) {}
287
288
explicit constexpr extent_type(index_type length) : size_(length) {}
289
290
constexpr index_type size() const { return size_; }
291
292
private:
293
index_type size_;
294
};
295
} // namespace span_details
296
297
/**
298
* Span - slices for C++
299
*
300
* Span implements Rust's slice concept for C++. It's called "Span" instead of
301
* "Slice" to follow the naming used in C++ Core Guidelines.
302
*
303
* A Span wraps a pointer and a length that identify a non-owning view to a
304
* contiguous block of memory of objects of the same type. Various types,
305
* including (pre-decay) C arrays, XPCOM strings, nsTArray, mozilla::Array,
306
* mozilla::Range and contiguous standard-library containers, auto-convert
307
* into Spans when attempting to pass them as arguments to methods that take
308
* Spans. MakeSpan() functions can be used for explicit conversion in other
309
* contexts. (Span itself autoconverts into mozilla::Range.)
310
*
311
* Like Rust's slices, Span provides safety against out-of-bounds access by
312
* performing run-time bound checks. However, unlike Rust's slices, Span
313
* cannot provide safety against use-after-free.
314
*
315
* (Note: Span is like Rust's slice only conceptually. Due to the lack of
316
* ABI guarantees, you should still decompose spans/slices to raw pointer
317
* and length parts when crossing the FFI. The Elements() and data() methods
318
* are guaranteed to return a non-null pointer even for zero-length spans,
319
* so the pointer can be used as a raw part of a Rust slice without further
320
* checks.)
321
*
322
* In addition to having constructors and MakeSpan() functions that take
323
* various well-known types, a Span for an arbitrary type can be constructed
324
* (via constructor or MakeSpan()) from a pointer and a length or a pointer
325
* and another pointer pointing just past the last element.
326
*
327
* A Span<const char> or Span<const char16_t> can be obtained for const char*
328
* or const char16_t pointing to a zero-terminated string using the
329
* MakeStringSpan() function (which treats a nullptr argument equivalently
330
* to the empty string). Corresponding implicit constructor does not exist
331
* in order to avoid accidental construction in cases where const char* or
332
* const char16_t* do not point to a zero-terminated string.
333
*
334
* Span has methods that follow the Mozilla naming style and methods that
335
* don't. The methods that follow the Mozilla naming style are meant to be
336
* used directly from Mozilla code. The methods that don't are meant for
337
* integration with C++11 range-based loops and with meta-programming that
338
* expects the same methods that are found on the standard-library
339
* containers. For example, to decompose a Span into its parts in Mozilla
340
* code, use Elements() and Length() (as with nsTArray) instead of data()
341
* and size() (as with std::vector).
342
*
343
* The pointer and length wrapped by a Span cannot be changed after a Span has
344
* been created. When new values are required, simply create a new Span. Span
345
* has a method called Subspan() that works analogously to the Substring()
346
* method of XPCOM strings taking a start index and an optional length. As a
347
* Mozilla extension (relative to Microsoft's gsl::span that mozilla::Span is
348
* based on), Span has methods From(start), To(end) and FromTo(start, end)
349
* that correspond to Rust's &slice[start..], &slice[..end] and
350
* &slice[start..end], respectively. (That is, the end index is the index of
351
* the first element not to be included in the new subspan.)
352
*
353
* When indicating a Span that's only read from, const goes inside the type
354
* parameter. Don't put const in front of Span. That is:
355
* size_t ReadsFromOneSpanAndWritesToAnother(Span<const uint8_t> aReadFrom,
356
* Span<uint8_t> aWrittenTo);
357
*
358
* Any Span<const T> can be viewed as Span<const uint8_t> using the function
359
* AsBytes(). Any Span<T> can be viewed as Span<uint8_t> using the function
360
* AsWritableBytes().
361
*/
362
template <class ElementType, size_t Extent /* = dynamic_extent */>
363
class Span {
364
public:
365
// constants and types
366
using element_type = ElementType;
367
using index_type = size_t;
368
using pointer = element_type*;
369
using reference = element_type&;
370
371
using iterator =
372
span_details::span_iterator<Span<ElementType, Extent>, false>;
373
using const_iterator =
374
span_details::span_iterator<Span<ElementType, Extent>, true>;
375
using reverse_iterator = std::reverse_iterator<iterator>;
376
using const_reverse_iterator = std::reverse_iterator<const_iterator>;
377
378
constexpr static const index_type extent = Extent;
379
380
// [Span.cons], Span constructors, copy, assignment, and destructor
381
// "Dependent" is needed to make "span_details::enable_if_t<(Dependent ||
382
// Extent == 0 || Extent == dynamic_extent)>" SFINAE,
383
// since
384
// "span_details::enable_if_t<(Extent == 0 || Extent == dynamic_extent)>" is
385
// ill-formed when Extent is neither of the extreme values.
386
/**
387
* Constructor with no args.
388
*/
389
template <bool Dependent = false,
390
class = span_details::enable_if_t<(Dependent || Extent == 0 ||
391
Extent == dynamic_extent)>>
392
constexpr Span() : storage_(nullptr, span_details::extent_type<0>()) {}
393
394
/**
395
* Constructor for nullptr.
396
*/
397
constexpr MOZ_IMPLICIT Span(std::nullptr_t) : Span() {}
398
399
/**
400
* Constructor for pointer and length.
401
*/
402
constexpr Span(pointer aPtr, index_type aLength) : storage_(aPtr, aLength) {}
403
404
/**
405
* Constructor for start pointer and pointer past end.
406
*/
407
constexpr Span(pointer aStartPtr, pointer aEndPtr)
408
: storage_(aStartPtr, std::distance(aStartPtr, aEndPtr)) {}
409
410
/**
411
* Constructor for C array.
412
*/
413
template <size_t N>
414
constexpr MOZ_IMPLICIT Span(element_type (&aArr)[N])
415
: storage_(&aArr[0], span_details::extent_type<N>()) {}
416
417
// Implicit constructors for char* and char16_t* pointers are deleted in order
418
// to avoid accidental construction in cases where a pointer does not point to
419
// a zero-terminated string. A Span<const char> or Span<const char16_t> can be
420
// obtained for const char* or const char16_t pointing to a zero-terminated
421
// string using the MakeStringSpan() function.
422
Span(char* aStr) = delete;
423
Span(const char* aStr) = delete;
424
Span(char16_t* aStr) = delete;
425
Span(const char16_t* aStr) = delete;
426
427
/**
428
* Constructor for std::array.
429
*/
430
template <size_t N,
431
class ArrayElementType = span_details::remove_const_t<element_type>>
432
constexpr MOZ_IMPLICIT Span(std::array<ArrayElementType, N>& aArr)
433
: storage_(&aArr[0], span_details::extent_type<N>()) {}
434
435
/**
436
* Constructor for const std::array.
437
*/
438
template <size_t N>
439
constexpr MOZ_IMPLICIT Span(
440
const std::array<span_details::remove_const_t<element_type>, N>& aArr)
441
: storage_(&aArr[0], span_details::extent_type<N>()) {}
442
443
/**
444
* Constructor for mozilla::Array.
445
*/
446
template <size_t N,
447
class ArrayElementType = span_details::remove_const_t<element_type>>
448
constexpr MOZ_IMPLICIT Span(mozilla::Array<ArrayElementType, N>& aArr)
449
: storage_(&aArr[0], span_details::extent_type<N>()) {}
450
451
/**
452
* Constructor for const mozilla::Array.
453
*/
454
template <size_t N>
455
constexpr MOZ_IMPLICIT Span(
456
const mozilla::Array<span_details::remove_const_t<element_type>, N>& aArr)
457
: storage_(&aArr[0], span_details::extent_type<N>()) {}
458
459
/**
460
* Constructor for mozilla::UniquePtr holding an array and length.
461
*/
462
template <class ArrayElementType = std::add_pointer<element_type>>
463
constexpr Span(const mozilla::UniquePtr<ArrayElementType>& aPtr,
464
index_type aLength)
465
: storage_(aPtr.get(), aLength) {}
466
467
// NB: the SFINAE here uses .data() as a incomplete/imperfect proxy for the
468
// requirement on Container to be a contiguous sequence container.
469
/**
470
* Constructor for standard-library containers.
471
*/
472
template <
473
class Container,
474
class = span_details::enable_if_t<
475
!span_details::is_span<Container>::value &&
476
!span_details::is_std_array<Container>::value &&
477
mozilla::IsConvertible<typename Container::pointer, pointer>::value &&
478
mozilla::IsConvertible<
479
typename Container::pointer,
480
decltype(mozilla::DeclVal<Container>().data())>::value>>
481
constexpr MOZ_IMPLICIT Span(Container& cont)
482
: Span(cont.data(), ReleaseAssertedCast<index_type>(cont.size())) {}
483
484
/**
485
* Constructor for standard-library containers (const version).
486
*/
487
template <
488
class Container,
489
class = span_details::enable_if_t<
490
mozilla::IsConst<element_type>::value &&
491
!span_details::is_span<Container>::value &&
492
mozilla::IsConvertible<typename Container::pointer, pointer>::value &&
493
mozilla::IsConvertible<
494
typename Container::pointer,
495
decltype(mozilla::DeclVal<Container>().data())>::value>>
496
constexpr MOZ_IMPLICIT Span(const Container& cont)
497
: Span(cont.data(), ReleaseAssertedCast<index_type>(cont.size())) {}
498
499
/**
500
* Constructor from other Span.
501
*/
502
constexpr Span(const Span& other) = default;
503
504
/**
505
* Constructor from other Span.
506
*/
507
constexpr Span(Span&& other) = default;
508
509
/**
510
* Constructor from other Span with conversion of element type.
511
*/
512
template <class OtherElementType, size_t OtherExtent,
513
class = span_details::enable_if_t<
514
span_details::is_allowed_extent_conversion<OtherExtent,
515
Extent>::value &&
516
span_details::is_allowed_element_type_conversion<
517
OtherElementType, element_type>::value>>
518
constexpr MOZ_IMPLICIT Span(const Span<OtherElementType, OtherExtent>& other)
519
: storage_(other.data(),
520
span_details::extent_type<OtherExtent>(other.size())) {}
521
522
/**
523
* Constructor from other Span with conversion of element type.
524
*/
525
template <class OtherElementType, size_t OtherExtent,
526
class = span_details::enable_if_t<
527
span_details::is_allowed_extent_conversion<OtherExtent,
528
Extent>::value &&
529
span_details::is_allowed_element_type_conversion<
530
OtherElementType, element_type>::value>>
531
constexpr MOZ_IMPLICIT Span(Span<OtherElementType, OtherExtent>&& other)
532
: storage_(other.data(),
533
span_details::extent_type<OtherExtent>(other.size())) {}
534
535
~Span() = default;
536
constexpr Span& operator=(const Span& other) = default;
537
538
constexpr Span& operator=(Span&& other) = default;
539
540
// [Span.sub], Span subviews
541
/**
542
* Subspan with first N elements with compile-time N.
543
*/
544
template <size_t Count>
545
constexpr Span<element_type, Count> First() const {
546
MOZ_RELEASE_ASSERT(Count <= size());
547
return {data(), Count};
548
}
549
550
/**
551
* Subspan with last N elements with compile-time N.
552
*/
553
template <size_t Count>
554
constexpr Span<element_type, Count> Last() const {
555
const size_t len = size();
556
MOZ_RELEASE_ASSERT(Count <= len);
557
return {data() + (len - Count), Count};
558
}
559
560
/**
561
* Subspan with compile-time start index and length.
562
*/
563
template <size_t Offset, size_t Count = dynamic_extent>
564
constexpr Span<element_type, Count> Subspan() const {
565
const size_t len = size();
566
MOZ_RELEASE_ASSERT(Offset <= len &&
567
(Count == dynamic_extent || (Offset + Count <= len)));
568
return {data() + Offset, Count == dynamic_extent ? len - Offset : Count};
569
}
570
571
/**
572
* Subspan with first N elements with run-time N.
573
*/
574
constexpr Span<element_type, dynamic_extent> First(index_type aCount) const {
575
MOZ_RELEASE_ASSERT(aCount <= size());
576
return {data(), aCount};
577
}
578
579
/**
580
* Subspan with last N elements with run-time N.
581
*/
582
constexpr Span<element_type, dynamic_extent> Last(index_type aCount) const {
583
const size_t len = size();
584
MOZ_RELEASE_ASSERT(aCount <= len);
585
return {data() + (len - aCount), aCount};
586
}
587
588
/**
589
* Subspan with run-time start index and length.
590
*/
591
constexpr Span<element_type, dynamic_extent> Subspan(
592
index_type aStart, index_type aLength = dynamic_extent) const {
593
const size_t len = size();
594
MOZ_RELEASE_ASSERT(aStart <= len && (aLength == dynamic_extent ||
595
(aStart + aLength <= len)));
596
return {data() + aStart,
597
aLength == dynamic_extent ? len - aStart : aLength};
598
}
599
600
/**
601
* Subspan with run-time start index. (Rust's &foo[start..])
602
*/
603
constexpr Span<element_type, dynamic_extent> From(index_type aStart) const {
604
return Subspan(aStart);
605
}
606
607
/**
608
* Subspan with run-time exclusive end index. (Rust's &foo[..end])
609
*/
610
constexpr Span<element_type, dynamic_extent> To(index_type aEnd) const {
611
return Subspan(0, aEnd);
612
}
613
614
/**
615
* Subspan with run-time start index and exclusive end index.
616
* (Rust's &foo[start..end])
617
*/
618
constexpr Span<element_type, dynamic_extent> FromTo(index_type aStart,
619
index_type aEnd) const {
620
MOZ_RELEASE_ASSERT(aStart <= aEnd);
621
return Subspan(aStart, aEnd - aStart);
622
}
623
624
// [Span.obs], Span observers
625
/**
626
* Number of elements in the span.
627
*/
628
constexpr index_type Length() const { return size(); }
629
630
/**
631
* Number of elements in the span (standard-libray duck typing version).
632
*/
633
constexpr index_type size() const { return storage_.size(); }
634
635
/**
636
* Size of the span in bytes.
637
*/
638
constexpr index_type LengthBytes() const { return size_bytes(); }
639
640
/**
641
* Size of the span in bytes (standard-library naming style version).
642
*/
643
constexpr index_type size_bytes() const {
644
return size() * narrow_cast<index_type>(sizeof(element_type));
645
}
646
647
/**
648
* Checks if the the length of the span is zero.
649
*/
650
constexpr bool IsEmpty() const { return empty(); }
651
652
/**
653
* Checks if the the length of the span is zero (standard-libray duck
654
* typing version).
655
*/
656
constexpr bool empty() const { return size() == 0; }
657
658
// [Span.elem], Span element access
659
constexpr reference operator[](index_type idx) const {
660
MOZ_RELEASE_ASSERT(idx < storage_.size());
661
return data()[idx];
662
}
663
664
/**
665
* Access element of span by index (standard-library duck typing version).
666
*/
667
constexpr reference at(index_type idx) const { return this->operator[](idx); }
668
669
constexpr reference operator()(index_type idx) const {
670
return this->operator[](idx);
671
}
672
673
/**
674
* Pointer to the first element of the span. The return value is never
675
* nullptr, not ever for zero-length spans, so it can be passed as-is
676
* to std::slice::from_raw_parts() in Rust.
677
*/
678
constexpr pointer Elements() const { return data(); }
679
680
/**
681
* Pointer to the first element of the span (standard-libray duck typing
682
* version). The return value is never nullptr, not ever for zero-length
683
* spans, so it can be passed as-is to std::slice::from_raw_parts() in Rust.
684
*/
685
constexpr pointer data() const { return storage_.data(); }
686
687
// [Span.iter], Span iterator support
688
iterator begin() const { return {this, 0}; }
689
iterator end() const { return {this, Length()}; }
690
691
const_iterator cbegin() const { return {this, 0}; }
692
const_iterator cend() const { return {this, Length()}; }
693
694
reverse_iterator rbegin() const { return reverse_iterator{end()}; }
695
reverse_iterator rend() const { return reverse_iterator{begin()}; }
696
697
const_reverse_iterator crbegin() const {
698
return const_reverse_iterator{cend()};
699
}
700
const_reverse_iterator crend() const {
701
return const_reverse_iterator{cbegin()};
702
}
703
704
private:
705
// this implementation detail class lets us take advantage of the
706
// empty base class optimization to pay for only storage of a single
707
// pointer in the case of fixed-size Spans
708
template <class ExtentType>
709
class storage_type : public ExtentType {
710
public:
711
template <class OtherExtentType>
712
constexpr storage_type(pointer elements, OtherExtentType ext)
713
: ExtentType(ext)
714
// Replace nullptr with aligned bogus pointer for Rust slice
715
// compatibility. See
717
,
718
data_(elements ? elements
719
: reinterpret_cast<pointer>(alignof(element_type))) {
720
const size_t extentSize = ExtentType::size();
721
MOZ_RELEASE_ASSERT((!elements && extentSize == 0) ||
722
(elements && extentSize != dynamic_extent));
723
}
724
725
constexpr pointer data() const { return data_; }
726
727
private:
728
pointer data_;
729
};
730
731
storage_type<span_details::extent_type<Extent>> storage_;
732
};
733
734
// [Span.comparison], Span comparison operators
735
template <class ElementType, size_t FirstExtent, size_t SecondExtent>
736
inline constexpr bool operator==(const Span<ElementType, FirstExtent>& l,
737
const Span<ElementType, SecondExtent>& r) {
738
return (l.size() == r.size()) &&
739
std::equal(l.data(), l.data() + l.size(), r.data());
740
}
741
742
template <class ElementType, size_t Extent>
743
inline constexpr bool operator!=(const Span<ElementType, Extent>& l,
744
const Span<ElementType, Extent>& r) {
745
return !(l == r);
746
}
747
748
template <class ElementType, size_t Extent>
749
inline constexpr bool operator<(const Span<ElementType, Extent>& l,
750
const Span<ElementType, Extent>& r) {
751
return std::lexicographical_compare(l.data(), l.data() + l.size(), r.data(),
752
r.data() + r.size());
753
}
754
755
template <class ElementType, size_t Extent>
756
inline constexpr bool operator<=(const Span<ElementType, Extent>& l,
757
const Span<ElementType, Extent>& r) {
758
return !(l > r);
759
}
760
761
template <class ElementType, size_t Extent>
762
inline constexpr bool operator>(const Span<ElementType, Extent>& l,
763
const Span<ElementType, Extent>& r) {
764
return r < l;
765
}
766
767
template <class ElementType, size_t Extent>
768
inline constexpr bool operator>=(const Span<ElementType, Extent>& l,
769
const Span<ElementType, Extent>& r) {
770
return !(l < r);
771
}
772
773
namespace span_details {
774
// if we only supported compilers with good constexpr support then
775
// this pair of classes could collapse down to a constexpr function
776
777
// we should use a narrow_cast<> to go to size_t, but older compilers may not
778
// see it as constexpr and so will fail compilation of the template
779
template <class ElementType, size_t Extent>
780
struct calculate_byte_size
781
: mozilla::IntegralConstant<size_t, static_cast<size_t>(
782
sizeof(ElementType) *
783
static_cast<size_t>(Extent))> {};
784
785
template <class ElementType>
786
struct calculate_byte_size<ElementType, dynamic_extent>
787
: mozilla::IntegralConstant<size_t, dynamic_extent> {};
788
} // namespace span_details
789
790
// [Span.objectrep], views of object representation
791
/**
792
* View span as Span<const uint8_t>.
793
*/
794
template <class ElementType, size_t Extent>
795
Span<const uint8_t,
796
span_details::calculate_byte_size<ElementType, Extent>::value>
797
AsBytes(Span<ElementType, Extent> s) {
798
return {reinterpret_cast<const uint8_t*>(s.data()), s.size_bytes()};
799
}
800
801
/**
802
* View span as Span<uint8_t>.
803
*/
804
template <
805
class ElementType, size_t Extent,
806
class = span_details::enable_if_t<!mozilla::IsConst<ElementType>::value>>
807
Span<uint8_t, span_details::calculate_byte_size<ElementType, Extent>::value>
808
AsWritableBytes(Span<ElementType, Extent> s) {
809
return {reinterpret_cast<uint8_t*>(s.data()), s.size_bytes()};
810
}
811
812
/**
813
* View a span of uint8_t as a span of char.
814
*/
815
inline Span<const char> AsChars(Span<const uint8_t> s) {
816
return {reinterpret_cast<const char*>(s.data()), s.size()};
817
}
818
819
/**
820
* View a writable span of uint8_t as a span of char.
821
*/
822
inline Span<char> AsWritableChars(Span<uint8_t> s) {
823
return {reinterpret_cast<char*>(s.data()), s.size()};
824
}
825
826
//
827
// MakeSpan() - Utility functions for creating Spans
828
//
829
/**
830
* Create span from pointer and length.
831
*/
832
template <class ElementType>
833
Span<ElementType> MakeSpan(ElementType* aPtr,
834
typename Span<ElementType>::index_type aLength) {
835
return Span<ElementType>(aPtr, aLength);
836
}
837
838
/**
839
* Create span from start pointer and pointer past end.
840
*/
841
template <class ElementType>
842
Span<ElementType> MakeSpan(ElementType* aStartPtr, ElementType* aEndPtr) {
843
return Span<ElementType>(aStartPtr, aEndPtr);
844
}
845
846
/**
847
* Create span from C array.
848
* MakeSpan() does not permit creating Span objects from string literals (const
849
* char or char16_t arrays) because the Span length would include the zero
850
* terminator, which may surprise callers. Use MakeStringSpan() to create a
851
* Span whose length that excludes the string literal's zero terminator or use
852
* the MakeSpan() overload that accepts a pointer and length and specify the
853
* string literal's full length.
854
*/
855
template <class ElementType, size_t N,
856
class = span_details::enable_if_t<
857
!IsSame<ElementType, const char>::value &&
858
!IsSame<ElementType, const char16_t>::value>>
859
Span<ElementType> MakeSpan(ElementType (&aArr)[N]) {
860
return Span<ElementType>(aArr, N);
861
}
862
863
/**
864
* Create span from mozilla::Array.
865
*/
866
template <class ElementType, size_t N>
867
Span<ElementType> MakeSpan(mozilla::Array<ElementType, N>& aArr) {
868
return aArr;
869
}
870
871
/**
872
* Create span from const mozilla::Array.
873
*/
874
template <class ElementType, size_t N>
875
Span<const ElementType> MakeSpan(const mozilla::Array<ElementType, N>& arr) {
876
return arr;
877
}
878
879
/**
880
* Create span from standard-library container.
881
*/
882
template <class Container>
883
Span<typename Container::value_type> MakeSpan(Container& cont) {
884
return Span<typename Container::value_type>(cont);
885
}
886
887
/**
888
* Create span from standard-library container (const version).
889
*/
890
template <class Container>
891
Span<const typename Container::value_type> MakeSpan(const Container& cont) {
892
return Span<const typename Container::value_type>(cont);
893
}
894
895
/**
896
* Create span from smart pointer and length.
897
*/
898
template <class Ptr>
899
Span<typename Ptr::element_type> MakeSpan(Ptr& aPtr, size_t aLength) {
900
return Span<typename Ptr::element_type>(aPtr, aLength);
901
}
902
903
/**
904
* Create span from a zero-terminated C string. nullptr is
905
* treated as the empty string.
906
*/
907
inline Span<const char> MakeStringSpan(const char* aZeroTerminated) {
908
if (!aZeroTerminated) {
909
return Span<const char>();
910
}
911
return Span<const char>(aZeroTerminated, std::strlen(aZeroTerminated));
912
}
913
914
/**
915
* Create span from a zero-terminated UTF-16 C string. nullptr is
916
* treated as the empty string.
917
*/
918
inline Span<const char16_t> MakeStringSpan(const char16_t* aZeroTerminated) {
919
if (!aZeroTerminated) {
920
return Span<const char16_t>();
921
}
922
return Span<const char16_t>(aZeroTerminated,
923
span_details::strlen16(aZeroTerminated));
924
}
925
926
} // namespace mozilla
927
928
#endif // mozilla_Span_h