Skip to main content

core/slice/
iter.rs

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