core/slice/iter/macros.rs
1//! Macros used by iterators of slice.
2
3/// Convenience & performance macro for consuming the `end_or_len` field, by
4/// giving a `(&mut) usize` or `(&mut) NonNull<T>` depending whether `T` is
5/// or is not a ZST respectively.
6///
7/// Internally, this reads the `end` through a pointer-to-`NonNull` so that
8/// it'll get the appropriate non-null metadata in the backend without needing
9/// to call `assume` manually.
10macro_rules! if_zst {
11 (mut $this:ident, $len:ident => $zst_body:expr, $end:ident => $other_body:expr,) => {{
12 #![allow(unused_unsafe)] // we're sometimes used within an unsafe block
13
14 if T::IS_ZST {
15 // SAFETY: for ZSTs, the pointer is storing a provenance-free length,
16 // so consuming and updating it as a `usize` is fine.
17 let $len = unsafe { &mut *(&raw mut $this.end_or_len).cast::<usize>() };
18 $zst_body
19 } else {
20 // SAFETY: for non-ZSTs, the type invariant ensures it cannot be null
21 let $end = unsafe { &mut *(&raw mut $this.end_or_len).cast::<NonNull<T>>() };
22 $other_body
23 }
24 }};
25 ($this:ident, $len:ident => $zst_body:expr, $end:ident => $other_body:expr,) => {{
26 #![allow(unused_unsafe)] // we're sometimes used within an unsafe block
27
28 if T::IS_ZST {
29 let $len = $this.end_or_len.addr();
30 $zst_body
31 } else {
32 // SAFETY: for non-ZSTs, the type invariant ensures it cannot be null
33 let $end = unsafe { mem::transmute::<*const T, NonNull<T>>($this.end_or_len) };
34 $other_body
35 }
36 }};
37}
38
39// Inlining is_empty and len makes a huge performance difference
40macro_rules! is_empty {
41 ($self: ident) => {
42 if_zst!($self,
43 len => len == 0,
44 end => $self.ptr == end,
45 )
46 };
47}
48
49macro_rules! len {
50 ($self: ident) => {{
51 if_zst!($self,
52 len => len,
53 end => {
54 // To get rid of some bounds checks (see `position`), we use ptr_sub instead of
55 // offset_from (Tested by `codegen/slice-position-bounds-check`.)
56 // SAFETY: by the type invariant pointers are aligned and `start <= end`
57 unsafe { end.offset_from_unsigned($self.ptr) }
58 },
59 )
60 }};
61}
62
63// The shared definition of the `Iter` and `IterMut` iterators
64macro_rules! iterator {
65 (
66 struct $name:ident -> $ptr:ty,
67 $elem:ty,
68 $raw_mut:tt,
69 {$( $mut_:tt )?},
70 $into_ref:ident,
71 $array_ref:ident,
72 {$($extra:tt)*}
73 ) => {
74 impl<'a, T> $name<'a, T> {
75 /// Returns the last element and moves the end of the iterator backwards by 1.
76 ///
77 /// # Safety
78 ///
79 /// The iterator must not be empty
80 #[inline]
81 unsafe fn next_back_unchecked(&mut self) -> $elem {
82 // SAFETY: the caller promised it's not empty, so
83 // the offsetting is in-bounds and there's an element to return.
84 unsafe { self.pre_dec_end(1).$into_ref() }
85 }
86
87 // Helper function for creating a slice from the iterator.
88 #[inline(always)]
89 fn make_slice(&self) -> &'a [T] {
90 // SAFETY: the iterator was created from a slice with pointer
91 // `self.ptr` and length `len!(self)`. This guarantees that all
92 // the prerequisites for `from_raw_parts` are fulfilled.
93 unsafe { from_raw_parts(self.ptr.as_ptr(), len!(self)) }
94 }
95
96 // Helper function for moving the start of the iterator forwards by `offset` elements,
97 // returning the old start.
98 // Unsafe because the offset must not exceed `self.len()`.
99 #[inline(always)]
100 unsafe fn post_inc_start(&mut self, offset: usize) -> NonNull<T> {
101 let old = self.ptr;
102
103 // SAFETY: the caller guarantees that `offset` doesn't exceed `self.len()`,
104 // so this new pointer is inside `self` and thus guaranteed to be non-null.
105 unsafe {
106 if_zst!(mut self,
107 // Using the intrinsic directly avoids emitting a UbCheck
108 len => *len = crate::intrinsics::unchecked_sub(*len, offset),
109 _end => self.ptr = self.ptr.add(offset),
110 );
111 }
112 old
113 }
114
115 // Helper function for moving the end of the iterator backwards by `offset` elements,
116 // returning the new end.
117 // Unsafe because the offset must not exceed `self.len()`.
118 #[inline(always)]
119 unsafe fn pre_dec_end(&mut self, offset: usize) -> NonNull<T> {
120 if_zst!(mut self,
121 // SAFETY: By our precondition, `offset` can be at most the
122 // current length, so the subtraction can never overflow.
123 len => unsafe {
124 // Using the intrinsic directly avoids emitting a UbCheck
125 *len = crate::intrinsics::unchecked_sub(*len, offset);
126 self.ptr
127 },
128 // SAFETY: the caller guarantees that `offset` doesn't exceed `self.len()`,
129 // which is guaranteed to not overflow an `isize`. Also, the resulting pointer
130 // is in bounds of `slice`, which fulfills the other requirements for `offset`.
131 end => unsafe {
132 *end = end.sub(offset);
133 *end
134 },
135 )
136 }
137 }
138
139 #[stable(feature = "rust1", since = "1.0.0")]
140 impl<T> ExactSizeIterator for $name<'_, T> {
141 #[inline(always)]
142 fn len(&self) -> usize {
143 len!(self)
144 }
145
146 #[inline(always)]
147 fn is_empty(&self) -> bool {
148 is_empty!(self)
149 }
150 }
151
152 #[stable(feature = "rust1", since = "1.0.0")]
153 impl<'a, T> Iterator for $name<'a, T> {
154 type Item = $elem;
155
156 #[inline]
157 fn next(&mut self) -> Option<$elem> {
158 // intentionally not using the helpers because this is
159 // one of the most mono'd things in the library.
160
161 let ptr = self.ptr;
162 let end_or_len = self.end_or_len;
163 // SAFETY: See inner comments. (For some reason having multiple
164 // block breaks inlining this -- if you can fix that please do!)
165 unsafe {
166 if T::IS_ZST {
167 let len = end_or_len.addr();
168 if len == 0 {
169 return None;
170 }
171 // SAFETY: just checked that it's not zero, so subtracting one
172 // cannot wrap. (Ideally this would be `checked_sub`, which
173 // does the same thing internally, but as of 2025-02 that
174 // doesn't optimize quite as small in MIR.)
175 self.end_or_len = without_provenance_mut(len.unchecked_sub(1));
176 } else {
177 // SAFETY: by type invariant, the `end_or_len` field is always
178 // non-null for a non-ZST pointee. (This transmute ensures we
179 // get `!nonnull` metadata on the load of the field.)
180 if ptr == crate::intrinsics::transmute::<$ptr, NonNull<T>>(end_or_len) {
181 return None;
182 }
183 // SAFETY: since it's not empty, per the check above, moving
184 // forward one keeps us inside the slice, and this is valid.
185 self.ptr = ptr.add(1);
186 }
187 // SAFETY: Now that we know it wasn't empty and we've moved past
188 // the first one (to avoid giving a duplicate `&mut` next time),
189 // we can give out a reference to it.
190 Some({ptr}.$into_ref())
191 }
192 }
193
194 fn next_chunk<const N:usize>(&mut self) -> Result<[$elem; N], crate::array::IntoIter<$elem, N>> {
195 if T::IS_ZST || len!(self) < N {
196 return crate::array::iter_next_chunk(self);
197 }
198
199 // SAFETY: the check above ensures len >= N
200 unsafe {
201 let r = self
202 .post_inc_start(N)
203 .cast_array() // NonNull<T> -> NonNull<[T; N]>
204 // SAFETY: post_inc_start(N) insures we don't return overlapping `&mut`s
205 .$into_ref() // NonNull<[T; N]> -> &{mut} [T; N]
206 .$array_ref(); // must convert &{mut} [T; N] to [&{mut} T; N]
207
208 Ok(r)
209 }
210 }
211
212 #[inline]
213 fn size_hint(&self) -> (usize, Option<usize>) {
214 let exact = len!(self);
215 (exact, Some(exact))
216 }
217
218 #[inline]
219 fn count(self) -> usize {
220 len!(self)
221 }
222
223 #[inline]
224 fn nth(&mut self, n: usize) -> Option<$elem> {
225 if n >= len!(self) {
226 // This iterator is now empty.
227 if_zst!(mut self,
228 len => *len = 0,
229 end => self.ptr = *end,
230 );
231 return None;
232 }
233 // SAFETY: We are in bounds. `post_inc_start` does the right thing even for ZSTs.
234 unsafe {
235 self.post_inc_start(n);
236 Some(self.post_inc_start(1).$into_ref())
237 }
238 }
239
240 #[inline]
241 fn advance_by(&mut self, n: usize) -> Result<(), NonZero<usize>> {
242 let advance = cmp::min(len!(self), n);
243 // SAFETY: By construction, `advance` does not exceed `self.len()`.
244 unsafe { self.post_inc_start(advance) };
245 NonZero::new(n - advance).map_or(Ok(()), Err)
246 }
247
248 #[inline]
249 fn last(mut self) -> Option<$elem> {
250 self.next_back()
251 }
252
253 #[inline]
254 fn fold<B, F>(self, init: B, mut f: F) -> B
255 where
256 F: FnMut(B, Self::Item) -> B,
257 {
258 // this implementation consists of the following optimizations compared to the
259 // default implementation:
260 // - do-while loop, as is llvm's preferred loop shape,
261 // see https://releases.llvm.org/16.0.0/docs/LoopTerminology.html#more-canonical-loops
262 // - bumps an index instead of a pointer since the latter case inhibits
263 // some optimizations, see #111603
264 // - avoids Option wrapping/matching
265 if is_empty!(self) {
266 return init;
267 }
268 let mut acc = init;
269 let mut i = 0;
270 let len = len!(self);
271 loop {
272 // SAFETY: the loop iterates `i in 0..len`, which always is in bounds of
273 // the slice allocation
274 acc = f(acc, unsafe { & $( $mut_ )? *self.ptr.add(i).as_ptr() });
275 // SAFETY: `i` can't overflow since it'll only reach usize::MAX if the
276 // slice had that length, in which case we'll break out of the loop
277 // after the increment
278 i = unsafe { i.unchecked_add(1) };
279 if i == len {
280 break;
281 }
282 }
283 acc
284 }
285
286 // We override the default implementation, which uses `try_fold`,
287 // because this simple implementation generates less LLVM IR and is
288 // faster to compile.
289 #[inline]
290 fn for_each<F>(mut self, mut f: F)
291 where
292 Self: Sized,
293 F: FnMut(Self::Item),
294 {
295 while let Some(x) = self.next() {
296 f(x);
297 }
298 }
299
300 // We override the default implementation, which uses `try_fold`,
301 // because this simple implementation generates less LLVM IR and is
302 // faster to compile.
303 #[inline]
304 fn all<F>(&mut self, mut f: F) -> bool
305 where
306 Self: Sized,
307 F: FnMut(Self::Item) -> bool,
308 {
309 while let Some(x) = self.next() {
310 if !f(x) {
311 return false;
312 }
313 }
314 true
315 }
316
317 // We override the default implementation, which uses `try_fold`,
318 // because this simple implementation generates less LLVM IR and is
319 // faster to compile.
320 #[inline]
321 fn any<F>(&mut self, mut f: F) -> bool
322 where
323 Self: Sized,
324 F: FnMut(Self::Item) -> bool,
325 {
326 while let Some(x) = self.next() {
327 if f(x) {
328 return true;
329 }
330 }
331 false
332 }
333
334 // We override the default implementation, which uses `try_fold`,
335 // because this simple implementation generates less LLVM IR and is
336 // faster to compile.
337 #[inline]
338 fn find<P>(&mut self, mut predicate: P) -> Option<Self::Item>
339 where
340 Self: Sized,
341 P: FnMut(&Self::Item) -> bool,
342 {
343 while let Some(x) = self.next() {
344 if predicate(&x) {
345 return Some(x);
346 }
347 }
348 None
349 }
350
351 // We override the default implementation, which uses `try_fold`,
352 // because this simple implementation generates less LLVM IR and is
353 // faster to compile.
354 #[inline]
355 fn find_map<B, F>(&mut self, mut f: F) -> Option<B>
356 where
357 Self: Sized,
358 F: FnMut(Self::Item) -> Option<B>,
359 {
360 while let Some(x) = self.next() {
361 if let Some(y) = f(x) {
362 return Some(y);
363 }
364 }
365 None
366 }
367
368 // We override the default implementation, which uses `try_fold`,
369 // because this simple implementation generates less LLVM IR and is
370 // faster to compile. Also, the `assume` avoids a bounds check.
371 #[inline]
372 fn position<P>(&mut self, mut predicate: P) -> Option<usize> where
373 Self: Sized,
374 P: FnMut(Self::Item) -> bool,
375 {
376 let n = len!(self);
377 let mut i = 0;
378 while let Some(x) = self.next() {
379 if predicate(x) {
380 // SAFETY: we are guaranteed to be in bounds by the loop invariant:
381 // when `i >= n`, `self.next()` returns `None` and the loop breaks.
382 unsafe { assert_unchecked(i < n) };
383 return Some(i);
384 }
385 i += 1;
386 }
387 None
388 }
389
390 // We override the default implementation, which uses `try_fold`,
391 // because this simple implementation generates less LLVM IR and is
392 // faster to compile. Also, the `assume` avoids a bounds check.
393 #[inline]
394 fn rposition<P>(&mut self, mut predicate: P) -> Option<usize> where
395 P: FnMut(Self::Item) -> bool,
396 Self: Sized + ExactSizeIterator + DoubleEndedIterator
397 {
398 let n = len!(self);
399 let mut i = n;
400 while let Some(x) = self.next_back() {
401 i -= 1;
402 if predicate(x) {
403 // SAFETY: `i` must be lower than `n` since it starts at `n`
404 // and is only decreasing.
405 unsafe { assert_unchecked(i < n) };
406 return Some(i);
407 }
408 }
409 None
410 }
411
412 #[inline]
413 unsafe fn __iterator_get_unchecked(&mut self, idx: usize) -> Self::Item {
414 // SAFETY: the caller must guarantee that `i` is in bounds of
415 // the underlying slice, so `i` cannot overflow an `isize`, and
416 // the returned references is guaranteed to refer to an element
417 // of the slice and thus guaranteed to be valid.
418 //
419 // Also note that the caller also guarantees that we're never
420 // called with the same index again, and that no other methods
421 // that will access this subslice are called, so it is valid
422 // for the returned reference to be mutable in the case of
423 // `IterMut`
424 unsafe { & $( $mut_ )? * self.ptr.as_ptr().add(idx) }
425 }
426
427 $($extra)*
428 }
429
430 #[stable(feature = "rust1", since = "1.0.0")]
431 impl<'a, T> DoubleEndedIterator for $name<'a, T> {
432 #[inline]
433 fn next_back(&mut self) -> Option<$elem> {
434 // could be implemented with slices, but this avoids bounds checks
435
436 // SAFETY: The call to `next_back_unchecked`
437 // is safe since we check if the iterator is empty first.
438 unsafe {
439 if is_empty!(self) {
440 None
441 } else {
442 Some(self.next_back_unchecked())
443 }
444 }
445 }
446
447 #[inline]
448 fn nth_back(&mut self, n: usize) -> Option<$elem> {
449 if n >= len!(self) {
450 // This iterator is now empty.
451 if_zst!(mut self,
452 len => *len = 0,
453 end => *end = self.ptr,
454 );
455 return None;
456 }
457 // SAFETY: We are in bounds. `pre_dec_end` does the right thing even for ZSTs.
458 unsafe {
459 self.pre_dec_end(n);
460 Some(self.next_back_unchecked())
461 }
462 }
463
464 #[inline]
465 fn advance_back_by(&mut self, n: usize) -> Result<(), NonZero<usize>> {
466 let advance = cmp::min(len!(self), n);
467 // SAFETY: By construction, `advance` does not exceed `self.len()`.
468 unsafe { self.pre_dec_end(advance) };
469 NonZero::new(n - advance).map_or(Ok(()), Err)
470 }
471 }
472
473 #[stable(feature = "fused", since = "1.26.0")]
474 impl<T> FusedIterator for $name<'_, T> {}
475
476 #[unstable(feature = "trusted_len", issue = "37572")]
477 unsafe impl<T> TrustedLen for $name<'_, T> {}
478
479 #[stable(feature = "default_iters", since = "1.70.0")]
480 impl<T> Default for $name<'_, T> {
481 /// Creates an empty slice iterator.
482 ///
483 /// ```
484 #[doc = concat!("# use core::slice::", stringify!($name), ";")]
485 #[doc = concat!("let iter: ", stringify!($name<'_, u8>), " = Default::default();")]
486 /// assert_eq!(iter.len(), 0);
487 /// ```
488 fn default() -> Self {
489 (& $( $mut_ )? []).into_iter()
490 }
491 }
492 }
493}
494
495macro_rules! forward_iterator {
496 ($name:ident: $elem:ident, $iter_of:ty) => {
497 #[stable(feature = "rust1", since = "1.0.0")]
498 impl<'a, $elem, P> Iterator for $name<'a, $elem, P>
499 where
500 P: FnMut(&T) -> bool,
501 {
502 type Item = $iter_of;
503
504 #[inline]
505 fn next(&mut self) -> Option<$iter_of> {
506 self.inner.next()
507 }
508
509 #[inline]
510 fn size_hint(&self) -> (usize, Option<usize>) {
511 self.inner.size_hint()
512 }
513 }
514
515 #[stable(feature = "fused", since = "1.26.0")]
516 impl<'a, $elem, P> FusedIterator for $name<'a, $elem, P> where P: FnMut(&T) -> bool {}
517 };
518}