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