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