1use crate::iter::{FusedIterator, TrustedLen};
2use crate::num::NonZero;
3use crate::ub_checks;
45/// Like a `Range<usize>`, but with a safety invariant that `start <= end`.
6///
7/// This means that `end - start` cannot overflow, allowing some μoptimizations.
8///
9/// (Normal `Range` code needs to handle degenerate ranges like `10..0`,
10/// which takes extra checks compared to only handling the canonical form.)
11#[derive(Clone, Debug, PartialEq, Eq)]
12pub(crate) struct IndexRange {
13 start: usize,
14 end: usize,
15}
1617impl IndexRange {
18/// # Safety
19 /// - `start <= end`
20#[inline]
21pub(crate) const unsafe fn new_unchecked(start: usize, end: usize) -> Self {
22ub_checks::assert_unsafe_precondition!(
23 check_library_ub,
24"IndexRange::new_unchecked requires `start <= end`",
25 (start: usize = start, end: usize = end) => start <= end,
26 );
27 IndexRange { start, end }
28 }
2930#[inline]
31pub(crate) const fn zero_to(end: usize) -> Self {
32 IndexRange { start: 0, end }
33 }
3435#[inline]
36pub(crate) const fn start(&self) -> usize {
37self.start
38 }
3940#[inline]
41pub(crate) const fn end(&self) -> usize {
42self.end
43 }
4445#[inline]
46pub(crate) const fn len(&self) -> usize {
47// SAFETY: By invariant, this cannot wrap
48 // Using the intrinsic because a UB check here impedes LLVM optimization. (#131563)
49unsafe { crate::intrinsics::unchecked_sub(self.end, self.start) }
50 }
5152/// # Safety
53 /// - Can only be called when `start < end`, aka when `len > 0`.
54#[inline]
55unsafe fn next_unchecked(&mut self) -> usize {
56debug_assert!(self.start < self.end);
5758let value = self.start;
59// SAFETY: The range isn't empty, so this cannot overflow
60self.start = unsafe { value.unchecked_add(1) };
61 value
62 }
6364/// # Safety
65 /// - Can only be called when `start < end`, aka when `len > 0`.
66#[inline]
67unsafe fn next_back_unchecked(&mut self) -> usize {
68debug_assert!(self.start < self.end);
6970// SAFETY: The range isn't empty, so this cannot overflow
71let value = unsafe { self.end.unchecked_sub(1) };
72self.end = value;
73 value
74 }
7576/// Removes the first `n` items from this range, returning them as an `IndexRange`.
77 /// If there are fewer than `n`, then the whole range is returned and
78 /// `self` is left empty.
79 ///
80 /// This is designed to help implement `Iterator::advance_by`.
81#[inline]
82pub(crate) fn take_prefix(&mut self, n: usize) -> Self {
83let mid = if n <= self.len() {
84// SAFETY: We just checked that this will be between start and end,
85 // and thus the addition cannot overflow.
86 // Using the intrinsic avoids a superfluous UB check.
87unsafe { crate::intrinsics::unchecked_add(self.start, n) }
88 } else {
89self.end
90 };
91let prefix = Self { start: self.start, end: mid };
92self.start = mid;
93 prefix
94 }
9596/// Removes the last `n` items from this range, returning them as an `IndexRange`.
97 /// If there are fewer than `n`, then the whole range is returned and
98 /// `self` is left empty.
99 ///
100 /// This is designed to help implement `Iterator::advance_back_by`.
101#[inline]
102pub(crate) fn take_suffix(&mut self, n: usize) -> Self {
103let mid = if n <= self.len() {
104// SAFETY: We just checked that this will be between start and end,
105 // and thus the subtraction cannot overflow.
106 // Using the intrinsic avoids a superfluous UB check.
107unsafe { crate::intrinsics::unchecked_sub(self.end, n) }
108 } else {
109self.start
110 };
111let suffix = Self { start: mid, end: self.end };
112self.end = mid;
113 suffix
114 }
115}
116117impl Iterator for IndexRange {
118type Item = usize;
119120#[inline]
121fn next(&mut self) -> Option<usize> {
122if self.len() > 0 {
123// SAFETY: We just checked that the range is non-empty
124unsafe { Some(self.next_unchecked()) }
125 } else {
126None
127}
128 }
129130#[inline]
131fn size_hint(&self) -> (usize, Option<usize>) {
132let len = self.len();
133 (len, Some(len))
134 }
135136#[inline]
137fn advance_by(&mut self, n: usize) -> Result<(), NonZero<usize>> {
138let taken = self.take_prefix(n);
139 NonZero::new(n - taken.len()).map_or(Ok(()), Err)
140 }
141}
142143impl DoubleEndedIterator for IndexRange {
144#[inline]
145fn next_back(&mut self) -> Option<usize> {
146if self.len() > 0 {
147// SAFETY: We just checked that the range is non-empty
148unsafe { Some(self.next_back_unchecked()) }
149 } else {
150None
151}
152 }
153154#[inline]
155fn advance_back_by(&mut self, n: usize) -> Result<(), NonZero<usize>> {
156let taken = self.take_suffix(n);
157 NonZero::new(n - taken.len()).map_or(Ok(()), Err)
158 }
159}
160161impl ExactSizeIterator for IndexRange {
162#[inline]
163fn len(&self) -> usize {
164self.len()
165 }
166}
167168// SAFETY: Because we only deal in `usize`, our `len` is always perfect.
169unsafe impl TrustedLen for IndexRange {}
170171impl FusedIterator for IndexRange {}