Skip to main content

core/slice/
iter.rs

1//! Definitions of a bunch of iterators for `[T]`.
2
3#[macro_use] // import iterator! and forward_iterator!
4mod macros;
5
6use super::{from_raw_parts, from_raw_parts_mut};
7use crate::hint::assert_unchecked;
8use crate::iter::{FusedIterator, TrustedLen, TrustedRandomAccess, TrustedRandomAccessNoCoerce};
9use crate::marker::PhantomData;
10use crate::mem::{self, SizedTypeProperties};
11use crate::num::NonZero;
12use crate::ptr::{NonNull, without_provenance, without_provenance_mut};
13use crate::{cmp, fmt};
14
15#[stable(feature = "boxed_slice_into_iter", since = "1.80.0")]
16impl<T> !Iterator for [T] {}
17
18#[stable(feature = "rust1", since = "1.0.0")]
19impl<'a, T> IntoIterator for &'a [T] {
20    type Item = &'a T;
21    type IntoIter = Iter<'a, T>;
22
23    fn into_iter(self) -> Iter<'a, T> {
24        self.iter()
25    }
26}
27
28#[stable(feature = "rust1", since = "1.0.0")]
29impl<'a, T> IntoIterator for &'a mut [T] {
30    type Item = &'a mut T;
31    type IntoIter = IterMut<'a, T>;
32
33    fn into_iter(self) -> IterMut<'a, T> {
34        self.iter_mut()
35    }
36}
37
38/// Immutable slice iterator
39///
40/// This struct is created by the [`iter`] method on [slices].
41///
42/// # Examples
43///
44/// Basic usage:
45///
46/// ```
47/// // First, we need a slice to call the `iter` method on:
48/// let slice = &[1, 2, 3];
49///
50/// // Then we call `iter` on the slice to get the `Iter` iterator,
51/// // and iterate over it:
52/// for element in slice.iter() {
53///     println!("{element}");
54/// }
55///
56/// // This for loop actually already works without calling `iter`:
57/// for element in slice {
58///     println!("{element}");
59/// }
60/// ```
61///
62/// [`iter`]: slice::iter
63/// [slices]: slice
64#[stable(feature = "rust1", since = "1.0.0")]
65#[must_use = "iterators are lazy and do nothing unless consumed"]
66#[rustc_diagnostic_item = "SliceIter"]
67pub struct Iter<'a, T: 'a> {
68    /// The pointer to the next element to return, or the past-the-end location
69    /// if the iterator is empty.
70    ///
71    /// This address will be used for all ZST elements, never changed.
72    ptr: NonNull<T>,
73    /// For non-ZSTs, the non-null pointer to the past-the-end element.
74    ///
75    /// For ZSTs, this is `ptr::without_provenance_mut(len)`.
76    end_or_len: *const T,
77    _marker: PhantomData<&'a T>,
78}
79
80#[stable(feature = "core_impl_debug", since = "1.9.0")]
81impl<T: fmt::Debug> fmt::Debug for Iter<'_, T> {
82    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
83        f.debug_tuple("Iter").field(&self.as_slice()).finish()
84    }
85}
86
87#[stable(feature = "rust1", since = "1.0.0")]
88unsafe impl<T: Sync> Sync for Iter<'_, T> {}
89#[stable(feature = "rust1", since = "1.0.0")]
90unsafe impl<T: Sync> Send for Iter<'_, T> {}
91
92impl<'a, T> Iter<'a, T> {
93    #[inline]
94    pub(super) const fn new(slice: &'a [T]) -> Self {
95        let len = slice.len();
96        let ptr: NonNull<T> = NonNull::from_ref(slice).cast();
97        // SAFETY: Similar to `IterMut::new`.
98        unsafe {
99            let end_or_len =
100                if T::IS_ZST { without_provenance(len) } else { ptr.as_ptr().add(len) };
101
102            Self { ptr, end_or_len, _marker: PhantomData }
103        }
104    }
105
106    /// Views the underlying data as a subslice of the original data.
107    ///
108    /// # Examples
109    ///
110    /// Basic usage:
111    ///
112    /// ```
113    /// // First, we need a slice to call the `iter` method on:
114    /// let slice = &[1, 2, 3];
115    ///
116    /// // Then we call `iter` on the slice to get the `Iter` iterator:
117    /// let mut iter = slice.iter();
118    /// // Here `as_slice` still returns the whole slice, so this prints "[1, 2, 3]":
119    /// println!("{:?}", iter.as_slice());
120    ///
121    /// // Now, we call the `next` method to remove the first element from the iterator:
122    /// iter.next();
123    /// // Here the iterator does not contain the first element of the slice any more,
124    /// // so `as_slice` only returns the last two elements of the slice,
125    /// // and so this prints "[2, 3]":
126    /// println!("{:?}", iter.as_slice());
127    ///
128    /// // The underlying slice has not been modified and still contains three elements,
129    /// // so this prints "[1, 2, 3]":
130    /// println!("{:?}", slice);
131    /// ```
132    #[must_use]
133    #[stable(feature = "iter_to_slice", since = "1.4.0")]
134    #[inline]
135    pub fn as_slice(&self) -> &'a [T] {
136        self.make_slice()
137    }
138}
139
140iterator! {struct Iter -> *const T, &'a T, const, {/* no mut */}, as_ref, each_ref, {
141    fn is_sorted_by<F>(self, mut compare: F) -> bool
142    where
143        Self: Sized,
144        F: FnMut(&Self::Item, &Self::Item) -> bool,
145    {
146        self.as_slice().is_sorted_by(|a, b| compare(&a, &b))
147    }
148}}
149
150#[stable(feature = "rust1", since = "1.0.0")]
151impl<T> Clone for Iter<'_, T> {
152    #[inline]
153    fn clone(&self) -> Self {
154        Iter { ptr: self.ptr, end_or_len: self.end_or_len, _marker: self._marker }
155    }
156}
157
158#[stable(feature = "slice_iter_as_ref", since = "1.13.0")]
159impl<T> AsRef<[T]> for Iter<'_, T> {
160    #[inline]
161    fn as_ref(&self) -> &[T] {
162        self.as_slice()
163    }
164}
165
166/// Mutable slice iterator.
167///
168/// This struct is created by the [`iter_mut`] method on [slices].
169///
170/// # Examples
171///
172/// Basic usage:
173///
174/// ```
175/// // First, we need a slice to call the `iter_mut` method on:
176/// let slice = &mut [1, 2, 3];
177///
178/// // Then we call `iter_mut` on the slice to get the `IterMut` iterator,
179/// // iterate over it and increment each element value:
180/// for element in slice.iter_mut() {
181///     *element += 1;
182/// }
183///
184/// // We now have "[2, 3, 4]":
185/// println!("{slice:?}");
186/// ```
187///
188/// [`iter_mut`]: slice::iter_mut
189/// [slices]: slice
190#[stable(feature = "rust1", since = "1.0.0")]
191#[must_use = "iterators are lazy and do nothing unless consumed"]
192pub struct IterMut<'a, T: 'a> {
193    /// The pointer to the next element to return, or the past-the-end location
194    /// if the iterator is empty.
195    ///
196    /// This address will be used for all ZST elements, never changed.
197    ptr: NonNull<T>,
198    /// For non-ZSTs, the non-null pointer to the past-the-end element.
199    ///
200    /// For ZSTs, this is `ptr::without_provenance_mut(len)`.
201    end_or_len: *mut T,
202    _marker: PhantomData<&'a mut T>,
203}
204
205#[stable(feature = "core_impl_debug", since = "1.9.0")]
206impl<T: fmt::Debug> fmt::Debug for IterMut<'_, T> {
207    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
208        f.debug_tuple("IterMut").field(&self.make_slice()).finish()
209    }
210}
211
212#[stable(feature = "rust1", since = "1.0.0")]
213unsafe impl<T: Sync> Sync for IterMut<'_, T> {}
214#[stable(feature = "rust1", since = "1.0.0")]
215unsafe impl<T: Send> Send for IterMut<'_, T> {}
216
217impl<'a, T> IterMut<'a, T> {
218    #[inline]
219    pub(super) const fn new(slice: &'a mut [T]) -> Self {
220        let len = slice.len();
221        let ptr: NonNull<T> = NonNull::from_mut(slice).cast();
222        // SAFETY: There are several things here:
223        //
224        // `ptr` has been obtained by `slice.as_ptr()` where `slice` is a valid
225        // reference thus it is non-NUL and safe to use and pass to
226        // `NonNull::new_unchecked` .
227        //
228        // Adding `slice.len()` to the starting pointer gives a pointer
229        // at the end of `slice`. `end` will never be dereferenced, only checked
230        // for direct pointer equality with `ptr` to check if the iterator is
231        // done.
232        //
233        // In the case of a ZST, the end pointer is just the length.  It's never
234        // used as a pointer at all, and thus it's fine to have no provenance.
235        //
236        // See the `next_unchecked!` and `is_empty!` macros as well as the
237        // `post_inc_start` method for more information.
238        unsafe {
239            let end_or_len =
240                if T::IS_ZST { without_provenance_mut(len) } else { ptr.as_ptr().add(len) };
241
242            Self { ptr, end_or_len, _marker: PhantomData }
243        }
244    }
245
246    /// Views the underlying data as a subslice of the original data.
247    ///
248    /// To avoid creating `&mut` references that alias, this is forced
249    /// to consume the iterator.
250    ///
251    /// # Examples
252    ///
253    /// Basic usage:
254    ///
255    /// ```
256    /// // First, we need a slice to call the `iter_mut` method on:
257    /// let mut slice = &mut [1, 2, 3];
258    ///
259    /// // Then we call `iter_mut` on the slice to get the `IterMut` struct:
260    /// let mut iter = slice.iter_mut();
261    /// // Now, we call the `next` method to remove the first element of the iterator,
262    /// // unwrap and dereference what we get from `next` and increase its value by 1:
263    /// *iter.next().unwrap() += 1;
264    /// // Here the iterator does not contain the first element of the slice any more,
265    /// // so `into_slice` only returns the last two elements of the slice,
266    /// // and so this prints "[2, 3]":
267    /// println!("{:?}", iter.into_slice());
268    /// // The underlying slice still contains three elements, but its first element
269    /// // was increased by 1, so this prints "[2, 2, 3]":
270    /// println!("{:?}", slice);
271    /// ```
272    #[must_use = "`self` will be dropped if the result is not used"]
273    #[stable(feature = "iter_to_slice", since = "1.4.0")]
274    pub fn into_slice(self) -> &'a mut [T] {
275        // SAFETY: the iterator was created from a mutable slice with pointer
276        // `self.ptr` and length `len!(self)`. This guarantees that all the prerequisites
277        // for `from_raw_parts_mut` are fulfilled.
278        unsafe { from_raw_parts_mut(self.ptr.as_ptr(), len!(self)) }
279    }
280
281    /// Views the underlying data as a subslice of the original data.
282    ///
283    /// # Examples
284    ///
285    /// Basic usage:
286    ///
287    /// ```
288    /// // First, we need a slice to call the `iter_mut` method on:
289    /// let slice = &mut [1, 2, 3];
290    ///
291    /// // Then we call `iter_mut` on the slice to get the `IterMut` iterator:
292    /// let mut iter = slice.iter_mut();
293    /// // Here `as_slice` still returns the whole slice, so this prints "[1, 2, 3]":
294    /// println!("{:?}", iter.as_slice());
295    ///
296    /// // Now, we call the `next` method to remove the first element from the iterator
297    /// // and increment its value:
298    /// *iter.next().unwrap() += 1;
299    /// // Here the iterator does not contain the first element of the slice any more,
300    /// // so `as_slice` only returns the last two elements of the slice,
301    /// // and so this prints "[2, 3]":
302    /// println!("{:?}", iter.as_slice());
303    ///
304    /// // The underlying slice still contains three elements, but its first element
305    /// // was increased by 1, so this prints "[2, 2, 3]":
306    /// println!("{:?}", slice);
307    /// ```
308    #[must_use]
309    #[stable(feature = "slice_iter_mut_as_slice", since = "1.53.0")]
310    #[inline]
311    pub fn as_slice(&self) -> &[T] {
312        self.make_slice()
313    }
314
315    /// Views the underlying data as a mutable subslice of the original data.
316    ///
317    /// # Examples
318    ///
319    /// Basic usage:
320    ///
321    /// ```
322    /// #![feature(slice_iter_mut_as_mut_slice)]
323    ///
324    /// let mut slice: &mut [usize] = &mut [1, 2, 3];
325    ///
326    /// // First, we get the iterator:
327    /// let mut iter = slice.iter_mut();
328    /// // Then, we get a mutable slice from it:
329    /// let mut_slice = iter.as_mut_slice();
330    /// // So if we check what the `as_mut_slice` method returned, we have "[1, 2, 3]":
331    /// assert_eq!(mut_slice, &mut [1, 2, 3]);
332    ///
333    /// // We can use it to mutate the slice:
334    /// mut_slice[0] = 4;
335    /// mut_slice[2] = 5;
336    ///
337    /// // Next, we can move to the second element of the slice, checking that
338    /// // it yields the value we just wrote:
339    /// assert_eq!(iter.next(), Some(&mut 4));
340    /// // Now `as_mut_slice` returns "[2, 5]":
341    /// assert_eq!(iter.as_mut_slice(), &mut [2, 5]);
342    /// ```
343    #[must_use]
344    // FIXME: Uncomment the `AsMut<[T]>` impl when this gets stabilized.
345    #[unstable(feature = "slice_iter_mut_as_mut_slice", issue = "93079")]
346    pub fn as_mut_slice(&mut self) -> &mut [T] {
347        // SAFETY: the iterator was created from a mutable slice with pointer
348        // `self.ptr` and length `len!(self)`. This guarantees that all the prerequisites
349        // for `from_raw_parts_mut` are fulfilled.
350        unsafe { from_raw_parts_mut(self.ptr.as_ptr(), len!(self)) }
351    }
352}
353
354#[stable(feature = "slice_iter_mut_as_slice", since = "1.53.0")]
355impl<T> AsRef<[T]> for IterMut<'_, T> {
356    #[inline]
357    fn as_ref(&self) -> &[T] {
358        self.as_slice()
359    }
360}
361
362// #[stable(feature = "slice_iter_mut_as_mut_slice", since = "FIXME")]
363// impl<T> AsMut<[T]> for IterMut<'_, T> {
364//     fn as_mut(&mut self) -> &mut [T] {
365//         self.as_mut_slice()
366//     }
367// }
368
369iterator! {struct IterMut -> *mut T, &'a mut T, mut, {mut}, as_mut, each_mut, {}}
370
371/// An internal abstraction over the splitting iterators, so that
372/// splitn, splitn_mut etc can be implemented once.
373#[doc(hidden)]
374pub(super) trait SplitIter: DoubleEndedIterator {
375    /// Marks the underlying iterator as complete, extracting the remaining
376    /// portion of the slice.
377    fn finish(&mut self) -> Option<Self::Item>;
378}
379
380/// An iterator over subslices separated by elements that match a predicate
381/// function.
382///
383/// This struct is created by the [`split`] method on [slices].
384///
385/// # Example
386///
387/// ```
388/// let slice = [10, 40, 33, 20];
389/// let mut iter = slice.split(|num| num % 3 == 0);
390/// assert_eq!(iter.next(), Some(&[10, 40][..]));
391/// assert_eq!(iter.next(), Some(&[20][..]));
392/// assert_eq!(iter.next(), None);
393/// ```
394///
395/// [`split`]: slice::split
396/// [slices]: slice
397#[stable(feature = "rust1", since = "1.0.0")]
398#[must_use = "iterators are lazy and do nothing unless consumed"]
399pub struct Split<'a, T: 'a, P>
400where
401    P: FnMut(&T) -> bool,
402{
403    // Used for `SplitWhitespace` and `SplitAsciiWhitespace` `as_str` methods
404    pub(crate) v: &'a [T],
405    pred: P,
406    // Used for `SplitAsciiWhitespace` `as_str` method
407    pub(crate) finished: bool,
408}
409
410impl<'a, T: 'a, P: FnMut(&T) -> bool> Split<'a, T, P> {
411    #[inline]
412    pub(super) fn new(slice: &'a [T], pred: P) -> Self {
413        Self { v: slice, pred, finished: false }
414    }
415    /// Returns a slice which contains items not yet handled by split.
416    /// # Example
417    ///
418    /// ```
419    /// #![feature(split_as_slice)]
420    /// let slice = [1,2,3,4,5];
421    /// let mut split = slice.split(|v| v % 2 == 0);
422    /// assert!(split.next().is_some());
423    /// assert_eq!(split.as_slice(), &[3,4,5]);
424    /// ```
425    #[unstable(feature = "split_as_slice", issue = "96137")]
426    pub fn as_slice(&self) -> &'a [T] {
427        if self.finished { &[] } else { &self.v }
428    }
429}
430
431#[stable(feature = "core_impl_debug", since = "1.9.0")]
432impl<T: fmt::Debug, P> fmt::Debug for Split<'_, T, P>
433where
434    P: FnMut(&T) -> bool,
435{
436    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
437        f.debug_struct("Split").field("v", &self.v).field("finished", &self.finished).finish()
438    }
439}
440
441// FIXME(#26925) Remove in favor of `#[derive(Clone)]`
442#[stable(feature = "rust1", since = "1.0.0")]
443impl<T, P> Clone for Split<'_, T, P>
444where
445    P: Clone + FnMut(&T) -> bool,
446{
447    fn clone(&self) -> Self {
448        Split { v: self.v, pred: self.pred.clone(), finished: self.finished }
449    }
450}
451
452#[stable(feature = "rust1", since = "1.0.0")]
453impl<'a, T, P> Iterator for Split<'a, T, P>
454where
455    P: FnMut(&T) -> bool,
456{
457    type Item = &'a [T];
458
459    #[inline]
460    fn next(&mut self) -> Option<&'a [T]> {
461        if self.finished {
462            return None;
463        }
464
465        match self.v.iter().position(|x| (self.pred)(x)) {
466            None => self.finish(),
467            Some(idx) => {
468                let (left, right) =
469                    // SAFETY: if v.iter().position returns Some(idx), that
470                    // idx is definitely a valid index for v
471                    unsafe { (self.v.get_unchecked(..idx), self.v.get_unchecked(idx + 1..)) };
472                let ret = Some(left);
473                self.v = right;
474                ret
475            }
476        }
477    }
478
479    #[inline]
480    fn size_hint(&self) -> (usize, Option<usize>) {
481        if self.finished {
482            (0, Some(0))
483        } else {
484            // If the predicate doesn't match anything, we yield one slice.
485            // If it matches every element, we yield `len() + 1` empty slices.
486            (1, Some(self.v.len() + 1))
487        }
488    }
489}
490
491#[stable(feature = "rust1", since = "1.0.0")]
492impl<'a, T, P> DoubleEndedIterator for Split<'a, T, P>
493where
494    P: FnMut(&T) -> bool,
495{
496    #[inline]
497    fn next_back(&mut self) -> Option<&'a [T]> {
498        if self.finished {
499            return None;
500        }
501
502        match self.v.iter().rposition(|x| (self.pred)(x)) {
503            None => self.finish(),
504            Some(idx) => {
505                let (left, right) =
506                    // SAFETY: if v.iter().rposition returns Some(idx), then
507                    // idx is definitely a valid index for v
508                    unsafe { (self.v.get_unchecked(..idx), self.v.get_unchecked(idx + 1..)) };
509                let ret = Some(right);
510                self.v = left;
511                ret
512            }
513        }
514    }
515}
516
517impl<'a, T, P> SplitIter for Split<'a, T, P>
518where
519    P: FnMut(&T) -> bool,
520{
521    #[inline]
522    fn finish(&mut self) -> Option<&'a [T]> {
523        if self.finished {
524            None
525        } else {
526            self.finished = true;
527            Some(self.v)
528        }
529    }
530}
531
532#[stable(feature = "fused", since = "1.26.0")]
533impl<T, P> FusedIterator for Split<'_, T, P> where P: FnMut(&T) -> bool {}
534
535/// An iterator over subslices separated by elements that match a predicate
536/// function. Unlike `Split`, it contains the matched part as a terminator
537/// of the subslice.
538///
539/// This struct is created by the [`split_inclusive`] method on [slices].
540///
541/// # Example
542///
543/// ```
544/// let slice = [10, 40, 33, 20];
545/// let mut iter = slice.split_inclusive(|num| num % 3 == 0);
546/// assert_eq!(iter.next(), Some(&[10, 40, 33][..]));
547/// assert_eq!(iter.next(), Some(&[20][..]));
548/// assert_eq!(iter.next(), None);
549/// ```
550///
551/// [`split_inclusive`]: slice::split_inclusive
552/// [slices]: slice
553#[stable(feature = "split_inclusive", since = "1.51.0")]
554#[must_use = "iterators are lazy and do nothing unless consumed"]
555pub struct SplitInclusive<'a, T: 'a, P>
556where
557    P: FnMut(&T) -> bool,
558{
559    v: &'a [T],
560    pred: P,
561    finished: bool,
562}
563
564impl<'a, T: 'a, P: FnMut(&T) -> bool> SplitInclusive<'a, T, P> {
565    #[inline]
566    pub(super) fn new(slice: &'a [T], pred: P) -> Self {
567        let finished = slice.is_empty();
568        Self { v: slice, pred, finished }
569    }
570}
571
572#[stable(feature = "split_inclusive", since = "1.51.0")]
573impl<T: fmt::Debug, P> fmt::Debug for SplitInclusive<'_, T, P>
574where
575    P: FnMut(&T) -> bool,
576{
577    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
578        f.debug_struct("SplitInclusive")
579            .field("v", &self.v)
580            .field("finished", &self.finished)
581            .finish()
582    }
583}
584
585// FIXME(#26925) Remove in favor of `#[derive(Clone)]`
586#[stable(feature = "split_inclusive", since = "1.51.0")]
587impl<T, P> Clone for SplitInclusive<'_, T, P>
588where
589    P: Clone + FnMut(&T) -> bool,
590{
591    fn clone(&self) -> Self {
592        SplitInclusive { v: self.v, pred: self.pred.clone(), finished: self.finished }
593    }
594}
595
596#[stable(feature = "split_inclusive", since = "1.51.0")]
597impl<'a, T, P> Iterator for SplitInclusive<'a, T, P>
598where
599    P: FnMut(&T) -> bool,
600{
601    type Item = &'a [T];
602
603    #[inline]
604    fn next(&mut self) -> Option<&'a [T]> {
605        if self.finished {
606            return None;
607        }
608
609        let idx =
610            self.v.iter().position(|x| (self.pred)(x)).map(|idx| idx + 1).unwrap_or(self.v.len());
611        if idx == self.v.len() {
612            self.finished = true;
613        }
614        let ret = Some(&self.v[..idx]);
615        self.v = &self.v[idx..];
616        ret
617    }
618
619    #[inline]
620    fn size_hint(&self) -> (usize, Option<usize>) {
621        if self.finished {
622            (0, Some(0))
623        } else {
624            // If the predicate doesn't match anything, we yield one slice.
625            // If it matches every element, we yield `len()` one-element slices,
626            // or a single empty slice.
627            (1, Some(cmp::max(1, self.v.len())))
628        }
629    }
630}
631
632#[stable(feature = "split_inclusive", since = "1.51.0")]
633impl<'a, T, P> DoubleEndedIterator for SplitInclusive<'a, T, P>
634where
635    P: FnMut(&T) -> bool,
636{
637    #[inline]
638    fn next_back(&mut self) -> Option<&'a [T]> {
639        if self.finished {
640            return None;
641        }
642
643        // The last index of self.v is already checked and found to match
644        // by the last iteration, so we start searching a new match
645        // one index to the left.
646        let remainder = if self.v.is_empty() { &[] } else { &self.v[..(self.v.len() - 1)] };
647        let idx = remainder.iter().rposition(|x| (self.pred)(x)).map(|idx| idx + 1).unwrap_or(0);
648        if idx == 0 {
649            self.finished = true;
650        }
651        let ret = Some(&self.v[idx..]);
652        self.v = &self.v[..idx];
653        ret
654    }
655}
656
657#[stable(feature = "split_inclusive", since = "1.51.0")]
658impl<T, P> FusedIterator for SplitInclusive<'_, T, P> where P: FnMut(&T) -> bool {}
659
660/// An iterator over the mutable subslices of the vector which are separated
661/// by elements that match `pred`.
662///
663/// This struct is created by the [`split_mut`] method on [slices].
664///
665/// # Example
666///
667/// ```
668/// let mut v = [10, 40, 30, 20, 60, 50];
669/// let iter = v.split_mut(|num| *num % 3 == 0);
670/// ```
671///
672/// [`split_mut`]: slice::split_mut
673/// [slices]: slice
674#[stable(feature = "rust1", since = "1.0.0")]
675#[must_use = "iterators are lazy and do nothing unless consumed"]
676pub struct SplitMut<'a, T: 'a, P>
677where
678    P: FnMut(&T) -> bool,
679{
680    v: &'a mut [T],
681    pred: P,
682    finished: bool,
683}
684
685impl<'a, T: 'a, P: FnMut(&T) -> bool> SplitMut<'a, T, P> {
686    #[inline]
687    pub(super) fn new(slice: &'a mut [T], pred: P) -> Self {
688        Self { v: slice, pred, finished: false }
689    }
690}
691
692#[stable(feature = "core_impl_debug", since = "1.9.0")]
693impl<T: fmt::Debug, P> fmt::Debug for SplitMut<'_, T, P>
694where
695    P: FnMut(&T) -> bool,
696{
697    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
698        f.debug_struct("SplitMut").field("v", &self.v).field("finished", &self.finished).finish()
699    }
700}
701
702impl<'a, T, P> SplitIter for SplitMut<'a, T, P>
703where
704    P: FnMut(&T) -> bool,
705{
706    #[inline]
707    fn finish(&mut self) -> Option<&'a mut [T]> {
708        if self.finished {
709            None
710        } else {
711            self.finished = true;
712            Some(mem::take(&mut self.v))
713        }
714    }
715}
716
717#[stable(feature = "rust1", since = "1.0.0")]
718impl<'a, T, P> Iterator for SplitMut<'a, T, P>
719where
720    P: FnMut(&T) -> bool,
721{
722    type Item = &'a mut [T];
723
724    #[inline]
725    fn next(&mut self) -> Option<&'a mut [T]> {
726        if self.finished {
727            return None;
728        }
729
730        match self.v.iter().position(|x| (self.pred)(x)) {
731            None => self.finish(),
732            Some(idx) => {
733                let tmp = mem::take(&mut self.v);
734                // idx is the index of the element we are splitting on. We want to set self to the
735                // region after idx, and return the subslice before and not including idx.
736                // So first we split after idx
737                let (head, tail) = tmp.split_at_mut(idx + 1);
738                self.v = tail;
739                // Then return the subslice up to but not including the found element
740                Some(&mut head[..idx])
741            }
742        }
743    }
744
745    #[inline]
746    fn size_hint(&self) -> (usize, Option<usize>) {
747        if self.finished {
748            (0, Some(0))
749        } else {
750            // If the predicate doesn't match anything, we yield one slice.
751            // If it matches every element, we yield `len() + 1` empty slices.
752            (1, Some(self.v.len() + 1))
753        }
754    }
755}
756
757#[stable(feature = "rust1", since = "1.0.0")]
758impl<'a, T, P> DoubleEndedIterator for SplitMut<'a, T, P>
759where
760    P: FnMut(&T) -> bool,
761{
762    #[inline]
763    fn next_back(&mut self) -> Option<&'a mut [T]> {
764        if self.finished {
765            return None;
766        }
767
768        let idx_opt = {
769            // work around borrowck limitations
770            let pred = &mut self.pred;
771            self.v.iter().rposition(|x| (*pred)(x))
772        };
773        match idx_opt {
774            None => self.finish(),
775            Some(idx) => {
776                let tmp = mem::take(&mut self.v);
777                let (head, tail) = tmp.split_at_mut(idx);
778                self.v = head;
779                Some(&mut tail[1..])
780            }
781        }
782    }
783}
784
785#[stable(feature = "fused", since = "1.26.0")]
786impl<T, P> FusedIterator for SplitMut<'_, T, P> where P: FnMut(&T) -> bool {}
787
788/// An iterator over the mutable subslices of the vector which are separated
789/// by elements that match `pred`. Unlike `SplitMut`, it contains the matched
790/// parts in the ends of the subslices.
791///
792/// This struct is created by the [`split_inclusive_mut`] method on [slices].
793///
794/// # Example
795///
796/// ```
797/// let mut v = [10, 40, 30, 20, 60, 50];
798/// let iter = v.split_inclusive_mut(|num| *num % 3 == 0);
799/// ```
800///
801/// [`split_inclusive_mut`]: slice::split_inclusive_mut
802/// [slices]: slice
803#[stable(feature = "split_inclusive", since = "1.51.0")]
804#[must_use = "iterators are lazy and do nothing unless consumed"]
805pub struct SplitInclusiveMut<'a, T: 'a, P>
806where
807    P: FnMut(&T) -> bool,
808{
809    v: &'a mut [T],
810    pred: P,
811    finished: bool,
812}
813
814impl<'a, T: 'a, P: FnMut(&T) -> bool> SplitInclusiveMut<'a, T, P> {
815    #[inline]
816    pub(super) fn new(slice: &'a mut [T], pred: P) -> Self {
817        let finished = slice.is_empty();
818        Self { v: slice, pred, finished }
819    }
820}
821
822#[stable(feature = "split_inclusive", since = "1.51.0")]
823impl<T: fmt::Debug, P> fmt::Debug for SplitInclusiveMut<'_, T, P>
824where
825    P: FnMut(&T) -> bool,
826{
827    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
828        f.debug_struct("SplitInclusiveMut")
829            .field("v", &self.v)
830            .field("finished", &self.finished)
831            .finish()
832    }
833}
834
835#[stable(feature = "split_inclusive", since = "1.51.0")]
836impl<'a, T, P> Iterator for SplitInclusiveMut<'a, T, P>
837where
838    P: FnMut(&T) -> bool,
839{
840    type Item = &'a mut [T];
841
842    #[inline]
843    fn next(&mut self) -> Option<&'a mut [T]> {
844        if self.finished {
845            return None;
846        }
847
848        let idx_opt = {
849            // work around borrowck limitations
850            let pred = &mut self.pred;
851            self.v.iter().position(|x| (*pred)(x))
852        };
853        let idx = idx_opt.map(|idx| idx + 1).unwrap_or(self.v.len());
854        if idx == self.v.len() {
855            self.finished = true;
856        }
857        let tmp = mem::take(&mut self.v);
858        let (head, tail) = tmp.split_at_mut(idx);
859        self.v = tail;
860        Some(head)
861    }
862
863    #[inline]
864    fn size_hint(&self) -> (usize, Option<usize>) {
865        if self.finished {
866            (0, Some(0))
867        } else {
868            // If the predicate doesn't match anything, we yield one slice.
869            // If it matches every element, we yield `len()` one-element slices,
870            // or a single empty slice.
871            (1, Some(cmp::max(1, self.v.len())))
872        }
873    }
874}
875
876#[stable(feature = "split_inclusive", since = "1.51.0")]
877impl<'a, T, P> DoubleEndedIterator for SplitInclusiveMut<'a, T, P>
878where
879    P: FnMut(&T) -> bool,
880{
881    #[inline]
882    fn next_back(&mut self) -> Option<&'a mut [T]> {
883        if self.finished {
884            return None;
885        }
886
887        let idx_opt = if self.v.is_empty() {
888            None
889        } else {
890            // work around borrowck limitations
891            let pred = &mut self.pred;
892
893            // The last index of self.v is already checked and found to match
894            // by the last iteration, so we start searching a new match
895            // one index to the left.
896            let remainder = &self.v[..(self.v.len() - 1)];
897            remainder.iter().rposition(|x| (*pred)(x))
898        };
899        let idx = idx_opt.map(|idx| idx + 1).unwrap_or(0);
900        if idx == 0 {
901            self.finished = true;
902        }
903        let tmp = mem::take(&mut self.v);
904        let (head, tail) = tmp.split_at_mut(idx);
905        self.v = head;
906        Some(tail)
907    }
908}
909
910#[stable(feature = "split_inclusive", since = "1.51.0")]
911impl<T, P> FusedIterator for SplitInclusiveMut<'_, T, P> where P: FnMut(&T) -> bool {}
912
913/// An iterator over subslices separated by elements that match a predicate
914/// function, starting from the end of the slice.
915///
916/// This struct is created by the [`rsplit`] method on [slices].
917///
918/// # Example
919///
920/// ```
921/// let slice = [11, 22, 33, 0, 44, 55];
922/// let mut iter = slice.rsplit(|num| *num == 0);
923/// assert_eq!(iter.next(), Some(&[44, 55][..]));
924/// assert_eq!(iter.next(), Some(&[11, 22, 33][..]));
925/// assert_eq!(iter.next(), None);
926/// ```
927///
928/// [`rsplit`]: slice::rsplit
929/// [slices]: slice
930#[stable(feature = "slice_rsplit", since = "1.27.0")]
931#[must_use = "iterators are lazy and do nothing unless consumed"]
932pub struct RSplit<'a, T: 'a, P>
933where
934    P: FnMut(&T) -> bool,
935{
936    inner: Split<'a, T, P>,
937}
938
939impl<'a, T: 'a, P: FnMut(&T) -> bool> RSplit<'a, T, P> {
940    #[inline]
941    pub(super) fn new(slice: &'a [T], pred: P) -> Self {
942        Self { inner: Split::new(slice, pred) }
943    }
944}
945
946#[stable(feature = "slice_rsplit", since = "1.27.0")]
947impl<T: fmt::Debug, P> fmt::Debug for RSplit<'_, T, P>
948where
949    P: FnMut(&T) -> bool,
950{
951    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
952        f.debug_struct("RSplit")
953            .field("v", &self.inner.v)
954            .field("finished", &self.inner.finished)
955            .finish()
956    }
957}
958
959// FIXME(#26925) Remove in favor of `#[derive(Clone)]`
960#[stable(feature = "slice_rsplit", since = "1.27.0")]
961impl<T, P> Clone for RSplit<'_, T, P>
962where
963    P: Clone + FnMut(&T) -> bool,
964{
965    fn clone(&self) -> Self {
966        RSplit { inner: self.inner.clone() }
967    }
968}
969
970#[stable(feature = "slice_rsplit", since = "1.27.0")]
971impl<'a, T, P> Iterator for RSplit<'a, T, P>
972where
973    P: FnMut(&T) -> bool,
974{
975    type Item = &'a [T];
976
977    #[inline]
978    fn next(&mut self) -> Option<&'a [T]> {
979        self.inner.next_back()
980    }
981
982    #[inline]
983    fn size_hint(&self) -> (usize, Option<usize>) {
984        self.inner.size_hint()
985    }
986}
987
988#[stable(feature = "slice_rsplit", since = "1.27.0")]
989impl<'a, T, P> DoubleEndedIterator for RSplit<'a, T, P>
990where
991    P: FnMut(&T) -> bool,
992{
993    #[inline]
994    fn next_back(&mut self) -> Option<&'a [T]> {
995        self.inner.next()
996    }
997}
998
999#[stable(feature = "slice_rsplit", since = "1.27.0")]
1000impl<'a, T, P> SplitIter for RSplit<'a, T, P>
1001where
1002    P: FnMut(&T) -> bool,
1003{
1004    #[inline]
1005    fn finish(&mut self) -> Option<&'a [T]> {
1006        self.inner.finish()
1007    }
1008}
1009
1010#[stable(feature = "slice_rsplit", since = "1.27.0")]
1011impl<T, P> FusedIterator for RSplit<'_, T, P> where P: FnMut(&T) -> bool {}
1012
1013/// An iterator over the subslices of the vector which are separated
1014/// by elements that match `pred`, starting from the end of the slice.
1015///
1016/// This struct is created by the [`rsplit_mut`] method on [slices].
1017///
1018/// # Example
1019///
1020/// ```
1021/// let mut slice = [11, 22, 33, 0, 44, 55];
1022/// let iter = slice.rsplit_mut(|num| *num == 0);
1023/// ```
1024///
1025/// [`rsplit_mut`]: slice::rsplit_mut
1026/// [slices]: slice
1027#[stable(feature = "slice_rsplit", since = "1.27.0")]
1028#[must_use = "iterators are lazy and do nothing unless consumed"]
1029pub struct RSplitMut<'a, T: 'a, P>
1030where
1031    P: FnMut(&T) -> bool,
1032{
1033    inner: SplitMut<'a, T, P>,
1034}
1035
1036impl<'a, T: 'a, P: FnMut(&T) -> bool> RSplitMut<'a, T, P> {
1037    #[inline]
1038    pub(super) fn new(slice: &'a mut [T], pred: P) -> Self {
1039        Self { inner: SplitMut::new(slice, pred) }
1040    }
1041}
1042
1043#[stable(feature = "slice_rsplit", since = "1.27.0")]
1044impl<T: fmt::Debug, P> fmt::Debug for RSplitMut<'_, T, P>
1045where
1046    P: FnMut(&T) -> bool,
1047{
1048    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
1049        f.debug_struct("RSplitMut")
1050            .field("v", &self.inner.v)
1051            .field("finished", &self.inner.finished)
1052            .finish()
1053    }
1054}
1055
1056#[stable(feature = "slice_rsplit", since = "1.27.0")]
1057impl<'a, T, P> SplitIter for RSplitMut<'a, T, P>
1058where
1059    P: FnMut(&T) -> bool,
1060{
1061    #[inline]
1062    fn finish(&mut self) -> Option<&'a mut [T]> {
1063        self.inner.finish()
1064    }
1065}
1066
1067#[stable(feature = "slice_rsplit", since = "1.27.0")]
1068impl<'a, T, P> Iterator for RSplitMut<'a, T, P>
1069where
1070    P: FnMut(&T) -> bool,
1071{
1072    type Item = &'a mut [T];
1073
1074    #[inline]
1075    fn next(&mut self) -> Option<&'a mut [T]> {
1076        self.inner.next_back()
1077    }
1078
1079    #[inline]
1080    fn size_hint(&self) -> (usize, Option<usize>) {
1081        self.inner.size_hint()
1082    }
1083}
1084
1085#[stable(feature = "slice_rsplit", since = "1.27.0")]
1086impl<'a, T, P> DoubleEndedIterator for RSplitMut<'a, T, P>
1087where
1088    P: FnMut(&T) -> bool,
1089{
1090    #[inline]
1091    fn next_back(&mut self) -> Option<&'a mut [T]> {
1092        self.inner.next()
1093    }
1094}
1095
1096#[stable(feature = "slice_rsplit", since = "1.27.0")]
1097impl<T, P> FusedIterator for RSplitMut<'_, T, P> where P: FnMut(&T) -> bool {}
1098
1099/// An private iterator over subslices separated by elements that
1100/// match a predicate function, splitting at most a fixed number of
1101/// times.
1102#[derive(Debug)]
1103struct GenericSplitN<I> {
1104    iter: I,
1105    count: usize,
1106}
1107
1108impl<T, I: SplitIter<Item = T>> Iterator for GenericSplitN<I> {
1109    type Item = T;
1110
1111    #[inline]
1112    fn next(&mut self) -> Option<T> {
1113        match self.count {
1114            0 => None,
1115            1 => {
1116                self.count -= 1;
1117                self.iter.finish()
1118            }
1119            _ => {
1120                self.count -= 1;
1121                self.iter.next()
1122            }
1123        }
1124    }
1125
1126    #[inline]
1127    fn size_hint(&self) -> (usize, Option<usize>) {
1128        let (lower, upper_opt) = self.iter.size_hint();
1129        (
1130            cmp::min(self.count, lower),
1131            Some(upper_opt.map_or(self.count, |upper| cmp::min(self.count, upper))),
1132        )
1133    }
1134}
1135
1136/// An iterator over subslices separated by elements that match a predicate
1137/// function, limited to a given number of splits.
1138///
1139/// This struct is created by the [`splitn`] method on [slices].
1140///
1141/// # Example
1142///
1143/// ```
1144/// let slice = [10, 40, 30, 20, 60, 50];
1145/// let mut iter = slice.splitn(2, |num| *num % 3 == 0);
1146/// assert_eq!(iter.next(), Some(&[10, 40][..]));
1147/// assert_eq!(iter.next(), Some(&[20, 60, 50][..]));
1148/// assert_eq!(iter.next(), None);
1149/// ```
1150///
1151/// [`splitn`]: slice::splitn
1152/// [slices]: slice
1153#[stable(feature = "rust1", since = "1.0.0")]
1154#[must_use = "iterators are lazy and do nothing unless consumed"]
1155pub struct SplitN<'a, T: 'a, P>
1156where
1157    P: FnMut(&T) -> bool,
1158{
1159    inner: GenericSplitN<Split<'a, T, P>>,
1160}
1161
1162impl<'a, T: 'a, P: FnMut(&T) -> bool> SplitN<'a, T, P> {
1163    #[inline]
1164    pub(super) fn new(s: Split<'a, T, P>, n: usize) -> Self {
1165        Self { inner: GenericSplitN { iter: s, count: n } }
1166    }
1167}
1168
1169#[stable(feature = "core_impl_debug", since = "1.9.0")]
1170impl<T: fmt::Debug, P> fmt::Debug for SplitN<'_, T, P>
1171where
1172    P: FnMut(&T) -> bool,
1173{
1174    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
1175        f.debug_struct("SplitN").field("inner", &self.inner).finish()
1176    }
1177}
1178
1179/// An iterator over subslices separated by elements that match a
1180/// predicate function, limited to a given number of splits, starting
1181/// from the end of the slice.
1182///
1183/// This struct is created by the [`rsplitn`] method on [slices].
1184///
1185/// # Example
1186///
1187/// ```
1188/// let slice = [10, 40, 30, 20, 60, 50];
1189/// let mut iter = slice.rsplitn(2, |num| *num % 3 == 0);
1190/// assert_eq!(iter.next(), Some(&[50][..]));
1191/// assert_eq!(iter.next(), Some(&[10, 40, 30, 20][..]));
1192/// assert_eq!(iter.next(), None);
1193/// ```
1194///
1195/// [`rsplitn`]: slice::rsplitn
1196/// [slices]: slice
1197#[stable(feature = "rust1", since = "1.0.0")]
1198#[must_use = "iterators are lazy and do nothing unless consumed"]
1199pub struct RSplitN<'a, T: 'a, P>
1200where
1201    P: FnMut(&T) -> bool,
1202{
1203    inner: GenericSplitN<RSplit<'a, T, P>>,
1204}
1205
1206impl<'a, T: 'a, P: FnMut(&T) -> bool> RSplitN<'a, T, P> {
1207    #[inline]
1208    pub(super) fn new(s: RSplit<'a, T, P>, n: usize) -> Self {
1209        Self { inner: GenericSplitN { iter: s, count: n } }
1210    }
1211}
1212
1213#[stable(feature = "core_impl_debug", since = "1.9.0")]
1214impl<T: fmt::Debug, P> fmt::Debug for RSplitN<'_, T, P>
1215where
1216    P: FnMut(&T) -> bool,
1217{
1218    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
1219        f.debug_struct("RSplitN").field("inner", &self.inner).finish()
1220    }
1221}
1222
1223/// An iterator over subslices separated by elements that match a predicate
1224/// function, limited to a given number of splits.
1225///
1226/// This struct is created by the [`splitn_mut`] method on [slices].
1227///
1228/// # Example
1229///
1230/// ```
1231/// let mut slice = [10, 40, 30, 20, 60, 50];
1232/// let iter = slice.splitn_mut(2, |num| *num % 3 == 0);
1233/// ```
1234///
1235/// [`splitn_mut`]: slice::splitn_mut
1236/// [slices]: slice
1237#[stable(feature = "rust1", since = "1.0.0")]
1238#[must_use = "iterators are lazy and do nothing unless consumed"]
1239pub struct SplitNMut<'a, T: 'a, P>
1240where
1241    P: FnMut(&T) -> bool,
1242{
1243    inner: GenericSplitN<SplitMut<'a, T, P>>,
1244}
1245
1246impl<'a, T: 'a, P: FnMut(&T) -> bool> SplitNMut<'a, T, P> {
1247    #[inline]
1248    pub(super) fn new(s: SplitMut<'a, T, P>, n: usize) -> Self {
1249        Self { inner: GenericSplitN { iter: s, count: n } }
1250    }
1251}
1252
1253#[stable(feature = "core_impl_debug", since = "1.9.0")]
1254impl<T: fmt::Debug, P> fmt::Debug for SplitNMut<'_, T, P>
1255where
1256    P: FnMut(&T) -> bool,
1257{
1258    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
1259        f.debug_struct("SplitNMut").field("inner", &self.inner).finish()
1260    }
1261}
1262
1263/// An iterator over subslices separated by elements that match a
1264/// predicate function, limited to a given number of splits, starting
1265/// from the end of the slice.
1266///
1267/// This struct is created by the [`rsplitn_mut`] method on [slices].
1268///
1269/// # Example
1270///
1271/// ```
1272/// let mut slice = [10, 40, 30, 20, 60, 50];
1273/// let iter = slice.rsplitn_mut(2, |num| *num % 3 == 0);
1274/// ```
1275///
1276/// [`rsplitn_mut`]: slice::rsplitn_mut
1277/// [slices]: slice
1278#[stable(feature = "rust1", since = "1.0.0")]
1279#[must_use = "iterators are lazy and do nothing unless consumed"]
1280pub struct RSplitNMut<'a, T: 'a, P>
1281where
1282    P: FnMut(&T) -> bool,
1283{
1284    inner: GenericSplitN<RSplitMut<'a, T, P>>,
1285}
1286
1287impl<'a, T: 'a, P: FnMut(&T) -> bool> RSplitNMut<'a, T, P> {
1288    #[inline]
1289    pub(super) fn new(s: RSplitMut<'a, T, P>, n: usize) -> Self {
1290        Self { inner: GenericSplitN { iter: s, count: n } }
1291    }
1292}
1293
1294#[stable(feature = "core_impl_debug", since = "1.9.0")]
1295impl<T: fmt::Debug, P> fmt::Debug for RSplitNMut<'_, T, P>
1296where
1297    P: FnMut(&T) -> bool,
1298{
1299    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
1300        f.debug_struct("RSplitNMut").field("inner", &self.inner).finish()
1301    }
1302}
1303
1304forward_iterator! { SplitN: T, &'a [T] }
1305forward_iterator! { RSplitN: T, &'a [T] }
1306forward_iterator! { SplitNMut: T, &'a mut [T] }
1307forward_iterator! { RSplitNMut: T, &'a mut [T] }
1308
1309/// An iterator over overlapping subslices of length `size`.
1310///
1311/// This struct is created by the [`windows`] method on [slices].
1312///
1313/// # Example
1314///
1315/// ```
1316/// let slice = ['r', 'u', 's', 't'];
1317/// let mut iter = slice.windows(2);
1318/// assert_eq!(iter.next(), Some(&['r', 'u'][..]));
1319/// assert_eq!(iter.next(), Some(&['u', 's'][..]));
1320/// assert_eq!(iter.next(), Some(&['s', 't'][..]));
1321/// assert_eq!(iter.next(), None);
1322/// ```
1323///
1324/// [`windows`]: slice::windows
1325/// [slices]: slice
1326#[derive(Debug)]
1327#[stable(feature = "rust1", since = "1.0.0")]
1328#[must_use = "iterators are lazy and do nothing unless consumed"]
1329pub struct Windows<'a, T: 'a> {
1330    v: &'a [T],
1331    size: NonZero<usize>,
1332}
1333
1334impl<'a, T: 'a> Windows<'a, T> {
1335    #[inline]
1336    pub(super) const fn new(slice: &'a [T], size: NonZero<usize>) -> Self {
1337        Self { v: slice, size }
1338    }
1339}
1340
1341// FIXME(#26925) Remove in favor of `#[derive(Clone)]`
1342#[stable(feature = "rust1", since = "1.0.0")]
1343impl<T> Clone for Windows<'_, T> {
1344    fn clone(&self) -> Self {
1345        Windows { v: self.v, size: self.size }
1346    }
1347}
1348
1349#[stable(feature = "rust1", since = "1.0.0")]
1350impl<'a, T> Iterator for Windows<'a, T> {
1351    type Item = &'a [T];
1352
1353    #[inline]
1354    fn next(&mut self) -> Option<&'a [T]> {
1355        if self.size.get() > self.v.len() {
1356            None
1357        } else {
1358            let ret = Some(&self.v[..self.size.get()]);
1359            self.v = &self.v[1..];
1360            ret
1361        }
1362    }
1363
1364    #[inline]
1365    fn size_hint(&self) -> (usize, Option<usize>) {
1366        if self.size.get() > self.v.len() {
1367            (0, Some(0))
1368        } else {
1369            let size = self.v.len() - self.size.get() + 1;
1370            (size, Some(size))
1371        }
1372    }
1373
1374    #[inline]
1375    fn count(self) -> usize {
1376        self.len()
1377    }
1378
1379    #[inline]
1380    fn nth(&mut self, n: usize) -> Option<Self::Item> {
1381        let size = self.size.get();
1382        if let Some(rest) = self.v.get(n..)
1383            && let Some(nth) = rest.get(..size)
1384        {
1385            self.v = &rest[1..];
1386            Some(nth)
1387        } else {
1388            // setting length to 0 is cheaper than overwriting the pointer when assigning &[]
1389            self.v = &self.v[..0]; // cheaper than &[]
1390            None
1391        }
1392    }
1393
1394    #[inline]
1395    fn last(self) -> Option<Self::Item> {
1396        if self.size.get() > self.v.len() {
1397            None
1398        } else {
1399            let start = self.v.len() - self.size.get();
1400            Some(&self.v[start..])
1401        }
1402    }
1403
1404    unsafe fn __iterator_get_unchecked(&mut self, idx: usize) -> Self::Item {
1405        // SAFETY: since the caller guarantees that `i` is in bounds,
1406        // which means that `i` cannot overflow an `isize`, and the
1407        // slice created by `from_raw_parts` is a subslice of `self.v`
1408        // thus is guaranteed to be valid for the lifetime `'a` of `self.v`.
1409        unsafe { from_raw_parts(self.v.as_ptr().add(idx), self.size.get()) }
1410    }
1411}
1412
1413#[stable(feature = "rust1", since = "1.0.0")]
1414impl<'a, T> DoubleEndedIterator for Windows<'a, T> {
1415    #[inline]
1416    fn next_back(&mut self) -> Option<Self::Item> {
1417        self.nth_back(0)
1418    }
1419
1420    #[inline]
1421    fn nth_back(&mut self, n: usize) -> Option<Self::Item> {
1422        if let Some(end) = self.v.len().checked_sub(n)
1423            && let Some(start) = end.checked_sub(self.size.get())
1424        {
1425            let res = &self.v[start..end];
1426            self.v = &self.v[..end - 1];
1427            Some(res)
1428        } else {
1429            self.v = &self.v[..0]; // cheaper than &[]
1430            None
1431        }
1432    }
1433}
1434
1435#[stable(feature = "rust1", since = "1.0.0")]
1436impl<T> ExactSizeIterator for Windows<'_, T> {}
1437
1438#[unstable(feature = "trusted_len", issue = "37572")]
1439unsafe impl<T> TrustedLen for Windows<'_, T> {}
1440
1441#[stable(feature = "fused", since = "1.26.0")]
1442impl<T> FusedIterator for Windows<'_, T> {}
1443
1444#[doc(hidden)]
1445#[unstable(feature = "trusted_random_access", issue = "none")]
1446unsafe impl<'a, T> TrustedRandomAccess for Windows<'a, T> {}
1447
1448#[doc(hidden)]
1449#[unstable(feature = "trusted_random_access", issue = "none")]
1450unsafe impl<'a, T> TrustedRandomAccessNoCoerce for Windows<'a, T> {
1451    const MAY_HAVE_SIDE_EFFECT: bool = false;
1452}
1453
1454/// An iterator over a slice in (non-overlapping) chunks (`chunk_size` elements at a
1455/// time), starting at the beginning of the slice.
1456///
1457/// When the slice len is not evenly divided by the chunk size, the last slice
1458/// of the iteration will be the remainder.
1459///
1460/// This struct is created by the [`chunks`] method on [slices].
1461///
1462/// # Example
1463///
1464/// ```
1465/// let slice = ['l', 'o', 'r', 'e', 'm'];
1466/// let mut iter = slice.chunks(2);
1467/// assert_eq!(iter.next(), Some(&['l', 'o'][..]));
1468/// assert_eq!(iter.next(), Some(&['r', 'e'][..]));
1469/// assert_eq!(iter.next(), Some(&['m'][..]));
1470/// assert_eq!(iter.next(), None);
1471/// ```
1472///
1473/// [`chunks`]: slice::chunks
1474/// [slices]: slice
1475#[derive(Debug)]
1476#[stable(feature = "rust1", since = "1.0.0")]
1477#[must_use = "iterators are lazy and do nothing unless consumed"]
1478pub struct Chunks<'a, T: 'a> {
1479    v: &'a [T],
1480    chunk_size: usize,
1481}
1482
1483impl<'a, T: 'a> Chunks<'a, T> {
1484    #[inline]
1485    pub(super) const fn new(slice: &'a [T], size: usize) -> Self {
1486        Self { v: slice, chunk_size: size }
1487    }
1488}
1489
1490// FIXME(#26925) Remove in favor of `#[derive(Clone)]`
1491#[stable(feature = "rust1", since = "1.0.0")]
1492impl<T> Clone for Chunks<'_, T> {
1493    fn clone(&self) -> Self {
1494        Chunks { v: self.v, chunk_size: self.chunk_size }
1495    }
1496}
1497
1498#[stable(feature = "rust1", since = "1.0.0")]
1499impl<'a, T> Iterator for Chunks<'a, T> {
1500    type Item = &'a [T];
1501
1502    #[inline]
1503    fn next(&mut self) -> Option<&'a [T]> {
1504        if self.v.is_empty() {
1505            None
1506        } else {
1507            let chunksz = cmp::min(self.v.len(), self.chunk_size);
1508            let (fst, snd) = self.v.split_at(chunksz);
1509            self.v = snd;
1510            Some(fst)
1511        }
1512    }
1513
1514    #[inline]
1515    fn size_hint(&self) -> (usize, Option<usize>) {
1516        if self.v.is_empty() {
1517            (0, Some(0))
1518        } else {
1519            let n = self.v.len().div_ceil(self.chunk_size);
1520            (n, Some(n))
1521        }
1522    }
1523
1524    #[inline]
1525    fn count(self) -> usize {
1526        self.len()
1527    }
1528
1529    #[inline]
1530    fn nth(&mut self, n: usize) -> Option<Self::Item> {
1531        if let Some(start) = n.checked_mul(self.chunk_size)
1532            && start < self.v.len()
1533        {
1534            let rest = &self.v[start..];
1535            let (chunk, rest) = rest.split_at(self.chunk_size.min(rest.len()));
1536            self.v = rest;
1537            Some(chunk)
1538        } else {
1539            self.v = &self.v[..0]; // cheaper than &[]
1540            None
1541        }
1542    }
1543
1544    #[inline]
1545    fn last(self) -> Option<Self::Item> {
1546        if self.v.is_empty() {
1547            None
1548        } else {
1549            let start = (self.v.len() - 1) / self.chunk_size * self.chunk_size;
1550            Some(&self.v[start..])
1551        }
1552    }
1553
1554    unsafe fn __iterator_get_unchecked(&mut self, idx: usize) -> Self::Item {
1555        let start = idx * self.chunk_size;
1556        // SAFETY: the caller guarantees that `i` is in bounds,
1557        // which means that `start` must be in bounds of the
1558        // underlying `self.v` slice, and we made sure that `len`
1559        // is also in bounds of `self.v`. Thus, `start` cannot overflow
1560        // an `isize`, and the slice constructed by `from_raw_parts`
1561        // is a subslice of `self.v` which is guaranteed to be valid
1562        // for the lifetime `'a` of `self.v`.
1563        unsafe {
1564            let len = cmp::min(self.v.len().unchecked_sub(start), self.chunk_size);
1565            from_raw_parts(self.v.as_ptr().add(start), len)
1566        }
1567    }
1568}
1569
1570#[stable(feature = "rust1", since = "1.0.0")]
1571impl<'a, T> DoubleEndedIterator for Chunks<'a, T> {
1572    #[inline]
1573    fn next_back(&mut self) -> Option<&'a [T]> {
1574        if self.v.is_empty() {
1575            None
1576        } else {
1577            let remainder = self.v.len() % self.chunk_size;
1578            let chunksz = if remainder != 0 { remainder } else { self.chunk_size };
1579            // SAFETY: split_at_unchecked requires the argument be less than or
1580            // equal to the length. This is guaranteed, but subtle: `chunksz`
1581            // will always either be `self.v.len() % self.chunk_size`, which
1582            // will always evaluate to strictly less than `self.v.len()` (or
1583            // panic, in the case that `self.chunk_size` is zero), or it can be
1584            // `self.chunk_size`, in the case that the length is exactly
1585            // divisible by the chunk size.
1586            //
1587            // While it seems like using `self.chunk_size` in this case could
1588            // lead to a value greater than `self.v.len()`, it cannot: if
1589            // `self.chunk_size` were greater than `self.v.len()`, then
1590            // `self.v.len() % self.chunk_size` would return nonzero (note that
1591            // in this branch of the `if`, we already know that `self.v` is
1592            // non-empty).
1593            let (fst, snd) = unsafe { self.v.split_at_unchecked(self.v.len() - chunksz) };
1594            self.v = fst;
1595            Some(snd)
1596        }
1597    }
1598
1599    #[inline]
1600    fn nth_back(&mut self, n: usize) -> Option<Self::Item> {
1601        let len = self.len();
1602        if n < len {
1603            let start = (len - 1 - n) * self.chunk_size;
1604            let end = start + (self.v.len() - start).min(self.chunk_size);
1605            let nth_back = &self.v[start..end];
1606            self.v = &self.v[..start];
1607            Some(nth_back)
1608        } else {
1609            self.v = &self.v[..0]; // cheaper than &[]
1610            None
1611        }
1612    }
1613}
1614
1615#[stable(feature = "rust1", since = "1.0.0")]
1616impl<T> ExactSizeIterator for Chunks<'_, T> {}
1617
1618#[unstable(feature = "trusted_len", issue = "37572")]
1619unsafe impl<T> TrustedLen for Chunks<'_, T> {}
1620
1621#[stable(feature = "fused", since = "1.26.0")]
1622impl<T> FusedIterator for Chunks<'_, T> {}
1623
1624#[doc(hidden)]
1625#[unstable(feature = "trusted_random_access", issue = "none")]
1626unsafe impl<'a, T> TrustedRandomAccess for Chunks<'a, T> {}
1627
1628#[doc(hidden)]
1629#[unstable(feature = "trusted_random_access", issue = "none")]
1630unsafe impl<'a, T> TrustedRandomAccessNoCoerce for Chunks<'a, T> {
1631    const MAY_HAVE_SIDE_EFFECT: bool = false;
1632}
1633
1634/// An iterator over a slice in (non-overlapping) mutable chunks (`chunk_size`
1635/// elements at a time), starting at the beginning of the slice.
1636///
1637/// When the slice len is not evenly divided by the chunk size, the last slice
1638/// of the iteration will be the remainder.
1639///
1640/// This struct is created by the [`chunks_mut`] method on [slices].
1641///
1642/// # Example
1643///
1644/// ```
1645/// let mut slice = ['l', 'o', 'r', 'e', 'm'];
1646/// let iter = slice.chunks_mut(2);
1647/// ```
1648///
1649/// [`chunks_mut`]: slice::chunks_mut
1650/// [slices]: slice
1651#[derive(Debug)]
1652#[stable(feature = "rust1", since = "1.0.0")]
1653#[must_use = "iterators are lazy and do nothing unless consumed"]
1654pub struct ChunksMut<'a, T: 'a> {
1655    /// # Safety
1656    /// This slice pointer must point at a valid region of `T` with at least length `v.len()`. Normally,
1657    /// those requirements would mean that we could instead use a `&mut [T]` here, but we cannot
1658    /// because `__iterator_get_unchecked` needs to return `&mut [T]`, which guarantees certain aliasing
1659    /// properties that we cannot uphold if we hold on to the full original `&mut [T]`. Wrapping a raw
1660    /// slice instead lets us hand out non-overlapping `&mut [T]` subslices of the slice we wrap.
1661    v: *mut [T],
1662    chunk_size: usize,
1663    _marker: PhantomData<&'a mut T>,
1664}
1665
1666impl<'a, T: 'a> ChunksMut<'a, T> {
1667    #[inline]
1668    pub(super) const fn new(slice: &'a mut [T], size: usize) -> Self {
1669        Self { v: slice, chunk_size: size, _marker: PhantomData }
1670    }
1671}
1672
1673#[stable(feature = "rust1", since = "1.0.0")]
1674impl<'a, T> Iterator for ChunksMut<'a, T> {
1675    type Item = &'a mut [T];
1676
1677    #[inline]
1678    fn next(&mut self) -> Option<&'a mut [T]> {
1679        if self.v.is_empty() {
1680            None
1681        } else {
1682            let sz = cmp::min(self.v.len(), self.chunk_size);
1683            // SAFETY: The self.v contract ensures that any split_at_mut is valid.
1684            let (head, tail) = unsafe { self.v.split_at_mut(sz) };
1685            self.v = tail;
1686            // SAFETY: Nothing else points to or will point to the contents of this slice.
1687            Some(unsafe { &mut *head })
1688        }
1689    }
1690
1691    #[inline]
1692    fn size_hint(&self) -> (usize, Option<usize>) {
1693        if self.v.is_empty() {
1694            (0, Some(0))
1695        } else {
1696            let n = self.v.len().div_ceil(self.chunk_size);
1697            (n, Some(n))
1698        }
1699    }
1700
1701    #[inline]
1702    fn count(self) -> usize {
1703        self.len()
1704    }
1705
1706    #[inline]
1707    fn nth(&mut self, n: usize) -> Option<&'a mut [T]> {
1708        if let Some(start) = n.checked_mul(self.chunk_size)
1709            && start < self.v.len()
1710        {
1711            // SAFETY: `start < self.v.len()` ensures this is in bounds
1712            let (_, rest) = unsafe { self.v.split_at_mut(start) };
1713            // SAFETY: `.min(rest.len()` ensures this is in bounds
1714            let (chunk, rest) = unsafe { rest.split_at_mut(self.chunk_size.min(rest.len())) };
1715            self.v = rest;
1716            // SAFETY: Nothing else points to or will point to the contents of this slice.
1717            Some(unsafe { &mut *chunk })
1718        } else {
1719            self.v = &mut [];
1720            None
1721        }
1722    }
1723
1724    #[inline]
1725    fn last(self) -> Option<Self::Item> {
1726        if self.v.is_empty() {
1727            None
1728        } else {
1729            let start = (self.v.len() - 1) / self.chunk_size * self.chunk_size;
1730            // SAFETY: Nothing else points to or will point to the contents of this slice.
1731            Some(unsafe { &mut *self.v.get_unchecked_mut(start..) })
1732        }
1733    }
1734
1735    unsafe fn __iterator_get_unchecked(&mut self, idx: usize) -> Self::Item {
1736        let start = idx * self.chunk_size;
1737        // SAFETY: see comments for `Chunks::__iterator_get_unchecked` and `self.v`.
1738        //
1739        // Also note that the caller also guarantees that we're never called
1740        // with the same index again, and that no other methods that will
1741        // access this subslice are called, so it is valid for the returned
1742        // slice to be mutable.
1743        unsafe {
1744            let len = cmp::min(self.v.len().unchecked_sub(start), self.chunk_size);
1745            from_raw_parts_mut(self.v.as_mut_ptr().add(start), len)
1746        }
1747    }
1748}
1749
1750#[stable(feature = "rust1", since = "1.0.0")]
1751impl<'a, T> DoubleEndedIterator for ChunksMut<'a, T> {
1752    #[inline]
1753    fn next_back(&mut self) -> Option<&'a mut [T]> {
1754        if self.v.is_empty() {
1755            None
1756        } else {
1757            let remainder = self.v.len() % self.chunk_size;
1758            let sz = if remainder != 0 { remainder } else { self.chunk_size };
1759            let len = self.v.len();
1760            // SAFETY: Similar to `Chunks::next_back`
1761            let (head, tail) = unsafe { self.v.split_at_mut_unchecked(len - sz) };
1762            self.v = head;
1763            // SAFETY: Nothing else points to or will point to the contents of this slice.
1764            Some(unsafe { &mut *tail })
1765        }
1766    }
1767
1768    #[inline]
1769    fn nth_back(&mut self, n: usize) -> Option<Self::Item> {
1770        let len = self.len();
1771        if n < len {
1772            let start = (len - 1 - n) * self.chunk_size;
1773            let end = match start.checked_add(self.chunk_size) {
1774                Some(res) => cmp::min(self.v.len(), res),
1775                None => self.v.len(),
1776            };
1777            // SAFETY: The self.v contract ensures that any split_at_mut is valid.
1778            let (temp, _tail) = unsafe { self.v.split_at_mut(end) };
1779            // SAFETY: The self.v contract ensures that any split_at_mut is valid.
1780            let (head, nth_back) = unsafe { temp.split_at_mut(start) };
1781            self.v = head;
1782            // SAFETY: Nothing else points to or will point to the contents of this slice.
1783            Some(unsafe { &mut *nth_back })
1784        } else {
1785            self.v = &mut [];
1786            None
1787        }
1788    }
1789}
1790
1791#[stable(feature = "rust1", since = "1.0.0")]
1792impl<T> ExactSizeIterator for ChunksMut<'_, T> {}
1793
1794#[unstable(feature = "trusted_len", issue = "37572")]
1795unsafe impl<T> TrustedLen for ChunksMut<'_, T> {}
1796
1797#[stable(feature = "fused", since = "1.26.0")]
1798impl<T> FusedIterator for ChunksMut<'_, T> {}
1799
1800#[doc(hidden)]
1801#[unstable(feature = "trusted_random_access", issue = "none")]
1802unsafe impl<'a, T> TrustedRandomAccess for ChunksMut<'a, T> {}
1803
1804#[doc(hidden)]
1805#[unstable(feature = "trusted_random_access", issue = "none")]
1806unsafe impl<'a, T> TrustedRandomAccessNoCoerce for ChunksMut<'a, T> {
1807    const MAY_HAVE_SIDE_EFFECT: bool = false;
1808}
1809
1810#[stable(feature = "rust1", since = "1.0.0")]
1811unsafe impl<T> Send for ChunksMut<'_, T> where T: Send {}
1812
1813#[stable(feature = "rust1", since = "1.0.0")]
1814unsafe impl<T> Sync for ChunksMut<'_, T> where T: Sync {}
1815
1816/// An iterator over a slice in (non-overlapping) chunks (`chunk_size` elements at a
1817/// time), starting at the beginning of the slice.
1818///
1819/// When the slice len is not evenly divided by the chunk size, the last
1820/// up to `chunk_size-1` elements will be omitted but can be retrieved from
1821/// the [`remainder`] function from the iterator.
1822///
1823/// This struct is created by the [`chunks_exact`] method on [slices].
1824///
1825/// # Example
1826///
1827/// ```
1828/// let slice = ['l', 'o', 'r', 'e', 'm'];
1829/// let mut iter = slice.chunks_exact(2);
1830/// assert_eq!(iter.next(), Some(&['l', 'o'][..]));
1831/// assert_eq!(iter.next(), Some(&['r', 'e'][..]));
1832/// assert_eq!(iter.next(), None);
1833/// ```
1834///
1835/// [`chunks_exact`]: slice::chunks_exact
1836/// [`remainder`]: ChunksExact::remainder
1837/// [slices]: slice
1838#[derive(Debug)]
1839#[stable(feature = "chunks_exact", since = "1.31.0")]
1840#[must_use = "iterators are lazy and do nothing unless consumed"]
1841pub struct ChunksExact<'a, T: 'a> {
1842    v: &'a [T],
1843    rem: &'a [T],
1844    chunk_size: usize,
1845}
1846
1847impl<'a, T> ChunksExact<'a, T> {
1848    #[inline]
1849    pub(super) const fn new(slice: &'a [T], chunk_size: usize) -> Self {
1850        let rem = slice.len() % chunk_size;
1851        let fst_len = slice.len() - rem;
1852        // SAFETY: 0 <= fst_len <= slice.len() by construction above
1853        let (fst, snd) = unsafe { slice.split_at_unchecked(fst_len) };
1854        Self { v: fst, rem: snd, chunk_size }
1855    }
1856
1857    /// Returns the remainder of the original slice that is not going to be
1858    /// returned by the iterator. The returned slice has at most `chunk_size-1`
1859    /// elements.
1860    ///
1861    /// # Example
1862    ///
1863    /// ```
1864    /// let slice = ['l', 'o', 'r', 'e', 'm'];
1865    /// let mut iter = slice.chunks_exact(2);
1866    /// assert_eq!(iter.remainder(), &['m'][..]);
1867    /// assert_eq!(iter.next(), Some(&['l', 'o'][..]));
1868    /// assert_eq!(iter.remainder(), &['m'][..]);
1869    /// assert_eq!(iter.next(), Some(&['r', 'e'][..]));
1870    /// assert_eq!(iter.remainder(), &['m'][..]);
1871    /// assert_eq!(iter.next(), None);
1872    /// assert_eq!(iter.remainder(), &['m'][..]);
1873    /// ```
1874    #[must_use]
1875    #[stable(feature = "chunks_exact", since = "1.31.0")]
1876    pub fn remainder(&self) -> &'a [T] {
1877        self.rem
1878    }
1879}
1880
1881// FIXME(#26925) Remove in favor of `#[derive(Clone)]`
1882#[stable(feature = "chunks_exact", since = "1.31.0")]
1883impl<T> Clone for ChunksExact<'_, T> {
1884    fn clone(&self) -> Self {
1885        ChunksExact { v: self.v, rem: self.rem, chunk_size: self.chunk_size }
1886    }
1887}
1888
1889#[stable(feature = "chunks_exact", since = "1.31.0")]
1890impl<'a, T> Iterator for ChunksExact<'a, T> {
1891    type Item = &'a [T];
1892
1893    #[inline]
1894    fn next(&mut self) -> Option<&'a [T]> {
1895        self.v.split_at_checked(self.chunk_size).and_then(|(chunk, rest)| {
1896            self.v = rest;
1897            Some(chunk)
1898        })
1899    }
1900
1901    #[inline]
1902    fn size_hint(&self) -> (usize, Option<usize>) {
1903        let n = self.v.len() / self.chunk_size;
1904        (n, Some(n))
1905    }
1906
1907    #[inline]
1908    fn count(self) -> usize {
1909        self.len()
1910    }
1911
1912    #[inline]
1913    fn nth(&mut self, n: usize) -> Option<Self::Item> {
1914        if let Some(start) = n.checked_mul(self.chunk_size)
1915            && start < self.v.len()
1916        {
1917            self.v = &self.v[start..];
1918            self.next()
1919        } else {
1920            self.v = &self.v[..0]; // cheaper than &[]
1921            None
1922        }
1923    }
1924
1925    #[inline]
1926    fn last(mut self) -> Option<Self::Item> {
1927        self.next_back()
1928    }
1929
1930    unsafe fn __iterator_get_unchecked(&mut self, idx: usize) -> Self::Item {
1931        let start = idx * self.chunk_size;
1932        // SAFETY: mostly identical to `Chunks::__iterator_get_unchecked`.
1933        unsafe { from_raw_parts(self.v.as_ptr().add(start), self.chunk_size) }
1934    }
1935}
1936
1937#[stable(feature = "chunks_exact", since = "1.31.0")]
1938impl<'a, T> DoubleEndedIterator for ChunksExact<'a, T> {
1939    #[inline]
1940    fn next_back(&mut self) -> Option<&'a [T]> {
1941        if self.v.len() < self.chunk_size {
1942            None
1943        } else {
1944            let (fst, snd) = self.v.split_at(self.v.len() - self.chunk_size);
1945            self.v = fst;
1946            Some(snd)
1947        }
1948    }
1949
1950    #[inline]
1951    fn nth_back(&mut self, n: usize) -> Option<Self::Item> {
1952        let len = self.len();
1953        if n < len {
1954            let start = (len - 1 - n) * self.chunk_size;
1955            let end = start + self.chunk_size;
1956            let nth_back = &self.v[start..end];
1957            self.v = &self.v[..start];
1958            Some(nth_back)
1959        } else {
1960            self.v = &self.v[..0]; // cheaper than &[]
1961            None
1962        }
1963    }
1964}
1965
1966#[stable(feature = "chunks_exact", since = "1.31.0")]
1967impl<T> ExactSizeIterator for ChunksExact<'_, T> {
1968    fn is_empty(&self) -> bool {
1969        self.v.is_empty()
1970    }
1971}
1972
1973#[unstable(feature = "trusted_len", issue = "37572")]
1974unsafe impl<T> TrustedLen for ChunksExact<'_, T> {}
1975
1976#[stable(feature = "chunks_exact", since = "1.31.0")]
1977impl<T> FusedIterator for ChunksExact<'_, T> {}
1978
1979#[doc(hidden)]
1980#[unstable(feature = "trusted_random_access", issue = "none")]
1981unsafe impl<'a, T> TrustedRandomAccess for ChunksExact<'a, T> {}
1982
1983#[doc(hidden)]
1984#[unstable(feature = "trusted_random_access", issue = "none")]
1985unsafe impl<'a, T> TrustedRandomAccessNoCoerce for ChunksExact<'a, T> {
1986    const MAY_HAVE_SIDE_EFFECT: bool = false;
1987}
1988
1989/// An iterator over a slice in (non-overlapping) mutable chunks (`chunk_size`
1990/// elements at a time), starting at the beginning of the slice.
1991///
1992/// When the slice len is not evenly divided by the chunk size, the last up to
1993/// `chunk_size-1` elements will be omitted but can be retrieved from the
1994/// [`into_remainder`] function from the iterator.
1995///
1996/// This struct is created by the [`chunks_exact_mut`] method on [slices].
1997///
1998/// # Example
1999///
2000/// ```
2001/// let mut slice = ['l', 'o', 'r', 'e', 'm'];
2002/// let iter = slice.chunks_exact_mut(2);
2003/// ```
2004///
2005/// [`chunks_exact_mut`]: slice::chunks_exact_mut
2006/// [`into_remainder`]: ChunksExactMut::into_remainder
2007/// [slices]: slice
2008#[derive(Debug)]
2009#[stable(feature = "chunks_exact", since = "1.31.0")]
2010#[must_use = "iterators are lazy and do nothing unless consumed"]
2011pub struct ChunksExactMut<'a, T: 'a> {
2012    /// # Safety
2013    /// This slice pointer must point at a valid region of `T` with at least length `v.len()`. Normally,
2014    /// those requirements would mean that we could instead use a `&mut [T]` here, but we cannot
2015    /// because `__iterator_get_unchecked` needs to return `&mut [T]`, which guarantees certain aliasing
2016    /// properties that we cannot uphold if we hold on to the full original `&mut [T]`. Wrapping a raw
2017    /// slice instead lets us hand out non-overlapping `&mut [T]` subslices of the slice we wrap.
2018    v: *mut [T],
2019    rem: &'a mut [T], // The iterator never yields from here, so this can be unique
2020    chunk_size: usize,
2021    _marker: PhantomData<&'a mut T>,
2022}
2023
2024impl<'a, T> ChunksExactMut<'a, T> {
2025    #[inline]
2026    pub(super) const fn new(slice: &'a mut [T], chunk_size: usize) -> Self {
2027        let rem = slice.len() % chunk_size;
2028        let fst_len = slice.len() - rem;
2029        // SAFETY: 0 <= fst_len <= slice.len() by construction above
2030        let (fst, snd) = unsafe { slice.split_at_mut_unchecked(fst_len) };
2031        Self { v: fst, rem: snd, chunk_size, _marker: PhantomData }
2032    }
2033
2034    /// Returns the remainder of the original slice that is not going to be
2035    /// returned by the iterator. The returned slice has at most `chunk_size-1`
2036    /// elements.
2037    #[must_use = "`self` will be dropped if the result is not used"]
2038    #[stable(feature = "chunks_exact", since = "1.31.0")]
2039    pub fn into_remainder(self) -> &'a mut [T] {
2040        self.rem
2041    }
2042}
2043
2044#[stable(feature = "chunks_exact", since = "1.31.0")]
2045impl<'a, T> Iterator for ChunksExactMut<'a, T> {
2046    type Item = &'a mut [T];
2047
2048    #[inline]
2049    fn next(&mut self) -> Option<&'a mut [T]> {
2050        // SAFETY: we have `&mut self`, so are allowed to temporarily materialize a mut slice
2051        unsafe { &mut *self.v }.split_at_mut_checked(self.chunk_size).and_then(|(chunk, rest)| {
2052            self.v = rest;
2053            Some(chunk)
2054        })
2055    }
2056
2057    #[inline]
2058    fn size_hint(&self) -> (usize, Option<usize>) {
2059        let n = self.v.len() / self.chunk_size;
2060        (n, Some(n))
2061    }
2062
2063    #[inline]
2064    fn count(self) -> usize {
2065        self.len()
2066    }
2067
2068    #[inline]
2069    fn nth(&mut self, n: usize) -> Option<&'a mut [T]> {
2070        if let Some(start) = n.checked_mul(self.chunk_size)
2071            && start < self.v.len()
2072        {
2073            // SAFETY: `start < self.v.len()`
2074            self.v = unsafe { self.v.split_at_mut(start).1 };
2075            self.next()
2076        } else {
2077            self.v = &mut [];
2078            None
2079        }
2080    }
2081
2082    #[inline]
2083    fn last(mut self) -> Option<Self::Item> {
2084        self.next_back()
2085    }
2086
2087    unsafe fn __iterator_get_unchecked(&mut self, idx: usize) -> Self::Item {
2088        let start = idx * self.chunk_size;
2089        // SAFETY: see comments for `Chunks::__iterator_get_unchecked` and `self.v`.
2090        unsafe { from_raw_parts_mut(self.v.as_mut_ptr().add(start), self.chunk_size) }
2091    }
2092}
2093
2094#[stable(feature = "chunks_exact", since = "1.31.0")]
2095impl<'a, T> DoubleEndedIterator for ChunksExactMut<'a, T> {
2096    #[inline]
2097    fn next_back(&mut self) -> Option<&'a mut [T]> {
2098        if self.v.len() < self.chunk_size {
2099            None
2100        } else {
2101            // SAFETY: This subtraction is inbounds because of the check above
2102            let (head, tail) = unsafe { self.v.split_at_mut(self.v.len() - self.chunk_size) };
2103            self.v = head;
2104            // SAFETY: Nothing else points to or will point to the contents of this slice.
2105            Some(unsafe { &mut *tail })
2106        }
2107    }
2108
2109    #[inline]
2110    fn nth_back(&mut self, n: usize) -> Option<Self::Item> {
2111        let len = self.len();
2112        if n < len {
2113            let start = (len - 1 - n) * self.chunk_size;
2114            let end = start + self.chunk_size;
2115            // SAFETY: The self.v contract ensures that any split_at_mut is valid.
2116            let (temp, _tail) = unsafe { mem::replace(&mut self.v, &mut []).split_at_mut(end) };
2117            // SAFETY: The self.v contract ensures that any split_at_mut is valid.
2118            let (head, nth_back) = unsafe { temp.split_at_mut(start) };
2119            self.v = head;
2120            // SAFETY: Nothing else points to or will point to the contents of this slice.
2121            Some(unsafe { &mut *nth_back })
2122        } else {
2123            self.v = &mut [];
2124            None
2125        }
2126    }
2127}
2128
2129#[stable(feature = "chunks_exact", since = "1.31.0")]
2130impl<T> ExactSizeIterator for ChunksExactMut<'_, T> {
2131    fn is_empty(&self) -> bool {
2132        self.v.is_empty()
2133    }
2134}
2135
2136#[unstable(feature = "trusted_len", issue = "37572")]
2137unsafe impl<T> TrustedLen for ChunksExactMut<'_, T> {}
2138
2139#[stable(feature = "chunks_exact", since = "1.31.0")]
2140impl<T> FusedIterator for ChunksExactMut<'_, T> {}
2141
2142#[doc(hidden)]
2143#[unstable(feature = "trusted_random_access", issue = "none")]
2144unsafe impl<'a, T> TrustedRandomAccess for ChunksExactMut<'a, T> {}
2145
2146#[doc(hidden)]
2147#[unstable(feature = "trusted_random_access", issue = "none")]
2148unsafe impl<'a, T> TrustedRandomAccessNoCoerce for ChunksExactMut<'a, T> {
2149    const MAY_HAVE_SIDE_EFFECT: bool = false;
2150}
2151
2152#[stable(feature = "chunks_exact", since = "1.31.0")]
2153unsafe impl<T> Send for ChunksExactMut<'_, T> where T: Send {}
2154
2155#[stable(feature = "chunks_exact", since = "1.31.0")]
2156unsafe impl<T> Sync for ChunksExactMut<'_, T> where T: Sync {}
2157
2158/// A windowed iterator over a slice in overlapping chunks (`N` elements at a
2159/// time), starting at the beginning of the slice
2160///
2161/// This struct is created by the [`array_windows`] method on [slices].
2162///
2163/// # Example
2164///
2165/// ```
2166/// let slice = [0, 1, 2, 3];
2167/// let mut iter = slice.array_windows::<2>();
2168/// assert_eq!(iter.next(), Some(&[0, 1]));
2169/// assert_eq!(iter.next(), Some(&[1, 2]));
2170/// assert_eq!(iter.next(), Some(&[2, 3]));
2171/// assert_eq!(iter.next(), None);
2172/// ```
2173///
2174/// [`array_windows`]: slice::array_windows
2175/// [slices]: slice
2176#[derive(Debug)]
2177#[stable(feature = "array_windows", since = "1.94.0")]
2178#[must_use = "iterators are lazy and do nothing unless consumed"]
2179pub struct ArrayWindows<'a, T: 'a, const N: usize> {
2180    v: &'a [T],
2181}
2182
2183impl<'a, T: 'a, const N: usize> ArrayWindows<'a, T, N> {
2184    #[inline]
2185    pub(super) const fn new(slice: &'a [T]) -> Self {
2186        Self { v: slice }
2187    }
2188}
2189
2190// FIXME(#26925) Remove in favor of `#[derive(Clone)]`
2191#[stable(feature = "array_windows", since = "1.94.0")]
2192impl<T, const N: usize> Clone for ArrayWindows<'_, T, N> {
2193    fn clone(&self) -> Self {
2194        Self { v: self.v }
2195    }
2196}
2197
2198#[stable(feature = "array_windows", since = "1.94.0")]
2199impl<'a, T, const N: usize> Iterator for ArrayWindows<'a, T, N> {
2200    type Item = &'a [T; N];
2201
2202    #[inline]
2203    fn next(&mut self) -> Option<Self::Item> {
2204        let ret = self.v.first_chunk();
2205        if ret.is_some() {
2206            self.v = &self.v[1..];
2207        }
2208        ret
2209    }
2210
2211    #[inline]
2212    fn size_hint(&self) -> (usize, Option<usize>) {
2213        let size = self.v.len().saturating_sub(N - 1);
2214        (size, Some(size))
2215    }
2216
2217    #[inline]
2218    fn count(self) -> usize {
2219        self.len()
2220    }
2221
2222    #[inline]
2223    fn nth(&mut self, n: usize) -> Option<Self::Item> {
2224        let idx = n.min(self.v.len());
2225        self.v = &self.v[idx..];
2226        self.next()
2227    }
2228
2229    #[inline]
2230    fn last(self) -> Option<Self::Item> {
2231        self.v.last_chunk()
2232    }
2233
2234    unsafe fn __iterator_get_unchecked(&mut self, idx: usize) -> Self::Item {
2235        // SAFETY: since the caller guarantees that `idx` is in bounds,
2236        // which means that `idx` cannot overflow an `isize`, and the
2237        // "slice" created by `cast_array` is a subslice of `self.v`
2238        // thus is guaranteed to be valid for the lifetime `'a` of `self.v`.
2239        unsafe { &*self.v.as_ptr().add(idx).cast_array() }
2240    }
2241}
2242
2243#[stable(feature = "array_windows", since = "1.94.0")]
2244impl<'a, T, const N: usize> DoubleEndedIterator for ArrayWindows<'a, T, N> {
2245    #[inline]
2246    fn next_back(&mut self) -> Option<&'a [T; N]> {
2247        let ret = self.v.last_chunk();
2248        if ret.is_some() {
2249            self.v = &self.v[..self.v.len() - 1];
2250        }
2251        ret
2252    }
2253
2254    #[inline]
2255    fn nth_back(&mut self, n: usize) -> Option<&'a [T; N]> {
2256        let idx = self.v.len().saturating_sub(n);
2257        self.v = &self.v[..idx];
2258        self.next_back()
2259    }
2260}
2261
2262#[stable(feature = "array_windows", since = "1.94.0")]
2263impl<T, const N: usize> ExactSizeIterator for ArrayWindows<'_, T, N> {
2264    fn is_empty(&self) -> bool {
2265        self.v.len() < N
2266    }
2267}
2268
2269#[unstable(feature = "trusted_len", issue = "37572")]
2270unsafe impl<T, const N: usize> TrustedLen for ArrayWindows<'_, T, N> {}
2271
2272#[stable(feature = "array_windows", since = "1.94.0")]
2273impl<T, const N: usize> FusedIterator for ArrayWindows<'_, T, N> {}
2274
2275#[doc(hidden)]
2276#[unstable(feature = "trusted_random_access", issue = "none")]
2277unsafe impl<T, const N: usize> TrustedRandomAccess for ArrayWindows<'_, T, N> {}
2278
2279#[doc(hidden)]
2280#[unstable(feature = "trusted_random_access", issue = "none")]
2281unsafe impl<T, const N: usize> TrustedRandomAccessNoCoerce for ArrayWindows<'_, T, N> {
2282    const MAY_HAVE_SIDE_EFFECT: bool = false;
2283}
2284
2285/// An iterator over a slice in (non-overlapping) chunks (`chunk_size` elements at a
2286/// time), starting at the end of the slice.
2287///
2288/// When the slice len is not evenly divided by the chunk size, the last slice
2289/// of the iteration will be the remainder.
2290///
2291/// This struct is created by the [`rchunks`] method on [slices].
2292///
2293/// # Example
2294///
2295/// ```
2296/// let slice = ['l', 'o', 'r', 'e', 'm'];
2297/// let mut iter = slice.rchunks(2);
2298/// assert_eq!(iter.next(), Some(&['e', 'm'][..]));
2299/// assert_eq!(iter.next(), Some(&['o', 'r'][..]));
2300/// assert_eq!(iter.next(), Some(&['l'][..]));
2301/// assert_eq!(iter.next(), None);
2302/// ```
2303///
2304/// [`rchunks`]: slice::rchunks
2305/// [slices]: slice
2306#[derive(Debug)]
2307#[stable(feature = "rchunks", since = "1.31.0")]
2308#[must_use = "iterators are lazy and do nothing unless consumed"]
2309pub struct RChunks<'a, T: 'a> {
2310    v: &'a [T],
2311    chunk_size: usize,
2312}
2313
2314impl<'a, T: 'a> RChunks<'a, T> {
2315    #[inline]
2316    pub(super) const fn new(slice: &'a [T], size: usize) -> Self {
2317        Self { v: slice, chunk_size: size }
2318    }
2319}
2320
2321// FIXME(#26925) Remove in favor of `#[derive(Clone)]`
2322#[stable(feature = "rchunks", since = "1.31.0")]
2323impl<T> Clone for RChunks<'_, T> {
2324    fn clone(&self) -> Self {
2325        RChunks { v: self.v, chunk_size: self.chunk_size }
2326    }
2327}
2328
2329#[stable(feature = "rchunks", since = "1.31.0")]
2330impl<'a, T> Iterator for RChunks<'a, T> {
2331    type Item = &'a [T];
2332
2333    #[inline]
2334    fn next(&mut self) -> Option<&'a [T]> {
2335        if self.v.is_empty() {
2336            None
2337        } else {
2338            let idx = self.v.len().saturating_sub(self.chunk_size);
2339            // SAFETY: self.chunk_size() > 0, so 0 <= idx < self.v.len().
2340            // Thus `idx` is in-bounds for `self.v` and can be used as a valid argument for `split_at_mut_unchecked`.
2341            let (rest, chunk) = unsafe { self.v.split_at_unchecked(idx) };
2342            self.v = rest;
2343            Some(chunk)
2344        }
2345    }
2346
2347    #[inline]
2348    fn size_hint(&self) -> (usize, Option<usize>) {
2349        if self.v.is_empty() {
2350            (0, Some(0))
2351        } else {
2352            let n = self.v.len().div_ceil(self.chunk_size);
2353            (n, Some(n))
2354        }
2355    }
2356
2357    #[inline]
2358    fn count(self) -> usize {
2359        self.len()
2360    }
2361
2362    #[inline]
2363    fn nth(&mut self, n: usize) -> Option<Self::Item> {
2364        if let Some(end) = n.checked_mul(self.chunk_size)
2365            && end < self.v.len()
2366        {
2367            let end = self.v.len() - end;
2368            let rest = &self.v[..end];
2369            let (rest, chunk) = rest.split_at(end.saturating_sub(self.chunk_size));
2370            self.v = rest;
2371            Some(chunk)
2372        } else {
2373            self.v = &self.v[..0]; // cheaper than &[]
2374            None
2375        }
2376    }
2377
2378    #[inline]
2379    fn last(self) -> Option<Self::Item> {
2380        if self.v.is_empty() {
2381            None
2382        } else {
2383            let rem = self.v.len() % self.chunk_size;
2384            let end = if rem == 0 { self.chunk_size } else { rem };
2385            Some(&self.v[0..end])
2386        }
2387    }
2388
2389    unsafe fn __iterator_get_unchecked(&mut self, idx: usize) -> Self::Item {
2390        let end = self.v.len() - idx * self.chunk_size;
2391        let start = end.saturating_sub(self.chunk_size);
2392        // SAFETY: mostly identical to `Chunks::__iterator_get_unchecked`.
2393        unsafe { from_raw_parts(self.v.as_ptr().add(start), end - start) }
2394    }
2395}
2396
2397#[stable(feature = "rchunks", since = "1.31.0")]
2398impl<'a, T> DoubleEndedIterator for RChunks<'a, T> {
2399    #[inline]
2400    fn next_back(&mut self) -> Option<&'a [T]> {
2401        if self.v.is_empty() {
2402            None
2403        } else {
2404            let remainder = self.v.len() % self.chunk_size;
2405            let chunksz = if remainder != 0 { remainder } else { self.chunk_size };
2406            // SAFETY: similar to Chunks::next_back
2407            let (fst, snd) = unsafe { self.v.split_at_unchecked(chunksz) };
2408            self.v = snd;
2409            Some(fst)
2410        }
2411    }
2412
2413    #[inline]
2414    fn nth_back(&mut self, n: usize) -> Option<Self::Item> {
2415        let len = self.len();
2416        if n < len {
2417            let offset_from_end = (len - 1 - n) * self.chunk_size;
2418            let end = self.v.len() - offset_from_end;
2419            let start = end.saturating_sub(self.chunk_size);
2420            let nth_back = &self.v[start..end];
2421            self.v = &self.v[end..];
2422            Some(nth_back)
2423        } else {
2424            self.v = &self.v[..0]; // cheaper than &[]
2425            None
2426        }
2427    }
2428}
2429
2430#[stable(feature = "rchunks", since = "1.31.0")]
2431impl<T> ExactSizeIterator for RChunks<'_, T> {}
2432
2433#[unstable(feature = "trusted_len", issue = "37572")]
2434unsafe impl<T> TrustedLen for RChunks<'_, T> {}
2435
2436#[stable(feature = "rchunks", since = "1.31.0")]
2437impl<T> FusedIterator for RChunks<'_, T> {}
2438
2439#[doc(hidden)]
2440#[unstable(feature = "trusted_random_access", issue = "none")]
2441unsafe impl<'a, T> TrustedRandomAccess for RChunks<'a, T> {}
2442
2443#[doc(hidden)]
2444#[unstable(feature = "trusted_random_access", issue = "none")]
2445unsafe impl<'a, T> TrustedRandomAccessNoCoerce for RChunks<'a, T> {
2446    const MAY_HAVE_SIDE_EFFECT: bool = false;
2447}
2448
2449/// An iterator over a slice in (non-overlapping) mutable chunks (`chunk_size`
2450/// elements at a time), starting at the end of the slice.
2451///
2452/// When the slice len is not evenly divided by the chunk size, the last slice
2453/// of the iteration will be the remainder.
2454///
2455/// This struct is created by the [`rchunks_mut`] method on [slices].
2456///
2457/// # Example
2458///
2459/// ```
2460/// let mut slice = ['l', 'o', 'r', 'e', 'm'];
2461/// let iter = slice.rchunks_mut(2);
2462/// ```
2463///
2464/// [`rchunks_mut`]: slice::rchunks_mut
2465/// [slices]: slice
2466#[derive(Debug)]
2467#[stable(feature = "rchunks", since = "1.31.0")]
2468#[must_use = "iterators are lazy and do nothing unless consumed"]
2469pub struct RChunksMut<'a, T: 'a> {
2470    /// # Safety
2471    /// This slice pointer must point at a valid region of `T` with at least length `v.len()`. Normally,
2472    /// those requirements would mean that we could instead use a `&mut [T]` here, but we cannot
2473    /// because `__iterator_get_unchecked` needs to return `&mut [T]`, which guarantees certain aliasing
2474    /// properties that we cannot uphold if we hold on to the full original `&mut [T]`. Wrapping a raw
2475    /// slice instead lets us hand out non-overlapping `&mut [T]` subslices of the slice we wrap.
2476    v: *mut [T],
2477    chunk_size: usize,
2478    _marker: PhantomData<&'a mut T>,
2479}
2480
2481impl<'a, T: 'a> RChunksMut<'a, T> {
2482    #[inline]
2483    pub(super) const fn new(slice: &'a mut [T], size: usize) -> Self {
2484        Self { v: slice, chunk_size: size, _marker: PhantomData }
2485    }
2486}
2487
2488#[stable(feature = "rchunks", since = "1.31.0")]
2489impl<'a, T> Iterator for RChunksMut<'a, T> {
2490    type Item = &'a mut [T];
2491
2492    #[inline]
2493    fn next(&mut self) -> Option<&'a mut [T]> {
2494        if self.v.is_empty() {
2495            None
2496        } else {
2497            let idx = self.v.len().saturating_sub(self.chunk_size);
2498            // SAFETY: self.chunk_size() > 0, so 0 <= idx < self.v.len().
2499            // Thus `idx` is in-bounds for `self.v` and can be used as a valid argument for `split_at_mut_unchecked`.
2500            let (rest, chunk) = unsafe { self.v.split_at_mut_unchecked(idx) };
2501            self.v = rest;
2502            // SAFETY: Nothing else points to or will point to the contents of this slice.
2503            Some(unsafe { &mut *chunk })
2504        }
2505    }
2506
2507    #[inline]
2508    fn size_hint(&self) -> (usize, Option<usize>) {
2509        if self.v.is_empty() {
2510            (0, Some(0))
2511        } else {
2512            let n = self.v.len().div_ceil(self.chunk_size);
2513            (n, Some(n))
2514        }
2515    }
2516
2517    #[inline]
2518    fn count(self) -> usize {
2519        self.len()
2520    }
2521
2522    #[inline]
2523    fn nth(&mut self, n: usize) -> Option<&'a mut [T]> {
2524        if let Some(end) = n.checked_mul(self.chunk_size)
2525            && end < self.v.len()
2526        {
2527            let end = self.v.len() - end;
2528            // SAFETY: The self.v contract ensures that any split_at_mut is valid.
2529            let (rest, _) = unsafe { self.v.split_at_mut(end) };
2530            // SAFETY: The self.v contract ensures that any split_at_mut is valid.
2531            let (rest, chunk) = unsafe { rest.split_at_mut(end.saturating_sub(self.chunk_size)) };
2532            self.v = rest;
2533            // SAFETY: Nothing else points to or will point to the contents of this slice.
2534            Some(unsafe { &mut *chunk })
2535        } else {
2536            self.v = &mut [];
2537            None
2538        }
2539    }
2540
2541    #[inline]
2542    fn last(self) -> Option<Self::Item> {
2543        if self.v.is_empty() {
2544            None
2545        } else {
2546            let rem = self.v.len() % self.chunk_size;
2547            let end = if rem == 0 { self.chunk_size } else { rem };
2548            // SAFETY: Nothing else points to or will point to the contents of this slice.
2549            Some(unsafe { &mut *self.v.get_unchecked_mut(0..end) })
2550        }
2551    }
2552
2553    unsafe fn __iterator_get_unchecked(&mut self, idx: usize) -> Self::Item {
2554        let end = self.v.len() - idx * self.chunk_size;
2555        let start = end.saturating_sub(self.chunk_size);
2556        // SAFETY: see comments for `RChunks::__iterator_get_unchecked` and
2557        // `ChunksMut::__iterator_get_unchecked`, `self.v`.
2558        unsafe { from_raw_parts_mut(self.v.as_mut_ptr().add(start), end - start) }
2559    }
2560}
2561
2562#[stable(feature = "rchunks", since = "1.31.0")]
2563impl<'a, T> DoubleEndedIterator for RChunksMut<'a, T> {
2564    #[inline]
2565    fn next_back(&mut self) -> Option<&'a mut [T]> {
2566        if self.v.is_empty() {
2567            None
2568        } else {
2569            let remainder = self.v.len() % self.chunk_size;
2570            let sz = if remainder != 0 { remainder } else { self.chunk_size };
2571            // SAFETY: Similar to `Chunks::next_back`
2572            let (head, tail) = unsafe { self.v.split_at_mut_unchecked(sz) };
2573            self.v = tail;
2574            // SAFETY: Nothing else points to or will point to the contents of this slice.
2575            Some(unsafe { &mut *head })
2576        }
2577    }
2578
2579    #[inline]
2580    fn nth_back(&mut self, n: usize) -> Option<Self::Item> {
2581        let len = self.len();
2582        if n < len {
2583            // can't underflow because `n < len`
2584            let offset_from_end = (len - 1 - n) * self.chunk_size;
2585            let end = self.v.len() - offset_from_end;
2586            let start = end.saturating_sub(self.chunk_size);
2587            // SAFETY: The self.v contract ensures that any split_at_mut is valid.
2588            let (tmp, tail) = unsafe { self.v.split_at_mut(end) };
2589            // SAFETY: The self.v contract ensures that any split_at_mut is valid.
2590            let (_, nth_back) = unsafe { tmp.split_at_mut(start) };
2591            self.v = tail;
2592            // SAFETY: Nothing else points to or will point to the contents of this slice.
2593            Some(unsafe { &mut *nth_back })
2594        } else {
2595            self.v = &mut [];
2596            None
2597        }
2598    }
2599}
2600
2601#[stable(feature = "rchunks", since = "1.31.0")]
2602impl<T> ExactSizeIterator for RChunksMut<'_, T> {}
2603
2604#[unstable(feature = "trusted_len", issue = "37572")]
2605unsafe impl<T> TrustedLen for RChunksMut<'_, T> {}
2606
2607#[stable(feature = "rchunks", since = "1.31.0")]
2608impl<T> FusedIterator for RChunksMut<'_, T> {}
2609
2610#[doc(hidden)]
2611#[unstable(feature = "trusted_random_access", issue = "none")]
2612unsafe impl<'a, T> TrustedRandomAccess for RChunksMut<'a, T> {}
2613
2614#[doc(hidden)]
2615#[unstable(feature = "trusted_random_access", issue = "none")]
2616unsafe impl<'a, T> TrustedRandomAccessNoCoerce for RChunksMut<'a, T> {
2617    const MAY_HAVE_SIDE_EFFECT: bool = false;
2618}
2619
2620#[stable(feature = "rchunks", since = "1.31.0")]
2621unsafe impl<T> Send for RChunksMut<'_, T> where T: Send {}
2622
2623#[stable(feature = "rchunks", since = "1.31.0")]
2624unsafe impl<T> Sync for RChunksMut<'_, T> where T: Sync {}
2625
2626/// An iterator over a slice in (non-overlapping) chunks (`chunk_size` elements at a
2627/// time), starting at the end of the slice.
2628///
2629/// When the slice len is not evenly divided by the chunk size, the last
2630/// up to `chunk_size-1` elements will be omitted but can be retrieved from
2631/// the [`remainder`] function from the iterator.
2632///
2633/// This struct is created by the [`rchunks_exact`] method on [slices].
2634///
2635/// # Example
2636///
2637/// ```
2638/// let slice = ['l', 'o', 'r', 'e', 'm'];
2639/// let mut iter = slice.rchunks_exact(2);
2640/// assert_eq!(iter.next(), Some(&['e', 'm'][..]));
2641/// assert_eq!(iter.next(), Some(&['o', 'r'][..]));
2642/// assert_eq!(iter.next(), None);
2643/// ```
2644///
2645/// [`rchunks_exact`]: slice::rchunks_exact
2646/// [`remainder`]: RChunksExact::remainder
2647/// [slices]: slice
2648#[derive(Debug)]
2649#[stable(feature = "rchunks", since = "1.31.0")]
2650#[must_use = "iterators are lazy and do nothing unless consumed"]
2651pub struct RChunksExact<'a, T: 'a> {
2652    v: &'a [T],
2653    rem: &'a [T],
2654    chunk_size: usize,
2655}
2656
2657impl<'a, T> RChunksExact<'a, T> {
2658    #[inline]
2659    pub(super) const fn new(slice: &'a [T], chunk_size: usize) -> Self {
2660        let rem = slice.len() % chunk_size;
2661        // SAFETY: 0 <= rem <= slice.len() by construction above
2662        let (fst, snd) = unsafe { slice.split_at_unchecked(rem) };
2663        Self { v: snd, rem: fst, chunk_size }
2664    }
2665
2666    /// Returns the remainder of the original slice that is not going to be
2667    /// returned by the iterator. The returned slice has at most `chunk_size-1`
2668    /// elements.
2669    ///
2670    /// # Example
2671    ///
2672    /// ```
2673    /// let slice = ['l', 'o', 'r', 'e', 'm'];
2674    /// let mut iter = slice.rchunks_exact(2);
2675    /// assert_eq!(iter.remainder(), &['l'][..]);
2676    /// assert_eq!(iter.next(), Some(&['e', 'm'][..]));
2677    /// assert_eq!(iter.remainder(), &['l'][..]);
2678    /// assert_eq!(iter.next(), Some(&['o', 'r'][..]));
2679    /// assert_eq!(iter.remainder(), &['l'][..]);
2680    /// assert_eq!(iter.next(), None);
2681    /// assert_eq!(iter.remainder(), &['l'][..]);
2682    /// ```
2683    #[must_use]
2684    #[stable(feature = "rchunks", since = "1.31.0")]
2685    #[rustc_const_unstable(feature = "const_slice_make_iter", issue = "137737")]
2686    pub const fn remainder(&self) -> &'a [T] {
2687        self.rem
2688    }
2689}
2690
2691// FIXME(#26925) Remove in favor of `#[derive(Clone)]`
2692#[stable(feature = "rchunks", since = "1.31.0")]
2693impl<'a, T> Clone for RChunksExact<'a, T> {
2694    fn clone(&self) -> RChunksExact<'a, T> {
2695        RChunksExact { v: self.v, rem: self.rem, chunk_size: self.chunk_size }
2696    }
2697}
2698
2699#[stable(feature = "rchunks", since = "1.31.0")]
2700impl<'a, T> Iterator for RChunksExact<'a, T> {
2701    type Item = &'a [T];
2702
2703    #[inline]
2704    fn next(&mut self) -> Option<&'a [T]> {
2705        if self.v.len() < self.chunk_size {
2706            None
2707        } else {
2708            let (fst, snd) = self.v.split_at(self.v.len() - self.chunk_size);
2709            self.v = fst;
2710            Some(snd)
2711        }
2712    }
2713
2714    #[inline]
2715    fn size_hint(&self) -> (usize, Option<usize>) {
2716        let n = self.v.len() / self.chunk_size;
2717        (n, Some(n))
2718    }
2719
2720    #[inline]
2721    fn count(self) -> usize {
2722        self.len()
2723    }
2724
2725    #[inline]
2726    fn nth(&mut self, n: usize) -> Option<Self::Item> {
2727        if let Some(end) = n.checked_mul(self.chunk_size)
2728            && end < self.v.len()
2729        {
2730            self.v = &self.v[..self.v.len() - end];
2731            self.next()
2732        } else {
2733            self.v = &self.v[..0]; // cheaper than &[]
2734            None
2735        }
2736    }
2737
2738    #[inline]
2739    fn last(mut self) -> Option<Self::Item> {
2740        self.next_back()
2741    }
2742
2743    unsafe fn __iterator_get_unchecked(&mut self, idx: usize) -> Self::Item {
2744        let end = self.v.len() - idx * self.chunk_size;
2745        let start = end - self.chunk_size;
2746        // SAFETY: mostly identical to `Chunks::__iterator_get_unchecked`.
2747        unsafe { from_raw_parts(self.v.as_ptr().add(start), self.chunk_size) }
2748    }
2749}
2750
2751#[stable(feature = "rchunks", since = "1.31.0")]
2752impl<'a, T> DoubleEndedIterator for RChunksExact<'a, T> {
2753    #[inline]
2754    fn next_back(&mut self) -> Option<&'a [T]> {
2755        if self.v.len() < self.chunk_size {
2756            None
2757        } else {
2758            let (fst, snd) = self.v.split_at(self.chunk_size);
2759            self.v = snd;
2760            Some(fst)
2761        }
2762    }
2763
2764    #[inline]
2765    fn nth_back(&mut self, n: usize) -> Option<Self::Item> {
2766        let len = self.len();
2767        if n < len {
2768            // now that we know that `n` corresponds to a chunk,
2769            // none of these operations can underflow/overflow
2770            let offset = (len - n) * self.chunk_size;
2771            let start = self.v.len() - offset;
2772            let end = start + self.chunk_size;
2773            let nth_back = &self.v[start..end];
2774            self.v = &self.v[end..];
2775            Some(nth_back)
2776        } else {
2777            self.v = &self.v[..0]; // cheaper than &[]
2778            None
2779        }
2780    }
2781}
2782
2783#[stable(feature = "rchunks", since = "1.31.0")]
2784impl<'a, T> ExactSizeIterator for RChunksExact<'a, T> {
2785    fn is_empty(&self) -> bool {
2786        self.v.is_empty()
2787    }
2788}
2789
2790#[unstable(feature = "trusted_len", issue = "37572")]
2791unsafe impl<T> TrustedLen for RChunksExact<'_, T> {}
2792
2793#[stable(feature = "rchunks", since = "1.31.0")]
2794impl<T> FusedIterator for RChunksExact<'_, T> {}
2795
2796#[doc(hidden)]
2797#[unstable(feature = "trusted_random_access", issue = "none")]
2798unsafe impl<'a, T> TrustedRandomAccess for RChunksExact<'a, T> {}
2799
2800#[doc(hidden)]
2801#[unstable(feature = "trusted_random_access", issue = "none")]
2802unsafe impl<'a, T> TrustedRandomAccessNoCoerce for RChunksExact<'a, T> {
2803    const MAY_HAVE_SIDE_EFFECT: bool = false;
2804}
2805
2806/// An iterator over a slice in (non-overlapping) mutable chunks (`chunk_size`
2807/// elements at a time), starting at the end of the slice.
2808///
2809/// When the slice len is not evenly divided by the chunk size, the last up to
2810/// `chunk_size-1` elements will be omitted but can be retrieved from the
2811/// [`into_remainder`] function from the iterator.
2812///
2813/// This struct is created by the [`rchunks_exact_mut`] method on [slices].
2814///
2815/// # Example
2816///
2817/// ```
2818/// let mut slice = ['l', 'o', 'r', 'e', 'm'];
2819/// let iter = slice.rchunks_exact_mut(2);
2820/// ```
2821///
2822/// [`rchunks_exact_mut`]: slice::rchunks_exact_mut
2823/// [`into_remainder`]: RChunksExactMut::into_remainder
2824/// [slices]: slice
2825#[derive(Debug)]
2826#[stable(feature = "rchunks", since = "1.31.0")]
2827#[must_use = "iterators are lazy and do nothing unless consumed"]
2828pub struct RChunksExactMut<'a, T: 'a> {
2829    /// # Safety
2830    /// This slice pointer must point at a valid region of `T` with at least length `v.len()`. Normally,
2831    /// those requirements would mean that we could instead use a `&mut [T]` here, but we cannot
2832    /// because `__iterator_get_unchecked` needs to return `&mut [T]`, which guarantees certain aliasing
2833    /// properties that we cannot uphold if we hold on to the full original `&mut [T]`. Wrapping a raw
2834    /// slice instead lets us hand out non-overlapping `&mut [T]` subslices of the slice we wrap.
2835    v: *mut [T],
2836    rem: &'a mut [T],
2837    chunk_size: usize,
2838}
2839
2840impl<'a, T> RChunksExactMut<'a, T> {
2841    #[inline]
2842    pub(super) const fn new(slice: &'a mut [T], chunk_size: usize) -> Self {
2843        let rem = slice.len() % chunk_size;
2844        // SAFETY: 0 <= rem <= slice.len() by construction above
2845        let (fst, snd) = unsafe { slice.split_at_mut_unchecked(rem) };
2846        Self { v: snd, rem: fst, chunk_size }
2847    }
2848
2849    /// Returns the remainder of the original slice that is not going to be
2850    /// returned by the iterator. The returned slice has at most `chunk_size-1`
2851    /// elements.
2852    #[must_use = "`self` will be dropped if the result is not used"]
2853    #[stable(feature = "rchunks", since = "1.31.0")]
2854    #[rustc_const_unstable(feature = "const_slice_make_iter", issue = "137737")]
2855    pub const fn into_remainder(self) -> &'a mut [T] {
2856        self.rem
2857    }
2858}
2859
2860#[stable(feature = "rchunks", since = "1.31.0")]
2861impl<'a, T> Iterator for RChunksExactMut<'a, T> {
2862    type Item = &'a mut [T];
2863
2864    #[inline]
2865    fn next(&mut self) -> Option<&'a mut [T]> {
2866        if self.v.len() < self.chunk_size {
2867            None
2868        } else {
2869            let len = self.v.len();
2870            // SAFETY: The self.v contract ensures that any split_at_mut is valid.
2871            let (head, tail) = unsafe { self.v.split_at_mut(len - self.chunk_size) };
2872            self.v = head;
2873            // SAFETY: Nothing else points to or will point to the contents of this slice.
2874            Some(unsafe { &mut *tail })
2875        }
2876    }
2877
2878    #[inline]
2879    fn size_hint(&self) -> (usize, Option<usize>) {
2880        let n = self.v.len() / self.chunk_size;
2881        (n, Some(n))
2882    }
2883
2884    #[inline]
2885    fn count(self) -> usize {
2886        self.len()
2887    }
2888
2889    #[inline]
2890    fn nth(&mut self, n: usize) -> Option<&'a mut [T]> {
2891        if let Some(end) = n.checked_mul(self.chunk_size)
2892            && end < self.v.len()
2893        {
2894            let idx = self.v.len() - end;
2895            // SAFETY: The self.v contract ensures that any split_at_mut is valid.
2896            let (fst, _) = unsafe { self.v.split_at_mut(idx) };
2897            self.v = fst;
2898            self.next()
2899        } else {
2900            self.v = &mut [];
2901            None
2902        }
2903    }
2904
2905    #[inline]
2906    fn last(mut self) -> Option<Self::Item> {
2907        self.next_back()
2908    }
2909
2910    unsafe fn __iterator_get_unchecked(&mut self, idx: usize) -> Self::Item {
2911        let end = self.v.len() - idx * self.chunk_size;
2912        let start = end - self.chunk_size;
2913        // SAFETY: see comments for `RChunksMut::__iterator_get_unchecked` and `self.v`.
2914        unsafe { from_raw_parts_mut(self.v.as_mut_ptr().add(start), self.chunk_size) }
2915    }
2916}
2917
2918#[stable(feature = "rchunks", since = "1.31.0")]
2919impl<'a, T> DoubleEndedIterator for RChunksExactMut<'a, T> {
2920    #[inline]
2921    fn next_back(&mut self) -> Option<&'a mut [T]> {
2922        if self.v.len() < self.chunk_size {
2923            None
2924        } else {
2925            // SAFETY: The self.v contract ensures that any split_at_mut is valid.
2926            let (head, tail) = unsafe { self.v.split_at_mut(self.chunk_size) };
2927            self.v = tail;
2928            // SAFETY: Nothing else points to or will point to the contents of this slice.
2929            Some(unsafe { &mut *head })
2930        }
2931    }
2932
2933    #[inline]
2934    fn nth_back(&mut self, n: usize) -> Option<Self::Item> {
2935        let len = self.len();
2936        if n < len {
2937            // now that we know that `n` corresponds to a chunk,
2938            // none of these operations can underflow/overflow
2939            let offset = (len - n) * self.chunk_size;
2940            let start = self.v.len() - offset;
2941            let end = start + self.chunk_size;
2942            // SAFETY: The self.v contract ensures that any split_at_mut is valid.
2943            let (tmp, tail) = unsafe { self.v.split_at_mut(end) };
2944            // SAFETY: The self.v contract ensures that any split_at_mut is valid.
2945            let (_, nth_back) = unsafe { tmp.split_at_mut(start) };
2946            self.v = tail;
2947            // SAFETY: Nothing else points to or will point to the contents of this slice.
2948            Some(unsafe { &mut *nth_back })
2949        } else {
2950            self.v = &mut [];
2951            None
2952        }
2953    }
2954}
2955
2956#[stable(feature = "rchunks", since = "1.31.0")]
2957impl<T> ExactSizeIterator for RChunksExactMut<'_, T> {
2958    fn is_empty(&self) -> bool {
2959        self.v.is_empty()
2960    }
2961}
2962
2963#[unstable(feature = "trusted_len", issue = "37572")]
2964unsafe impl<T> TrustedLen for RChunksExactMut<'_, T> {}
2965
2966#[stable(feature = "rchunks", since = "1.31.0")]
2967impl<T> FusedIterator for RChunksExactMut<'_, T> {}
2968
2969#[doc(hidden)]
2970#[unstable(feature = "trusted_random_access", issue = "none")]
2971unsafe impl<'a, T> TrustedRandomAccess for RChunksExactMut<'a, T> {}
2972
2973#[doc(hidden)]
2974#[unstable(feature = "trusted_random_access", issue = "none")]
2975unsafe impl<'a, T> TrustedRandomAccessNoCoerce for RChunksExactMut<'a, T> {
2976    const MAY_HAVE_SIDE_EFFECT: bool = false;
2977}
2978
2979#[stable(feature = "rchunks", since = "1.31.0")]
2980unsafe impl<T> Send for RChunksExactMut<'_, T> where T: Send {}
2981
2982#[stable(feature = "rchunks", since = "1.31.0")]
2983unsafe impl<T> Sync for RChunksExactMut<'_, T> where T: Sync {}
2984
2985#[doc(hidden)]
2986#[unstable(feature = "trusted_random_access", issue = "none")]
2987unsafe impl<'a, T> TrustedRandomAccess for Iter<'a, T> {}
2988
2989#[doc(hidden)]
2990#[unstable(feature = "trusted_random_access", issue = "none")]
2991unsafe impl<'a, T> TrustedRandomAccessNoCoerce for Iter<'a, T> {
2992    const MAY_HAVE_SIDE_EFFECT: bool = false;
2993}
2994
2995#[doc(hidden)]
2996#[unstable(feature = "trusted_random_access", issue = "none")]
2997unsafe impl<'a, T> TrustedRandomAccess for IterMut<'a, T> {}
2998
2999#[doc(hidden)]
3000#[unstable(feature = "trusted_random_access", issue = "none")]
3001unsafe impl<'a, T> TrustedRandomAccessNoCoerce for IterMut<'a, T> {
3002    const MAY_HAVE_SIDE_EFFECT: bool = false;
3003}
3004
3005/// An iterator over slice in (non-overlapping) chunks separated by a predicate.
3006///
3007/// This struct is created by the [`chunk_by`] method on [slices].
3008///
3009/// [`chunk_by`]: slice::chunk_by
3010/// [slices]: slice
3011#[stable(feature = "slice_group_by", since = "1.77.0")]
3012#[must_use = "iterators are lazy and do nothing unless consumed"]
3013pub struct ChunkBy<'a, T: 'a, P> {
3014    slice: &'a [T],
3015    predicate: P,
3016}
3017
3018#[stable(feature = "slice_group_by", since = "1.77.0")]
3019impl<'a, T: 'a, P> ChunkBy<'a, T, P> {
3020    pub(super) const fn new(slice: &'a [T], predicate: P) -> Self {
3021        ChunkBy { slice, predicate }
3022    }
3023}
3024
3025#[stable(feature = "slice_group_by", since = "1.77.0")]
3026impl<'a, T: 'a, P> Iterator for ChunkBy<'a, T, P>
3027where
3028    P: FnMut(&T, &T) -> bool,
3029{
3030    type Item = &'a [T];
3031
3032    #[inline]
3033    fn next(&mut self) -> Option<Self::Item> {
3034        if self.slice.is_empty() {
3035            None
3036        } else {
3037            let mut len = 1;
3038            let mut iter = self.slice.windows(2);
3039            while let Some([l, r]) = iter.next() {
3040                if (self.predicate)(l, r) { len += 1 } else { break }
3041            }
3042            let (head, tail) = self.slice.split_at(len);
3043            self.slice = tail;
3044            Some(head)
3045        }
3046    }
3047
3048    #[inline]
3049    fn size_hint(&self) -> (usize, Option<usize>) {
3050        if self.slice.is_empty() { (0, Some(0)) } else { (1, Some(self.slice.len())) }
3051    }
3052
3053    #[inline]
3054    fn last(mut self) -> Option<Self::Item> {
3055        self.next_back()
3056    }
3057}
3058
3059#[stable(feature = "slice_group_by", since = "1.77.0")]
3060impl<'a, T: 'a, P> DoubleEndedIterator for ChunkBy<'a, T, P>
3061where
3062    P: FnMut(&T, &T) -> bool,
3063{
3064    #[inline]
3065    fn next_back(&mut self) -> Option<Self::Item> {
3066        if self.slice.is_empty() {
3067            None
3068        } else {
3069            let mut len = 1;
3070            let mut iter = self.slice.windows(2);
3071            while let Some([l, r]) = iter.next_back() {
3072                if (self.predicate)(l, r) { len += 1 } else { break }
3073            }
3074            let (head, tail) = self.slice.split_at(self.slice.len() - len);
3075            self.slice = head;
3076            Some(tail)
3077        }
3078    }
3079}
3080
3081#[stable(feature = "slice_group_by", since = "1.77.0")]
3082impl<'a, T: 'a, P> FusedIterator for ChunkBy<'a, T, P> where P: FnMut(&T, &T) -> bool {}
3083
3084#[stable(feature = "slice_group_by_clone", since = "1.89.0")]
3085impl<'a, T: 'a, P: Clone> Clone for ChunkBy<'a, T, P> {
3086    fn clone(&self) -> Self {
3087        Self { slice: self.slice, predicate: self.predicate.clone() }
3088    }
3089}
3090
3091#[stable(feature = "slice_group_by", since = "1.77.0")]
3092impl<'a, T: 'a + fmt::Debug, P> fmt::Debug for ChunkBy<'a, T, P> {
3093    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
3094        f.debug_struct("ChunkBy").field("slice", &self.slice).finish()
3095    }
3096}
3097
3098/// An iterator over slice in (non-overlapping) mutable chunks separated
3099/// by a predicate.
3100///
3101/// This struct is created by the [`chunk_by_mut`] method on [slices].
3102///
3103/// [`chunk_by_mut`]: slice::chunk_by_mut
3104/// [slices]: slice
3105#[stable(feature = "slice_group_by", since = "1.77.0")]
3106#[must_use = "iterators are lazy and do nothing unless consumed"]
3107pub struct ChunkByMut<'a, T: 'a, P> {
3108    slice: &'a mut [T],
3109    predicate: P,
3110}
3111
3112#[stable(feature = "slice_group_by", since = "1.77.0")]
3113impl<'a, T: 'a, P> ChunkByMut<'a, T, P> {
3114    pub(super) const fn new(slice: &'a mut [T], predicate: P) -> Self {
3115        ChunkByMut { slice, predicate }
3116    }
3117}
3118
3119#[stable(feature = "slice_group_by", since = "1.77.0")]
3120impl<'a, T: 'a, P> Iterator for ChunkByMut<'a, T, P>
3121where
3122    P: FnMut(&T, &T) -> bool,
3123{
3124    type Item = &'a mut [T];
3125
3126    #[inline]
3127    fn next(&mut self) -> Option<Self::Item> {
3128        if self.slice.is_empty() {
3129            None
3130        } else {
3131            let mut len = 1;
3132            let mut iter = self.slice.windows(2);
3133            while let Some([l, r]) = iter.next() {
3134                if (self.predicate)(l, r) { len += 1 } else { break }
3135            }
3136            let slice = mem::take(&mut self.slice);
3137            let (head, tail) = slice.split_at_mut(len);
3138            self.slice = tail;
3139            Some(head)
3140        }
3141    }
3142
3143    #[inline]
3144    fn size_hint(&self) -> (usize, Option<usize>) {
3145        if self.slice.is_empty() { (0, Some(0)) } else { (1, Some(self.slice.len())) }
3146    }
3147
3148    #[inline]
3149    fn last(mut self) -> Option<Self::Item> {
3150        self.next_back()
3151    }
3152}
3153
3154#[stable(feature = "slice_group_by", since = "1.77.0")]
3155impl<'a, T: 'a, P> DoubleEndedIterator for ChunkByMut<'a, T, P>
3156where
3157    P: FnMut(&T, &T) -> bool,
3158{
3159    #[inline]
3160    fn next_back(&mut self) -> Option<Self::Item> {
3161        if self.slice.is_empty() {
3162            None
3163        } else {
3164            let mut len = 1;
3165            let mut iter = self.slice.windows(2);
3166            while let Some([l, r]) = iter.next_back() {
3167                if (self.predicate)(l, r) { len += 1 } else { break }
3168            }
3169            let slice = mem::take(&mut self.slice);
3170            let (head, tail) = slice.split_at_mut(slice.len() - len);
3171            self.slice = head;
3172            Some(tail)
3173        }
3174    }
3175}
3176
3177#[stable(feature = "slice_group_by", since = "1.77.0")]
3178impl<'a, T: 'a, P> FusedIterator for ChunkByMut<'a, T, P> where P: FnMut(&T, &T) -> bool {}
3179
3180#[stable(feature = "slice_group_by", since = "1.77.0")]
3181impl<'a, T: 'a + fmt::Debug, P> fmt::Debug for ChunkByMut<'a, T, P> {
3182    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
3183        f.debug_struct("ChunkByMut").field("slice", &self.slice).finish()
3184    }
3185}