-
Notifications
You must be signed in to change notification settings - Fork 13.3k
/
Copy pathindex_range.rs
172 lines (151 loc) · 5.18 KB
/
index_range.rs
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
use crate::iter::{FusedIterator, TrustedLen};
use crate::num::NonZero;
use crate::ub_checks;
/// Like a `Range<usize>`, but with a safety invariant that `start <= end`.
///
/// This means that `end - start` cannot overflow, allowing some μoptimizations.
///
/// (Normal `Range` code needs to handle degenerate ranges like `10..0`,
/// which takes extra checks compared to only handling the canonical form.)
#[derive(Clone, Debug, PartialEq, Eq)]
pub(crate) struct IndexRange {
start: usize,
end: usize,
}
impl IndexRange {
/// # Safety
/// - `start <= end`
#[inline]
pub(crate) const unsafe fn new_unchecked(start: usize, end: usize) -> Self {
ub_checks::assert_unsafe_precondition!(
check_library_ub,
"IndexRange::new_unchecked requires `start <= end` \
(start:{start}, end:{end})",
(start: usize = start, end: usize = end) => start <= end,
);
IndexRange { start, end }
}
#[inline]
pub(crate) const fn zero_to(end: usize) -> Self {
IndexRange { start: 0, end }
}
#[inline]
pub(crate) const fn start(&self) -> usize {
self.start
}
#[inline]
pub(crate) const fn end(&self) -> usize {
self.end
}
#[inline]
pub(crate) const fn len(&self) -> usize {
// SAFETY: By invariant, this cannot wrap
// Using the intrinsic because a UB check here impedes LLVM optimization. (#131563)
unsafe { crate::intrinsics::unchecked_sub(self.end, self.start) }
}
/// # Safety
/// - Can only be called when `start < end`, aka when `len > 0`.
#[inline]
unsafe fn next_unchecked(&mut self) -> usize {
debug_assert!(self.start < self.end);
let value = self.start;
// SAFETY: The range isn't empty, so this cannot overflow
self.start = unsafe { value.unchecked_add(1) };
value
}
/// # Safety
/// - Can only be called when `start < end`, aka when `len > 0`.
#[inline]
unsafe fn next_back_unchecked(&mut self) -> usize {
debug_assert!(self.start < self.end);
// SAFETY: The range isn't empty, so this cannot overflow
let value = unsafe { self.end.unchecked_sub(1) };
self.end = value;
value
}
/// Removes the first `n` items from this range, returning them as an `IndexRange`.
/// If there are fewer than `n`, then the whole range is returned and
/// `self` is left empty.
///
/// This is designed to help implement `Iterator::advance_by`.
#[inline]
pub(crate) fn take_prefix(&mut self, n: usize) -> Self {
let mid = if n <= self.len() {
// SAFETY: We just checked that this will be between start and end,
// and thus the addition cannot overflow.
// Using the intrinsic avoids a superfluous UB check.
unsafe { crate::intrinsics::unchecked_add(self.start, n) }
} else {
self.end
};
let prefix = Self { start: self.start, end: mid };
self.start = mid;
prefix
}
/// Removes the last `n` items from this range, returning them as an `IndexRange`.
/// If there are fewer than `n`, then the whole range is returned and
/// `self` is left empty.
///
/// This is designed to help implement `Iterator::advance_back_by`.
#[inline]
pub(crate) fn take_suffix(&mut self, n: usize) -> Self {
let mid = if n <= self.len() {
// SAFETY: We just checked that this will be between start and end,
// and thus the subtraction cannot overflow.
// Using the intrinsic avoids a superfluous UB check.
unsafe { crate::intrinsics::unchecked_sub(self.end, n) }
} else {
self.start
};
let suffix = Self { start: mid, end: self.end };
self.end = mid;
suffix
}
}
impl Iterator for IndexRange {
type Item = usize;
#[inline]
fn next(&mut self) -> Option<usize> {
if self.len() > 0 {
// SAFETY: We just checked that the range is non-empty
unsafe { Some(self.next_unchecked()) }
} else {
None
}
}
#[inline]
fn size_hint(&self) -> (usize, Option<usize>) {
let len = self.len();
(len, Some(len))
}
#[inline]
fn advance_by(&mut self, n: usize) -> Result<(), NonZero<usize>> {
let taken = self.take_prefix(n);
NonZero::new(n - taken.len()).map_or(Ok(()), Err)
}
}
impl DoubleEndedIterator for IndexRange {
#[inline]
fn next_back(&mut self) -> Option<usize> {
if self.len() > 0 {
// SAFETY: We just checked that the range is non-empty
unsafe { Some(self.next_back_unchecked()) }
} else {
None
}
}
#[inline]
fn advance_back_by(&mut self, n: usize) -> Result<(), NonZero<usize>> {
let taken = self.take_suffix(n);
NonZero::new(n - taken.len()).map_or(Ok(()), Err)
}
}
impl ExactSizeIterator for IndexRange {
#[inline]
fn len(&self) -> usize {
self.len()
}
}
// SAFETY: Because we only deal in `usize`, our `len` is always perfect.
unsafe impl TrustedLen for IndexRange {}
impl FusedIterator for IndexRange {}