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