1 //! Definitions of a bunch of iterators for `[T]`.
3 #[macro_use] // import iterator! and forward_iterator!
7 use crate::cmp::Ordering;
9 use crate::intrinsics::{assume, exact_div, unchecked_sub};
10 use crate::iter::{FusedIterator, TrustedLen, TrustedRandomAccess, TrustedRandomAccessNoCoerce};
11 use crate::marker::{PhantomData, Send, Sized, Sync};
13 use crate::num::NonZeroUsize;
14 use crate::ptr::NonNull;
16 use super::{from_raw_parts, from_raw_parts_mut};
18 #[stable(feature = "rust1", since = "1.0.0")]
19 impl<'a, T> IntoIterator for &'a [T] {
21 type IntoIter = Iter<'a, T>;
23 fn into_iter(self) -> Iter<'a, T> {
28 #[stable(feature = "rust1", since = "1.0.0")]
29 impl<'a, T> IntoIterator for &'a mut [T] {
30 type Item = &'a mut T;
31 type IntoIter = IterMut<'a, T>;
33 fn into_iter(self) -> IterMut<'a, T> {
38 // Macro helper functions
40 fn size_from_ptr<T>(_: *const T) -> usize {
44 /// Immutable slice iterator
46 /// This struct is created by the [`iter`] method on [slices].
53 /// // First, we declare a type which has `iter` method to get the `Iter` struct (`&[usize]` here):
54 /// let slice = &[1, 2, 3];
56 /// // Then, we iterate over it:
57 /// for element in slice.iter() {
58 /// println!("{element}");
62 /// [`iter`]: slice::iter
64 #[stable(feature = "rust1", since = "1.0.0")]
65 #[must_use = "iterators are lazy and do nothing unless consumed"]
66 pub struct Iter<'a, T: 'a> {
68 end: *const T, // If T is a ZST, this is actually ptr+len. This encoding is picked so that
69 // ptr == end is a quick test for the Iterator being empty, that works
70 // for both ZST and non-ZST.
71 _marker: PhantomData<&'a T>,
74 #[stable(feature = "core_impl_debug", since = "1.9.0")]
75 impl<T: fmt::Debug> fmt::Debug for Iter<'_, T> {
76 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
77 f.debug_tuple("Iter").field(&self.as_slice()).finish()
81 #[stable(feature = "rust1", since = "1.0.0")]
82 unsafe impl<T: Sync> Sync for Iter<'_, T> {}
83 #[stable(feature = "rust1", since = "1.0.0")]
84 unsafe impl<T: Sync> Send for Iter<'_, T> {}
86 impl<'a, T> Iter<'a, T> {
88 pub(super) fn new(slice: &'a [T]) -> Self {
89 let ptr = slice.as_ptr();
90 // SAFETY: Similar to `IterMut::new`.
92 assume(!ptr.is_null());
94 let end = if mem::size_of::<T>() == 0 {
95 (ptr as *const u8).wrapping_add(slice.len()) as *const T
100 Self { ptr: NonNull::new_unchecked(ptr as *mut T), end, _marker: PhantomData }
104 /// Views the underlying data as a subslice of the original data.
106 /// This has the same lifetime as the original slice, and so the
107 /// iterator can continue to be used while this exists.
114 /// // First, we declare a type which has the `iter` method to get the `Iter`
115 /// // struct (`&[usize]` here):
116 /// let slice = &[1, 2, 3];
118 /// // Then, we get the iterator:
119 /// let mut iter = slice.iter();
120 /// // So if we print what `as_slice` method returns here, we have "[1, 2, 3]":
121 /// println!("{:?}", iter.as_slice());
123 /// // Next, we move to the second element of the slice:
125 /// // Now `as_slice` returns "[2, 3]":
126 /// println!("{:?}", iter.as_slice());
129 #[stable(feature = "iter_to_slice", since = "1.4.0")]
130 pub fn as_slice(&self) -> &'a [T] {
135 iterator! {struct Iter -> *const T, &'a T, const, {/* no mut */}, {
136 fn is_sorted_by<F>(self, mut compare: F) -> bool
139 F: FnMut(&Self::Item, &Self::Item) -> Option<Ordering>,
141 self.as_slice().windows(2).all(|w| {
142 compare(&&w[0], &&w[1]).map(|o| o != Ordering::Greater).unwrap_or(false)
147 #[stable(feature = "rust1", since = "1.0.0")]
148 impl<T> Clone for Iter<'_, T> {
149 fn clone(&self) -> Self {
150 Iter { ptr: self.ptr, end: self.end, _marker: self._marker }
154 #[stable(feature = "slice_iter_as_ref", since = "1.13.0")]
155 impl<T> AsRef<[T]> for Iter<'_, T> {
156 fn as_ref(&self) -> &[T] {
161 /// Mutable slice iterator.
163 /// This struct is created by the [`iter_mut`] method on [slices].
170 /// // First, we declare a type which has `iter_mut` method to get the `IterMut`
171 /// // struct (`&[usize]` here):
172 /// let mut slice = &mut [1, 2, 3];
174 /// // Then, we iterate over it and increment each element value:
175 /// for element in slice.iter_mut() {
179 /// // We now have "[2, 3, 4]":
180 /// println!("{slice:?}");
183 /// [`iter_mut`]: slice::iter_mut
185 #[stable(feature = "rust1", since = "1.0.0")]
186 #[must_use = "iterators are lazy and do nothing unless consumed"]
187 pub struct IterMut<'a, T: 'a> {
189 end: *mut T, // If T is a ZST, this is actually ptr+len. This encoding is picked so that
190 // ptr == end is a quick test for the Iterator being empty, that works
191 // for both ZST and non-ZST.
192 _marker: PhantomData<&'a mut T>,
195 #[stable(feature = "core_impl_debug", since = "1.9.0")]
196 impl<T: fmt::Debug> fmt::Debug for IterMut<'_, T> {
197 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
198 f.debug_tuple("IterMut").field(&self.make_slice()).finish()
202 #[stable(feature = "rust1", since = "1.0.0")]
203 unsafe impl<T: Sync> Sync for IterMut<'_, T> {}
204 #[stable(feature = "rust1", since = "1.0.0")]
205 unsafe impl<T: Send> Send for IterMut<'_, T> {}
207 impl<'a, T> IterMut<'a, T> {
209 pub(super) fn new(slice: &'a mut [T]) -> Self {
210 let ptr = slice.as_mut_ptr();
211 // SAFETY: There are several things here:
213 // `ptr` has been obtained by `slice.as_ptr()` where `slice` is a valid
214 // reference thus it is non-NUL and safe to use and pass to
215 // `NonNull::new_unchecked` .
217 // Adding `slice.len()` to the starting pointer gives a pointer
218 // at the end of `slice`. `end` will never be dereferenced, only checked
219 // for direct pointer equality with `ptr` to check if the iterator is
222 // In the case of a ZST, the end pointer is just the start pointer plus
223 // the length, to also allows for the fast `ptr == end` check.
225 // See the `next_unchecked!` and `is_empty!` macros as well as the
226 // `post_inc_start` method for more information.
228 assume(!ptr.is_null());
230 let end = if mem::size_of::<T>() == 0 {
231 (ptr as *mut u8).wrapping_add(slice.len()) as *mut T
236 Self { ptr: NonNull::new_unchecked(ptr), end, _marker: PhantomData }
240 /// Views the underlying data as a subslice of the original data.
242 /// To avoid creating `&mut` references that alias, this is forced
243 /// to consume the iterator.
250 /// // First, we declare a type which has `iter_mut` method to get the `IterMut`
251 /// // struct (`&[usize]` here):
252 /// let mut slice = &mut [1, 2, 3];
255 /// // Then, we get the iterator:
256 /// let mut iter = slice.iter_mut();
257 /// // We move to next element:
259 /// // So if we print what `into_slice` method returns here, we have "[2, 3]":
260 /// println!("{:?}", iter.into_slice());
263 /// // Now let's modify a value of the slice:
265 /// // First we get back the iterator:
266 /// let mut iter = slice.iter_mut();
267 /// // We change the value of the first element of the slice returned by the `next` method:
268 /// *iter.next().unwrap() += 1;
270 /// // Now slice is "[2, 2, 3]":
271 /// println!("{slice:?}");
273 #[must_use = "`self` will be dropped if the result is not used"]
274 #[stable(feature = "iter_to_slice", since = "1.4.0")]
275 pub fn into_slice(self) -> &'a mut [T] {
276 // SAFETY: the iterator was created from a mutable slice with pointer
277 // `self.ptr` and length `len!(self)`. This guarantees that all the prerequisites
278 // for `from_raw_parts_mut` are fulfilled.
279 unsafe { from_raw_parts_mut(self.ptr.as_ptr(), len!(self)) }
282 /// Views the underlying data as a subslice of the original data.
284 /// To avoid creating `&mut [T]` references that alias, the returned slice
285 /// borrows its lifetime from the iterator the method is applied on.
292 /// let mut slice: &mut [usize] = &mut [1, 2, 3];
294 /// // First, we get the iterator:
295 /// let mut iter = slice.iter_mut();
296 /// // So if we check what the `as_slice` method returns here, we have "[1, 2, 3]":
297 /// assert_eq!(iter.as_slice(), &[1, 2, 3]);
299 /// // Next, we move to the second element of the slice:
301 /// // Now `as_slice` returns "[2, 3]":
302 /// assert_eq!(iter.as_slice(), &[2, 3]);
305 #[stable(feature = "slice_iter_mut_as_slice", since = "1.53.0")]
306 pub fn as_slice(&self) -> &[T] {
311 #[stable(feature = "slice_iter_mut_as_slice", since = "1.53.0")]
312 impl<T> AsRef<[T]> for IterMut<'_, T> {
313 fn as_ref(&self) -> &[T] {
318 iterator! {struct IterMut -> *mut T, &'a mut T, mut, {mut}, {}}
320 /// An internal abstraction over the splitting iterators, so that
321 /// splitn, splitn_mut etc can be implemented once.
323 pub(super) trait SplitIter: DoubleEndedIterator {
324 /// Marks the underlying iterator as complete, extracting the remaining
325 /// portion of the slice.
326 fn finish(&mut self) -> Option<Self::Item>;
329 /// An iterator over subslices separated by elements that match a predicate
332 /// This struct is created by the [`split`] method on [slices].
337 /// let slice = [10, 40, 33, 20];
338 /// let mut iter = slice.split(|num| num % 3 == 0);
341 /// [`split`]: slice::split
343 #[stable(feature = "rust1", since = "1.0.0")]
344 #[must_use = "iterators are lazy and do nothing unless consumed"]
345 pub struct Split<'a, T: 'a, P>
347 P: FnMut(&T) -> bool,
349 // Used for `SplitWhitespace` and `SplitAsciiWhitespace` `as_str` methods
350 pub(crate) v: &'a [T],
352 // Used for `SplitAsciiWhitespace` `as_str` method
353 pub(crate) finished: bool,
356 impl<'a, T: 'a, P: FnMut(&T) -> bool> Split<'a, T, P> {
358 pub(super) fn new(slice: &'a [T], pred: P) -> Self {
359 Self { v: slice, pred, finished: false }
363 #[stable(feature = "core_impl_debug", since = "1.9.0")]
364 impl<T: fmt::Debug, P> fmt::Debug for Split<'_, T, P>
366 P: FnMut(&T) -> bool,
368 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
369 f.debug_struct("Split").field("v", &self.v).field("finished", &self.finished).finish()
373 // FIXME(#26925) Remove in favor of `#[derive(Clone)]`
374 #[stable(feature = "rust1", since = "1.0.0")]
375 impl<T, P> Clone for Split<'_, T, P>
377 P: Clone + FnMut(&T) -> bool,
379 fn clone(&self) -> Self {
380 Split { v: self.v, pred: self.pred.clone(), finished: self.finished }
384 #[stable(feature = "rust1", since = "1.0.0")]
385 impl<'a, T, P> Iterator for Split<'a, T, P>
387 P: FnMut(&T) -> bool,
392 fn next(&mut self) -> Option<&'a [T]> {
397 match self.v.iter().position(|x| (self.pred)(x)) {
398 None => self.finish(),
400 let ret = Some(&self.v[..idx]);
401 self.v = &self.v[idx + 1..];
408 fn size_hint(&self) -> (usize, Option<usize>) {
412 // If the predicate doesn't match anything, we yield one slice.
413 // If it matches every element, we yield `len() + 1` empty slices.
414 (1, Some(self.v.len() + 1))
419 #[stable(feature = "rust1", since = "1.0.0")]
420 impl<'a, T, P> DoubleEndedIterator for Split<'a, T, P>
422 P: FnMut(&T) -> bool,
425 fn next_back(&mut self) -> Option<&'a [T]> {
430 match self.v.iter().rposition(|x| (self.pred)(x)) {
431 None => self.finish(),
433 let ret = Some(&self.v[idx + 1..]);
434 self.v = &self.v[..idx];
441 impl<'a, T, P> SplitIter for Split<'a, T, P>
443 P: FnMut(&T) -> bool,
446 fn finish(&mut self) -> Option<&'a [T]> {
450 self.finished = true;
456 #[stable(feature = "fused", since = "1.26.0")]
457 impl<T, P> FusedIterator for Split<'_, T, P> where P: FnMut(&T) -> bool {}
459 /// An iterator over subslices separated by elements that match a predicate
460 /// function. Unlike `Split`, it contains the matched part as a terminator
463 /// This struct is created by the [`split_inclusive`] method on [slices].
468 /// let slice = [10, 40, 33, 20];
469 /// let mut iter = slice.split_inclusive(|num| num % 3 == 0);
472 /// [`split_inclusive`]: slice::split_inclusive
474 #[stable(feature = "split_inclusive", since = "1.51.0")]
475 #[must_use = "iterators are lazy and do nothing unless consumed"]
476 pub struct SplitInclusive<'a, T: 'a, P>
478 P: FnMut(&T) -> bool,
485 impl<'a, T: 'a, P: FnMut(&T) -> bool> SplitInclusive<'a, T, P> {
487 pub(super) fn new(slice: &'a [T], pred: P) -> Self {
488 let finished = slice.is_empty();
489 Self { v: slice, pred, finished }
493 #[stable(feature = "split_inclusive", since = "1.51.0")]
494 impl<T: fmt::Debug, P> fmt::Debug for SplitInclusive<'_, T, P>
496 P: FnMut(&T) -> bool,
498 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
499 f.debug_struct("SplitInclusive")
501 .field("finished", &self.finished)
506 // FIXME(#26925) Remove in favor of `#[derive(Clone)]`
507 #[stable(feature = "split_inclusive", since = "1.51.0")]
508 impl<T, P> Clone for SplitInclusive<'_, T, P>
510 P: Clone + FnMut(&T) -> bool,
512 fn clone(&self) -> Self {
513 SplitInclusive { v: self.v, pred: self.pred.clone(), finished: self.finished }
517 #[stable(feature = "split_inclusive", since = "1.51.0")]
518 impl<'a, T, P> Iterator for SplitInclusive<'a, T, P>
520 P: FnMut(&T) -> bool,
525 fn next(&mut self) -> Option<&'a [T]> {
531 self.v.iter().position(|x| (self.pred)(x)).map(|idx| idx + 1).unwrap_or(self.v.len());
532 if idx == self.v.len() {
533 self.finished = true;
535 let ret = Some(&self.v[..idx]);
536 self.v = &self.v[idx..];
541 fn size_hint(&self) -> (usize, Option<usize>) {
545 // If the predicate doesn't match anything, we yield one slice.
546 // If it matches every element, we yield `len()` one-element slices,
547 // or a single empty slice.
548 (1, Some(cmp::max(1, self.v.len())))
553 #[stable(feature = "split_inclusive", since = "1.51.0")]
554 impl<'a, T, P> DoubleEndedIterator for SplitInclusive<'a, T, P>
556 P: FnMut(&T) -> bool,
559 fn next_back(&mut self) -> Option<&'a [T]> {
564 // The last index of self.v is already checked and found to match
565 // by the last iteration, so we start searching a new match
566 // one index to the left.
567 let remainder = if self.v.is_empty() { &[] } else { &self.v[..(self.v.len() - 1)] };
568 let idx = remainder.iter().rposition(|x| (self.pred)(x)).map(|idx| idx + 1).unwrap_or(0);
570 self.finished = true;
572 let ret = Some(&self.v[idx..]);
573 self.v = &self.v[..idx];
578 #[stable(feature = "split_inclusive", since = "1.51.0")]
579 impl<T, P> FusedIterator for SplitInclusive<'_, T, P> where P: FnMut(&T) -> bool {}
581 /// An iterator over the mutable subslices of the vector which are separated
582 /// by elements that match `pred`.
584 /// This struct is created by the [`split_mut`] method on [slices].
589 /// let mut v = [10, 40, 30, 20, 60, 50];
590 /// let iter = v.split_mut(|num| *num % 3 == 0);
593 /// [`split_mut`]: slice::split_mut
595 #[stable(feature = "rust1", since = "1.0.0")]
596 #[must_use = "iterators are lazy and do nothing unless consumed"]
597 pub struct SplitMut<'a, T: 'a, P>
599 P: FnMut(&T) -> bool,
606 impl<'a, T: 'a, P: FnMut(&T) -> bool> SplitMut<'a, T, P> {
608 pub(super) fn new(slice: &'a mut [T], pred: P) -> Self {
609 Self { v: slice, pred, finished: false }
613 #[stable(feature = "core_impl_debug", since = "1.9.0")]
614 impl<T: fmt::Debug, P> fmt::Debug for SplitMut<'_, T, P>
616 P: FnMut(&T) -> bool,
618 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
619 f.debug_struct("SplitMut").field("v", &self.v).field("finished", &self.finished).finish()
623 impl<'a, T, P> SplitIter for SplitMut<'a, T, P>
625 P: FnMut(&T) -> bool,
628 fn finish(&mut self) -> Option<&'a mut [T]> {
632 self.finished = true;
633 Some(mem::replace(&mut self.v, &mut []))
638 #[stable(feature = "rust1", since = "1.0.0")]
639 impl<'a, T, P> Iterator for SplitMut<'a, T, P>
641 P: FnMut(&T) -> bool,
643 type Item = &'a mut [T];
646 fn next(&mut self) -> Option<&'a mut [T]> {
652 // work around borrowck limitations
653 let pred = &mut self.pred;
654 self.v.iter().position(|x| (*pred)(x))
657 None => self.finish(),
659 let tmp = mem::replace(&mut self.v, &mut []);
660 let (head, tail) = tmp.split_at_mut(idx);
661 self.v = &mut tail[1..];
668 fn size_hint(&self) -> (usize, Option<usize>) {
672 // If the predicate doesn't match anything, we yield one slice.
673 // If it matches every element, we yield `len() + 1` empty slices.
674 (1, Some(self.v.len() + 1))
679 #[stable(feature = "rust1", since = "1.0.0")]
680 impl<'a, T, P> DoubleEndedIterator for SplitMut<'a, T, P>
682 P: FnMut(&T) -> bool,
685 fn next_back(&mut self) -> Option<&'a mut [T]> {
691 // work around borrowck limitations
692 let pred = &mut self.pred;
693 self.v.iter().rposition(|x| (*pred)(x))
696 None => self.finish(),
698 let tmp = mem::replace(&mut self.v, &mut []);
699 let (head, tail) = tmp.split_at_mut(idx);
707 #[stable(feature = "fused", since = "1.26.0")]
708 impl<T, P> FusedIterator for SplitMut<'_, T, P> where P: FnMut(&T) -> bool {}
710 /// An iterator over the mutable subslices of the vector which are separated
711 /// by elements that match `pred`. Unlike `SplitMut`, it contains the matched
712 /// parts in the ends of the subslices.
714 /// This struct is created by the [`split_inclusive_mut`] method on [slices].
719 /// let mut v = [10, 40, 30, 20, 60, 50];
720 /// let iter = v.split_inclusive_mut(|num| *num % 3 == 0);
723 /// [`split_inclusive_mut`]: slice::split_inclusive_mut
725 #[stable(feature = "split_inclusive", since = "1.51.0")]
726 #[must_use = "iterators are lazy and do nothing unless consumed"]
727 pub struct SplitInclusiveMut<'a, T: 'a, P>
729 P: FnMut(&T) -> bool,
736 impl<'a, T: 'a, P: FnMut(&T) -> bool> SplitInclusiveMut<'a, T, P> {
738 pub(super) fn new(slice: &'a mut [T], pred: P) -> Self {
739 let finished = slice.is_empty();
740 Self { v: slice, pred, finished }
744 #[stable(feature = "split_inclusive", since = "1.51.0")]
745 impl<T: fmt::Debug, P> fmt::Debug for SplitInclusiveMut<'_, T, P>
747 P: FnMut(&T) -> bool,
749 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
750 f.debug_struct("SplitInclusiveMut")
752 .field("finished", &self.finished)
757 #[stable(feature = "split_inclusive", since = "1.51.0")]
758 impl<'a, T, P> Iterator for SplitInclusiveMut<'a, T, P>
760 P: FnMut(&T) -> bool,
762 type Item = &'a mut [T];
765 fn next(&mut self) -> Option<&'a mut [T]> {
771 // work around borrowck limitations
772 let pred = &mut self.pred;
773 self.v.iter().position(|x| (*pred)(x))
775 let idx = idx_opt.map(|idx| idx + 1).unwrap_or(self.v.len());
776 if idx == self.v.len() {
777 self.finished = true;
779 let tmp = mem::replace(&mut self.v, &mut []);
780 let (head, tail) = tmp.split_at_mut(idx);
786 fn size_hint(&self) -> (usize, Option<usize>) {
790 // If the predicate doesn't match anything, we yield one slice.
791 // If it matches every element, we yield `len()` one-element slices,
792 // or a single empty slice.
793 (1, Some(cmp::max(1, self.v.len())))
798 #[stable(feature = "split_inclusive", since = "1.51.0")]
799 impl<'a, T, P> DoubleEndedIterator for SplitInclusiveMut<'a, T, P>
801 P: FnMut(&T) -> bool,
804 fn next_back(&mut self) -> Option<&'a mut [T]> {
809 let idx_opt = if self.v.is_empty() {
812 // work around borrowck limitations
813 let pred = &mut self.pred;
815 // The last index of self.v is already checked and found to match
816 // by the last iteration, so we start searching a new match
817 // one index to the left.
818 let remainder = &self.v[..(self.v.len() - 1)];
819 remainder.iter().rposition(|x| (*pred)(x))
821 let idx = idx_opt.map(|idx| idx + 1).unwrap_or(0);
823 self.finished = true;
825 let tmp = mem::replace(&mut self.v, &mut []);
826 let (head, tail) = tmp.split_at_mut(idx);
832 #[stable(feature = "split_inclusive", since = "1.51.0")]
833 impl<T, P> FusedIterator for SplitInclusiveMut<'_, T, P> where P: FnMut(&T) -> bool {}
835 /// An iterator over subslices separated by elements that match a predicate
836 /// function, starting from the end of the slice.
838 /// This struct is created by the [`rsplit`] method on [slices].
843 /// let slice = [11, 22, 33, 0, 44, 55];
844 /// let iter = slice.rsplit(|num| *num == 0);
847 /// [`rsplit`]: slice::rsplit
849 #[stable(feature = "slice_rsplit", since = "1.27.0")]
850 #[must_use = "iterators are lazy and do nothing unless consumed"]
851 pub struct RSplit<'a, T: 'a, P>
853 P: FnMut(&T) -> bool,
855 inner: Split<'a, T, P>,
858 impl<'a, T: 'a, P: FnMut(&T) -> bool> RSplit<'a, T, P> {
860 pub(super) fn new(slice: &'a [T], pred: P) -> Self {
861 Self { inner: Split::new(slice, pred) }
865 #[stable(feature = "slice_rsplit", since = "1.27.0")]
866 impl<T: fmt::Debug, P> fmt::Debug for RSplit<'_, T, P>
868 P: FnMut(&T) -> bool,
870 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
871 f.debug_struct("RSplit")
872 .field("v", &self.inner.v)
873 .field("finished", &self.inner.finished)
878 // FIXME(#26925) Remove in favor of `#[derive(Clone)]`
879 #[stable(feature = "slice_rsplit", since = "1.27.0")]
880 impl<T, P> Clone for RSplit<'_, T, P>
882 P: Clone + FnMut(&T) -> bool,
884 fn clone(&self) -> Self {
885 RSplit { inner: self.inner.clone() }
889 #[stable(feature = "slice_rsplit", since = "1.27.0")]
890 impl<'a, T, P> Iterator for RSplit<'a, T, P>
892 P: FnMut(&T) -> bool,
897 fn next(&mut self) -> Option<&'a [T]> {
898 self.inner.next_back()
902 fn size_hint(&self) -> (usize, Option<usize>) {
903 self.inner.size_hint()
907 #[stable(feature = "slice_rsplit", since = "1.27.0")]
908 impl<'a, T, P> DoubleEndedIterator for RSplit<'a, T, P>
910 P: FnMut(&T) -> bool,
913 fn next_back(&mut self) -> Option<&'a [T]> {
918 #[stable(feature = "slice_rsplit", since = "1.27.0")]
919 impl<'a, T, P> SplitIter for RSplit<'a, T, P>
921 P: FnMut(&T) -> bool,
924 fn finish(&mut self) -> Option<&'a [T]> {
929 #[stable(feature = "slice_rsplit", since = "1.27.0")]
930 impl<T, P> FusedIterator for RSplit<'_, T, P> where P: FnMut(&T) -> bool {}
932 /// An iterator over the subslices of the vector which are separated
933 /// by elements that match `pred`, starting from the end of the slice.
935 /// This struct is created by the [`rsplit_mut`] method on [slices].
940 /// let mut slice = [11, 22, 33, 0, 44, 55];
941 /// let iter = slice.rsplit_mut(|num| *num == 0);
944 /// [`rsplit_mut`]: slice::rsplit_mut
946 #[stable(feature = "slice_rsplit", since = "1.27.0")]
947 #[must_use = "iterators are lazy and do nothing unless consumed"]
948 pub struct RSplitMut<'a, T: 'a, P>
950 P: FnMut(&T) -> bool,
952 inner: SplitMut<'a, T, P>,
955 impl<'a, T: 'a, P: FnMut(&T) -> bool> RSplitMut<'a, T, P> {
957 pub(super) fn new(slice: &'a mut [T], pred: P) -> Self {
958 Self { inner: SplitMut::new(slice, pred) }
962 #[stable(feature = "slice_rsplit", since = "1.27.0")]
963 impl<T: fmt::Debug, P> fmt::Debug for RSplitMut<'_, T, P>
965 P: FnMut(&T) -> bool,
967 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
968 f.debug_struct("RSplitMut")
969 .field("v", &self.inner.v)
970 .field("finished", &self.inner.finished)
975 #[stable(feature = "slice_rsplit", since = "1.27.0")]
976 impl<'a, T, P> SplitIter for RSplitMut<'a, T, P>
978 P: FnMut(&T) -> bool,
981 fn finish(&mut self) -> Option<&'a mut [T]> {
986 #[stable(feature = "slice_rsplit", since = "1.27.0")]
987 impl<'a, T, P> Iterator for RSplitMut<'a, T, P>
989 P: FnMut(&T) -> bool,
991 type Item = &'a mut [T];
994 fn next(&mut self) -> Option<&'a mut [T]> {
995 self.inner.next_back()
999 fn size_hint(&self) -> (usize, Option<usize>) {
1000 self.inner.size_hint()
1004 #[stable(feature = "slice_rsplit", since = "1.27.0")]
1005 impl<'a, T, P> DoubleEndedIterator for RSplitMut<'a, T, P>
1007 P: FnMut(&T) -> bool,
1010 fn next_back(&mut self) -> Option<&'a mut [T]> {
1015 #[stable(feature = "slice_rsplit", since = "1.27.0")]
1016 impl<T, P> FusedIterator for RSplitMut<'_, T, P> where P: FnMut(&T) -> bool {}
1018 /// An private iterator over subslices separated by elements that
1019 /// match a predicate function, splitting at most a fixed number of
1022 struct GenericSplitN<I> {
1027 impl<T, I: SplitIter<Item = T>> Iterator for GenericSplitN<I> {
1031 fn next(&mut self) -> Option<T> {
1046 fn size_hint(&self) -> (usize, Option<usize>) {
1047 let (lower, upper_opt) = self.iter.size_hint();
1049 cmp::min(self.count, lower),
1050 Some(upper_opt.map_or(self.count, |upper| cmp::min(self.count, upper))),
1055 /// An iterator over subslices separated by elements that match a predicate
1056 /// function, limited to a given number of splits.
1058 /// This struct is created by the [`splitn`] method on [slices].
1063 /// let slice = [10, 40, 30, 20, 60, 50];
1064 /// let iter = slice.splitn(2, |num| *num % 3 == 0);
1067 /// [`splitn`]: slice::splitn
1069 #[stable(feature = "rust1", since = "1.0.0")]
1070 #[must_use = "iterators are lazy and do nothing unless consumed"]
1071 pub struct SplitN<'a, T: 'a, P>
1073 P: FnMut(&T) -> bool,
1075 inner: GenericSplitN<Split<'a, T, P>>,
1078 impl<'a, T: 'a, P: FnMut(&T) -> bool> SplitN<'a, T, P> {
1080 pub(super) fn new(s: Split<'a, T, P>, n: usize) -> Self {
1081 Self { inner: GenericSplitN { iter: s, count: n } }
1085 #[stable(feature = "core_impl_debug", since = "1.9.0")]
1086 impl<T: fmt::Debug, P> fmt::Debug for SplitN<'_, T, P>
1088 P: FnMut(&T) -> bool,
1090 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
1091 f.debug_struct("SplitN").field("inner", &self.inner).finish()
1095 /// An iterator over subslices separated by elements that match a
1096 /// predicate function, limited to a given number of splits, starting
1097 /// from the end of the slice.
1099 /// This struct is created by the [`rsplitn`] method on [slices].
1104 /// let slice = [10, 40, 30, 20, 60, 50];
1105 /// let iter = slice.rsplitn(2, |num| *num % 3 == 0);
1108 /// [`rsplitn`]: slice::rsplitn
1110 #[stable(feature = "rust1", since = "1.0.0")]
1111 #[must_use = "iterators are lazy and do nothing unless consumed"]
1112 pub struct RSplitN<'a, T: 'a, P>
1114 P: FnMut(&T) -> bool,
1116 inner: GenericSplitN<RSplit<'a, T, P>>,
1119 impl<'a, T: 'a, P: FnMut(&T) -> bool> RSplitN<'a, T, P> {
1121 pub(super) fn new(s: RSplit<'a, T, P>, n: usize) -> Self {
1122 Self { inner: GenericSplitN { iter: s, count: n } }
1126 #[stable(feature = "core_impl_debug", since = "1.9.0")]
1127 impl<T: fmt::Debug, P> fmt::Debug for RSplitN<'_, T, P>
1129 P: FnMut(&T) -> bool,
1131 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
1132 f.debug_struct("RSplitN").field("inner", &self.inner).finish()
1136 /// An iterator over subslices separated by elements that match a predicate
1137 /// function, limited to a given number of splits.
1139 /// This struct is created by the [`splitn_mut`] method on [slices].
1144 /// let mut slice = [10, 40, 30, 20, 60, 50];
1145 /// let iter = slice.splitn_mut(2, |num| *num % 3 == 0);
1148 /// [`splitn_mut`]: slice::splitn_mut
1150 #[stable(feature = "rust1", since = "1.0.0")]
1151 #[must_use = "iterators are lazy and do nothing unless consumed"]
1152 pub struct SplitNMut<'a, T: 'a, P>
1154 P: FnMut(&T) -> bool,
1156 inner: GenericSplitN<SplitMut<'a, T, P>>,
1159 impl<'a, T: 'a, P: FnMut(&T) -> bool> SplitNMut<'a, T, P> {
1161 pub(super) fn new(s: SplitMut<'a, T, P>, n: usize) -> Self {
1162 Self { inner: GenericSplitN { iter: s, count: n } }
1166 #[stable(feature = "core_impl_debug", since = "1.9.0")]
1167 impl<T: fmt::Debug, P> fmt::Debug for SplitNMut<'_, T, P>
1169 P: FnMut(&T) -> bool,
1171 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
1172 f.debug_struct("SplitNMut").field("inner", &self.inner).finish()
1176 /// An iterator over subslices separated by elements that match a
1177 /// predicate function, limited to a given number of splits, starting
1178 /// from the end of the slice.
1180 /// This struct is created by the [`rsplitn_mut`] method on [slices].
1185 /// let mut slice = [10, 40, 30, 20, 60, 50];
1186 /// let iter = slice.rsplitn_mut(2, |num| *num % 3 == 0);
1189 /// [`rsplitn_mut`]: slice::rsplitn_mut
1191 #[stable(feature = "rust1", since = "1.0.0")]
1192 #[must_use = "iterators are lazy and do nothing unless consumed"]
1193 pub struct RSplitNMut<'a, T: 'a, P>
1195 P: FnMut(&T) -> bool,
1197 inner: GenericSplitN<RSplitMut<'a, T, P>>,
1200 impl<'a, T: 'a, P: FnMut(&T) -> bool> RSplitNMut<'a, T, P> {
1202 pub(super) fn new(s: RSplitMut<'a, T, P>, n: usize) -> Self {
1203 Self { inner: GenericSplitN { iter: s, count: n } }
1207 #[stable(feature = "core_impl_debug", since = "1.9.0")]
1208 impl<T: fmt::Debug, P> fmt::Debug for RSplitNMut<'_, T, P>
1210 P: FnMut(&T) -> bool,
1212 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
1213 f.debug_struct("RSplitNMut").field("inner", &self.inner).finish()
1217 forward_iterator! { SplitN: T, &'a [T] }
1218 forward_iterator! { RSplitN: T, &'a [T] }
1219 forward_iterator! { SplitNMut: T, &'a mut [T] }
1220 forward_iterator! { RSplitNMut: T, &'a mut [T] }
1222 /// An iterator over overlapping subslices of length `size`.
1224 /// This struct is created by the [`windows`] method on [slices].
1229 /// let slice = ['r', 'u', 's', 't'];
1230 /// let iter = slice.windows(2);
1233 /// [`windows`]: slice::windows
1236 #[stable(feature = "rust1", since = "1.0.0")]
1237 #[must_use = "iterators are lazy and do nothing unless consumed"]
1238 pub struct Windows<'a, T: 'a> {
1243 impl<'a, T: 'a> Windows<'a, T> {
1245 pub(super) fn new(slice: &'a [T], size: NonZeroUsize) -> Self {
1246 Self { v: slice, size }
1250 // FIXME(#26925) Remove in favor of `#[derive(Clone)]`
1251 #[stable(feature = "rust1", since = "1.0.0")]
1252 impl<T> Clone for Windows<'_, T> {
1253 fn clone(&self) -> Self {
1254 Windows { v: self.v, size: self.size }
1258 #[stable(feature = "rust1", since = "1.0.0")]
1259 impl<'a, T> Iterator for Windows<'a, T> {
1260 type Item = &'a [T];
1263 fn next(&mut self) -> Option<&'a [T]> {
1264 if self.size.get() > self.v.len() {
1267 let ret = Some(&self.v[..self.size.get()]);
1268 self.v = &self.v[1..];
1274 fn size_hint(&self) -> (usize, Option<usize>) {
1275 if self.size.get() > self.v.len() {
1278 let size = self.v.len() - self.size.get() + 1;
1284 fn count(self) -> usize {
1289 fn nth(&mut self, n: usize) -> Option<Self::Item> {
1290 let (end, overflow) = self.size.get().overflowing_add(n);
1291 if end > self.v.len() || overflow {
1295 let nth = &self.v[n..end];
1296 self.v = &self.v[n + 1..];
1302 fn last(self) -> Option<Self::Item> {
1303 if self.size.get() > self.v.len() {
1306 let start = self.v.len() - self.size.get();
1307 Some(&self.v[start..])
1312 unsafe fn __iterator_get_unchecked(&mut self, idx: usize) -> Self::Item {
1313 // SAFETY: since the caller guarantees that `i` is in bounds,
1314 // which means that `i` cannot overflow an `isize`, and the
1315 // slice created by `from_raw_parts` is a subslice of `self.v`
1316 // thus is guaranteed to be valid for the lifetime `'a` of `self.v`.
1317 unsafe { from_raw_parts(self.v.as_ptr().add(idx), self.size.get()) }
1321 #[stable(feature = "rust1", since = "1.0.0")]
1322 impl<'a, T> DoubleEndedIterator for Windows<'a, T> {
1324 fn next_back(&mut self) -> Option<&'a [T]> {
1325 if self.size.get() > self.v.len() {
1328 let ret = Some(&self.v[self.v.len() - self.size.get()..]);
1329 self.v = &self.v[..self.v.len() - 1];
1335 fn nth_back(&mut self, n: usize) -> Option<Self::Item> {
1336 let (end, overflow) = self.v.len().overflowing_sub(n);
1337 if end < self.size.get() || overflow {
1341 let ret = &self.v[end - self.size.get()..end];
1342 self.v = &self.v[..end - 1];
1348 #[stable(feature = "rust1", since = "1.0.0")]
1349 impl<T> ExactSizeIterator for Windows<'_, T> {}
1351 #[unstable(feature = "trusted_len", issue = "37572")]
1352 unsafe impl<T> TrustedLen for Windows<'_, T> {}
1354 #[stable(feature = "fused", since = "1.26.0")]
1355 impl<T> FusedIterator for Windows<'_, T> {}
1358 #[unstable(feature = "trusted_random_access", issue = "none")]
1359 unsafe impl<'a, T> TrustedRandomAccess for Windows<'a, T> {}
1362 #[unstable(feature = "trusted_random_access", issue = "none")]
1363 unsafe impl<'a, T> TrustedRandomAccessNoCoerce for Windows<'a, T> {
1364 const MAY_HAVE_SIDE_EFFECT: bool = false;
1367 /// An iterator over a slice in (non-overlapping) chunks (`chunk_size` elements at a
1368 /// time), starting at the beginning of the slice.
1370 /// When the slice len is not evenly divided by the chunk size, the last slice
1371 /// of the iteration will be the remainder.
1373 /// This struct is created by the [`chunks`] method on [slices].
1378 /// let slice = ['l', 'o', 'r', 'e', 'm'];
1379 /// let iter = slice.chunks(2);
1382 /// [`chunks`]: slice::chunks
1385 #[stable(feature = "rust1", since = "1.0.0")]
1386 #[must_use = "iterators are lazy and do nothing unless consumed"]
1387 pub struct Chunks<'a, T: 'a> {
1392 impl<'a, T: 'a> Chunks<'a, T> {
1394 pub(super) fn new(slice: &'a [T], size: usize) -> Self {
1395 Self { v: slice, chunk_size: size }
1399 // FIXME(#26925) Remove in favor of `#[derive(Clone)]`
1400 #[stable(feature = "rust1", since = "1.0.0")]
1401 impl<T> Clone for Chunks<'_, T> {
1402 fn clone(&self) -> Self {
1403 Chunks { v: self.v, chunk_size: self.chunk_size }
1407 #[stable(feature = "rust1", since = "1.0.0")]
1408 impl<'a, T> Iterator for Chunks<'a, T> {
1409 type Item = &'a [T];
1412 fn next(&mut self) -> Option<&'a [T]> {
1413 if self.v.is_empty() {
1416 let chunksz = cmp::min(self.v.len(), self.chunk_size);
1417 let (fst, snd) = self.v.split_at(chunksz);
1424 fn size_hint(&self) -> (usize, Option<usize>) {
1425 if self.v.is_empty() {
1428 let n = self.v.len() / self.chunk_size;
1429 let rem = self.v.len() % self.chunk_size;
1430 let n = if rem > 0 { n + 1 } else { n };
1436 fn count(self) -> usize {
1441 fn nth(&mut self, n: usize) -> Option<Self::Item> {
1442 let (start, overflow) = n.overflowing_mul(self.chunk_size);
1443 if start >= self.v.len() || overflow {
1447 let end = match start.checked_add(self.chunk_size) {
1448 Some(sum) => cmp::min(self.v.len(), sum),
1449 None => self.v.len(),
1451 let nth = &self.v[start..end];
1452 self.v = &self.v[end..];
1458 fn last(self) -> Option<Self::Item> {
1459 if self.v.is_empty() {
1462 let start = (self.v.len() - 1) / self.chunk_size * self.chunk_size;
1463 Some(&self.v[start..])
1468 unsafe fn __iterator_get_unchecked(&mut self, idx: usize) -> Self::Item {
1469 let start = idx * self.chunk_size;
1470 // SAFETY: the caller guarantees that `i` is in bounds,
1471 // which means that `start` must be in bounds of the
1472 // underlying `self.v` slice, and we made sure that `len`
1473 // is also in bounds of `self.v`. Thus, `start` cannot overflow
1474 // an `isize`, and the slice constructed by `from_raw_parts`
1475 // is a subslice of `self.v` which is guaranteed to be valid
1476 // for the lifetime `'a` of `self.v`.
1478 let len = cmp::min(self.v.len().unchecked_sub(start), self.chunk_size);
1479 from_raw_parts(self.v.as_ptr().add(start), len)
1484 #[stable(feature = "rust1", since = "1.0.0")]
1485 impl<'a, T> DoubleEndedIterator for Chunks<'a, T> {
1487 fn next_back(&mut self) -> Option<&'a [T]> {
1488 if self.v.is_empty() {
1491 let remainder = self.v.len() % self.chunk_size;
1492 let chunksz = if remainder != 0 { remainder } else { self.chunk_size };
1493 // SAFETY: split_at_unchecked requires the argument be less than or
1494 // equal to the length. This is guaranteed, but subtle: `chunksz`
1495 // will always either be `self.v.len() % self.chunk_size`, which
1496 // will always evaluate to strictly less than `self.v.len()` (or
1497 // panic, in the case that `self.chunk_size` is zero), or it can be
1498 // `self.chunk_size`, in the case that the length is exactly
1499 // divisible by the chunk size.
1501 // While it seems like using `self.chunk_size` in this case could
1502 // lead to a value greater than `self.v.len()`, it cannot: if
1503 // `self.chunk_size` were greater than `self.v.len()`, then
1504 // `self.v.len() % self.chunk_size` would return nonzero (note that
1505 // in this branch of the `if`, we already know that `self.v` is
1507 let (fst, snd) = unsafe { self.v.split_at_unchecked(self.v.len() - chunksz) };
1514 fn nth_back(&mut self, n: usize) -> Option<Self::Item> {
1515 let len = self.len();
1520 let start = (len - 1 - n) * self.chunk_size;
1521 let end = match start.checked_add(self.chunk_size) {
1522 Some(res) => cmp::min(self.v.len(), res),
1523 None => self.v.len(),
1525 let nth_back = &self.v[start..end];
1526 self.v = &self.v[..start];
1532 #[stable(feature = "rust1", since = "1.0.0")]
1533 impl<T> ExactSizeIterator for Chunks<'_, T> {}
1535 #[unstable(feature = "trusted_len", issue = "37572")]
1536 unsafe impl<T> TrustedLen for Chunks<'_, T> {}
1538 #[stable(feature = "fused", since = "1.26.0")]
1539 impl<T> FusedIterator for Chunks<'_, T> {}
1542 #[unstable(feature = "trusted_random_access", issue = "none")]
1543 unsafe impl<'a, T> TrustedRandomAccess for Chunks<'a, T> {}
1546 #[unstable(feature = "trusted_random_access", issue = "none")]
1547 unsafe impl<'a, T> TrustedRandomAccessNoCoerce for Chunks<'a, T> {
1548 const MAY_HAVE_SIDE_EFFECT: bool = false;
1551 /// An iterator over a slice in (non-overlapping) mutable chunks (`chunk_size`
1552 /// elements at a time), starting at the beginning of the slice.
1554 /// When the slice len is not evenly divided by the chunk size, the last slice
1555 /// of the iteration will be the remainder.
1557 /// This struct is created by the [`chunks_mut`] method on [slices].
1562 /// let mut slice = ['l', 'o', 'r', 'e', 'm'];
1563 /// let iter = slice.chunks_mut(2);
1566 /// [`chunks_mut`]: slice::chunks_mut
1569 #[stable(feature = "rust1", since = "1.0.0")]
1570 #[must_use = "iterators are lazy and do nothing unless consumed"]
1571 pub struct ChunksMut<'a, T: 'a> {
1576 impl<'a, T: 'a> ChunksMut<'a, T> {
1578 pub(super) fn new(slice: &'a mut [T], size: usize) -> Self {
1579 Self { v: slice, chunk_size: size }
1583 #[stable(feature = "rust1", since = "1.0.0")]
1584 impl<'a, T> Iterator for ChunksMut<'a, T> {
1585 type Item = &'a mut [T];
1588 fn next(&mut self) -> Option<&'a mut [T]> {
1589 if self.v.is_empty() {
1592 let sz = cmp::min(self.v.len(), self.chunk_size);
1593 let tmp = mem::replace(&mut self.v, &mut []);
1594 let (head, tail) = tmp.split_at_mut(sz);
1601 fn size_hint(&self) -> (usize, Option<usize>) {
1602 if self.v.is_empty() {
1605 let n = self.v.len() / self.chunk_size;
1606 let rem = self.v.len() % self.chunk_size;
1607 let n = if rem > 0 { n + 1 } else { n };
1613 fn count(self) -> usize {
1618 fn nth(&mut self, n: usize) -> Option<&'a mut [T]> {
1619 let (start, overflow) = n.overflowing_mul(self.chunk_size);
1620 if start >= self.v.len() || overflow {
1624 let end = match start.checked_add(self.chunk_size) {
1625 Some(sum) => cmp::min(self.v.len(), sum),
1626 None => self.v.len(),
1628 let tmp = mem::replace(&mut self.v, &mut []);
1629 let (head, tail) = tmp.split_at_mut(end);
1630 let (_, nth) = head.split_at_mut(start);
1637 fn last(self) -> Option<Self::Item> {
1638 if self.v.is_empty() {
1641 let start = (self.v.len() - 1) / self.chunk_size * self.chunk_size;
1642 Some(&mut self.v[start..])
1647 unsafe fn __iterator_get_unchecked(&mut self, idx: usize) -> Self::Item {
1648 let start = idx * self.chunk_size;
1649 // SAFETY: see comments for `Chunks::__iterator_get_unchecked`.
1651 // Also note that the caller also guarantees that we're never called
1652 // with the same index again, and that no other methods that will
1653 // access this subslice are called, so it is valid for the returned
1654 // slice to be mutable.
1656 let len = cmp::min(self.v.len().unchecked_sub(start), self.chunk_size);
1657 from_raw_parts_mut(self.v.as_mut_ptr().add(start), len)
1662 #[stable(feature = "rust1", since = "1.0.0")]
1663 impl<'a, T> DoubleEndedIterator for ChunksMut<'a, T> {
1665 fn next_back(&mut self) -> Option<&'a mut [T]> {
1666 if self.v.is_empty() {
1669 let remainder = self.v.len() % self.chunk_size;
1670 let sz = if remainder != 0 { remainder } else { self.chunk_size };
1671 let tmp = mem::replace(&mut self.v, &mut []);
1672 let tmp_len = tmp.len();
1673 // SAFETY: Similar to `Chunks::next_back`
1674 let (head, tail) = unsafe { tmp.split_at_mut_unchecked(tmp_len - sz) };
1681 fn nth_back(&mut self, n: usize) -> Option<Self::Item> {
1682 let len = self.len();
1687 let start = (len - 1 - n) * self.chunk_size;
1688 let end = match start.checked_add(self.chunk_size) {
1689 Some(res) => cmp::min(self.v.len(), res),
1690 None => self.v.len(),
1692 let (temp, _tail) = mem::replace(&mut self.v, &mut []).split_at_mut(end);
1693 let (head, nth_back) = temp.split_at_mut(start);
1700 #[stable(feature = "rust1", since = "1.0.0")]
1701 impl<T> ExactSizeIterator for ChunksMut<'_, T> {}
1703 #[unstable(feature = "trusted_len", issue = "37572")]
1704 unsafe impl<T> TrustedLen for ChunksMut<'_, T> {}
1706 #[stable(feature = "fused", since = "1.26.0")]
1707 impl<T> FusedIterator for ChunksMut<'_, T> {}
1710 #[unstable(feature = "trusted_random_access", issue = "none")]
1711 unsafe impl<'a, T> TrustedRandomAccess for ChunksMut<'a, T> {}
1714 #[unstable(feature = "trusted_random_access", issue = "none")]
1715 unsafe impl<'a, T> TrustedRandomAccessNoCoerce for ChunksMut<'a, T> {
1716 const MAY_HAVE_SIDE_EFFECT: bool = false;
1719 /// An iterator over a slice in (non-overlapping) chunks (`chunk_size` elements at a
1720 /// time), starting at the beginning of the slice.
1722 /// When the slice len is not evenly divided by the chunk size, the last
1723 /// up to `chunk_size-1` elements will be omitted but can be retrieved from
1724 /// the [`remainder`] function from the iterator.
1726 /// This struct is created by the [`chunks_exact`] method on [slices].
1731 /// let slice = ['l', 'o', 'r', 'e', 'm'];
1732 /// let iter = slice.chunks_exact(2);
1735 /// [`chunks_exact`]: slice::chunks_exact
1736 /// [`remainder`]: ChunksExact::remainder
1739 #[stable(feature = "chunks_exact", since = "1.31.0")]
1740 #[must_use = "iterators are lazy and do nothing unless consumed"]
1741 pub struct ChunksExact<'a, T: 'a> {
1747 impl<'a, T> ChunksExact<'a, T> {
1749 pub(super) fn new(slice: &'a [T], chunk_size: usize) -> Self {
1750 let rem = slice.len() % chunk_size;
1751 let fst_len = slice.len() - rem;
1752 // SAFETY: 0 <= fst_len <= slice.len() by construction above
1753 let (fst, snd) = unsafe { slice.split_at_unchecked(fst_len) };
1754 Self { v: fst, rem: snd, chunk_size }
1757 /// Returns the remainder of the original slice that is not going to be
1758 /// returned by the iterator. The returned slice has at most `chunk_size-1`
1761 #[stable(feature = "chunks_exact", since = "1.31.0")]
1762 pub fn remainder(&self) -> &'a [T] {
1767 // FIXME(#26925) Remove in favor of `#[derive(Clone)]`
1768 #[stable(feature = "chunks_exact", since = "1.31.0")]
1769 impl<T> Clone for ChunksExact<'_, T> {
1770 fn clone(&self) -> Self {
1771 ChunksExact { v: self.v, rem: self.rem, chunk_size: self.chunk_size }
1775 #[stable(feature = "chunks_exact", since = "1.31.0")]
1776 impl<'a, T> Iterator for ChunksExact<'a, T> {
1777 type Item = &'a [T];
1780 fn next(&mut self) -> Option<&'a [T]> {
1781 if self.v.len() < self.chunk_size {
1784 let (fst, snd) = self.v.split_at(self.chunk_size);
1791 fn size_hint(&self) -> (usize, Option<usize>) {
1792 let n = self.v.len() / self.chunk_size;
1797 fn count(self) -> usize {
1802 fn nth(&mut self, n: usize) -> Option<Self::Item> {
1803 let (start, overflow) = n.overflowing_mul(self.chunk_size);
1804 if start >= self.v.len() || overflow {
1808 let (_, snd) = self.v.split_at(start);
1815 fn last(mut self) -> Option<Self::Item> {
1820 unsafe fn __iterator_get_unchecked(&mut self, idx: usize) -> Self::Item {
1821 let start = idx * self.chunk_size;
1822 // SAFETY: mostly identical to `Chunks::__iterator_get_unchecked`.
1823 unsafe { from_raw_parts(self.v.as_ptr().add(start), self.chunk_size) }
1827 #[stable(feature = "chunks_exact", since = "1.31.0")]
1828 impl<'a, T> DoubleEndedIterator for ChunksExact<'a, T> {
1830 fn next_back(&mut self) -> Option<&'a [T]> {
1831 if self.v.len() < self.chunk_size {
1834 let (fst, snd) = self.v.split_at(self.v.len() - self.chunk_size);
1841 fn nth_back(&mut self, n: usize) -> Option<Self::Item> {
1842 let len = self.len();
1847 let start = (len - 1 - n) * self.chunk_size;
1848 let end = start + self.chunk_size;
1849 let nth_back = &self.v[start..end];
1850 self.v = &self.v[..start];
1856 #[stable(feature = "chunks_exact", since = "1.31.0")]
1857 impl<T> ExactSizeIterator for ChunksExact<'_, T> {
1858 fn is_empty(&self) -> bool {
1863 #[unstable(feature = "trusted_len", issue = "37572")]
1864 unsafe impl<T> TrustedLen for ChunksExact<'_, T> {}
1866 #[stable(feature = "chunks_exact", since = "1.31.0")]
1867 impl<T> FusedIterator for ChunksExact<'_, T> {}
1870 #[unstable(feature = "trusted_random_access", issue = "none")]
1871 unsafe impl<'a, T> TrustedRandomAccess for ChunksExact<'a, T> {}
1874 #[unstable(feature = "trusted_random_access", issue = "none")]
1875 unsafe impl<'a, T> TrustedRandomAccessNoCoerce for ChunksExact<'a, T> {
1876 const MAY_HAVE_SIDE_EFFECT: bool = false;
1879 /// An iterator over a slice in (non-overlapping) mutable chunks (`chunk_size`
1880 /// elements at a time), starting at the beginning of the slice.
1882 /// When the slice len is not evenly divided by the chunk size, the last up to
1883 /// `chunk_size-1` elements will be omitted but can be retrieved from the
1884 /// [`into_remainder`] function from the iterator.
1886 /// This struct is created by the [`chunks_exact_mut`] method on [slices].
1891 /// let mut slice = ['l', 'o', 'r', 'e', 'm'];
1892 /// let iter = slice.chunks_exact_mut(2);
1895 /// [`chunks_exact_mut`]: slice::chunks_exact_mut
1896 /// [`into_remainder`]: ChunksExactMut::into_remainder
1899 #[stable(feature = "chunks_exact", since = "1.31.0")]
1900 #[must_use = "iterators are lazy and do nothing unless consumed"]
1901 pub struct ChunksExactMut<'a, T: 'a> {
1907 impl<'a, T> ChunksExactMut<'a, T> {
1909 pub(super) fn new(slice: &'a mut [T], chunk_size: usize) -> Self {
1910 let rem = slice.len() % chunk_size;
1911 let fst_len = slice.len() - rem;
1912 // SAFETY: 0 <= fst_len <= slice.len() by construction above
1913 let (fst, snd) = unsafe { slice.split_at_mut_unchecked(fst_len) };
1914 Self { v: fst, rem: snd, chunk_size }
1917 /// Returns the remainder of the original slice that is not going to be
1918 /// returned by the iterator. The returned slice has at most `chunk_size-1`
1920 #[must_use = "`self` will be dropped if the result is not used"]
1921 #[stable(feature = "chunks_exact", since = "1.31.0")]
1922 pub fn into_remainder(self) -> &'a mut [T] {
1927 #[stable(feature = "chunks_exact", since = "1.31.0")]
1928 impl<'a, T> Iterator for ChunksExactMut<'a, T> {
1929 type Item = &'a mut [T];
1932 fn next(&mut self) -> Option<&'a mut [T]> {
1933 if self.v.len() < self.chunk_size {
1936 let tmp = mem::replace(&mut self.v, &mut []);
1937 let (head, tail) = tmp.split_at_mut(self.chunk_size);
1944 fn size_hint(&self) -> (usize, Option<usize>) {
1945 let n = self.v.len() / self.chunk_size;
1950 fn count(self) -> usize {
1955 fn nth(&mut self, n: usize) -> Option<&'a mut [T]> {
1956 let (start, overflow) = n.overflowing_mul(self.chunk_size);
1957 if start >= self.v.len() || overflow {
1961 let tmp = mem::replace(&mut self.v, &mut []);
1962 let (_, snd) = tmp.split_at_mut(start);
1969 fn last(mut self) -> Option<Self::Item> {
1974 unsafe fn __iterator_get_unchecked(&mut self, idx: usize) -> Self::Item {
1975 let start = idx * self.chunk_size;
1976 // SAFETY: see comments for `ChunksMut::__iterator_get_unchecked`.
1977 unsafe { from_raw_parts_mut(self.v.as_mut_ptr().add(start), self.chunk_size) }
1981 #[stable(feature = "chunks_exact", since = "1.31.0")]
1982 impl<'a, T> DoubleEndedIterator for ChunksExactMut<'a, T> {
1984 fn next_back(&mut self) -> Option<&'a mut [T]> {
1985 if self.v.len() < self.chunk_size {
1988 let tmp = mem::replace(&mut self.v, &mut []);
1989 let tmp_len = tmp.len();
1990 let (head, tail) = tmp.split_at_mut(tmp_len - self.chunk_size);
1997 fn nth_back(&mut self, n: usize) -> Option<Self::Item> {
1998 let len = self.len();
2003 let start = (len - 1 - n) * self.chunk_size;
2004 let end = start + self.chunk_size;
2005 let (temp, _tail) = mem::replace(&mut self.v, &mut []).split_at_mut(end);
2006 let (head, nth_back) = temp.split_at_mut(start);
2013 #[stable(feature = "chunks_exact", since = "1.31.0")]
2014 impl<T> ExactSizeIterator for ChunksExactMut<'_, T> {
2015 fn is_empty(&self) -> bool {
2020 #[unstable(feature = "trusted_len", issue = "37572")]
2021 unsafe impl<T> TrustedLen for ChunksExactMut<'_, T> {}
2023 #[stable(feature = "chunks_exact", since = "1.31.0")]
2024 impl<T> FusedIterator for ChunksExactMut<'_, T> {}
2027 #[unstable(feature = "trusted_random_access", issue = "none")]
2028 unsafe impl<'a, T> TrustedRandomAccess for ChunksExactMut<'a, T> {}
2031 #[unstable(feature = "trusted_random_access", issue = "none")]
2032 unsafe impl<'a, T> TrustedRandomAccessNoCoerce for ChunksExactMut<'a, T> {
2033 const MAY_HAVE_SIDE_EFFECT: bool = false;
2036 /// A windowed iterator over a slice in overlapping chunks (`N` elements at a
2037 /// time), starting at the beginning of the slice
2039 /// This struct is created by the [`array_windows`] method on [slices].
2044 /// #![feature(array_windows)]
2046 /// let slice = [0, 1, 2, 3];
2047 /// let iter = slice.array_windows::<2>();
2050 /// [`array_windows`]: slice::array_windows
2052 #[derive(Debug, Clone, Copy)]
2053 #[unstable(feature = "array_windows", issue = "75027")]
2054 #[must_use = "iterators are lazy and do nothing unless consumed"]
2055 pub struct ArrayWindows<'a, T: 'a, const N: usize> {
2056 slice_head: *const T,
2058 marker: PhantomData<&'a [T; N]>,
2061 impl<'a, T: 'a, const N: usize> ArrayWindows<'a, T, N> {
2063 pub(super) fn new(slice: &'a [T]) -> Self {
2064 let num_windows = slice.len().saturating_sub(N - 1);
2065 Self { slice_head: slice.as_ptr(), num: num_windows, marker: PhantomData }
2069 #[unstable(feature = "array_windows", issue = "75027")]
2070 impl<'a, T, const N: usize> Iterator for ArrayWindows<'a, T, N> {
2071 type Item = &'a [T; N];
2074 fn next(&mut self) -> Option<Self::Item> {
2079 // This is safe because it's indexing into a slice guaranteed to be length > N.
2080 let ret = unsafe { &*self.slice_head.cast::<[T; N]>() };
2081 // SAFETY: Guaranteed that there are at least 1 item remaining otherwise
2082 // earlier branch would've been hit
2083 self.slice_head = unsafe { self.slice_head.add(1) };
2090 fn size_hint(&self) -> (usize, Option<usize>) {
2091 (self.num, Some(self.num))
2095 fn count(self) -> usize {
2100 fn nth(&mut self, n: usize) -> Option<Self::Item> {
2106 // This is safe because it's indexing into a slice guaranteed to be length > N.
2107 let ret = unsafe { &*self.slice_head.add(n).cast::<[T; N]>() };
2108 // SAFETY: Guaranteed that there are at least n items remaining
2109 self.slice_head = unsafe { self.slice_head.add(n + 1) };
2116 fn last(mut self) -> Option<Self::Item> {
2117 self.nth(self.num.checked_sub(1)?)
2121 #[unstable(feature = "array_windows", issue = "75027")]
2122 impl<'a, T, const N: usize> DoubleEndedIterator for ArrayWindows<'a, T, N> {
2124 fn next_back(&mut self) -> Option<&'a [T; N]> {
2128 // SAFETY: Guaranteed that there are n items remaining, n-1 for 0-indexing.
2129 let ret = unsafe { &*self.slice_head.add(self.num - 1).cast::<[T; N]>() };
2135 fn nth_back(&mut self, n: usize) -> Option<&'a [T; N]> {
2140 // SAFETY: Guaranteed that there are n items remaining, n-1 for 0-indexing.
2141 let ret = unsafe { &*self.slice_head.add(self.num - (n + 1)).cast::<[T; N]>() };
2147 #[unstable(feature = "array_windows", issue = "75027")]
2148 impl<T, const N: usize> ExactSizeIterator for ArrayWindows<'_, T, N> {
2149 fn is_empty(&self) -> bool {
2154 /// An iterator over a slice in (non-overlapping) chunks (`N` elements at a
2155 /// time), starting at the beginning of the slice.
2157 /// When the slice len is not evenly divided by the chunk size, the last
2158 /// up to `N-1` elements will be omitted but can be retrieved from
2159 /// the [`remainder`] function from the iterator.
2161 /// This struct is created by the [`array_chunks`] method on [slices].
2166 /// #![feature(array_chunks)]
2168 /// let slice = ['l', 'o', 'r', 'e', 'm'];
2169 /// let iter = slice.array_chunks::<2>();
2172 /// [`array_chunks`]: slice::array_chunks
2173 /// [`remainder`]: ArrayChunks::remainder
2176 #[unstable(feature = "array_chunks", issue = "74985")]
2177 #[must_use = "iterators are lazy and do nothing unless consumed"]
2178 pub struct ArrayChunks<'a, T: 'a, const N: usize> {
2179 iter: Iter<'a, [T; N]>,
2183 impl<'a, T, const N: usize> ArrayChunks<'a, T, N> {
2185 pub(super) fn new(slice: &'a [T]) -> Self {
2186 let (array_slice, rem) = slice.as_chunks();
2187 Self { iter: array_slice.iter(), rem }
2190 /// Returns the remainder of the original slice that is not going to be
2191 /// returned by the iterator. The returned slice has at most `N-1`
2194 #[unstable(feature = "array_chunks", issue = "74985")]
2195 pub fn remainder(&self) -> &'a [T] {
2200 // FIXME(#26925) Remove in favor of `#[derive(Clone)]`
2201 #[unstable(feature = "array_chunks", issue = "74985")]
2202 impl<T, const N: usize> Clone for ArrayChunks<'_, T, N> {
2203 fn clone(&self) -> Self {
2204 ArrayChunks { iter: self.iter.clone(), rem: self.rem }
2208 #[unstable(feature = "array_chunks", issue = "74985")]
2209 impl<'a, T, const N: usize> Iterator for ArrayChunks<'a, T, N> {
2210 type Item = &'a [T; N];
2213 fn next(&mut self) -> Option<&'a [T; N]> {
2218 fn size_hint(&self) -> (usize, Option<usize>) {
2219 self.iter.size_hint()
2223 fn count(self) -> usize {
2228 fn nth(&mut self, n: usize) -> Option<Self::Item> {
2233 fn last(self) -> Option<Self::Item> {
2238 unsafe fn __iterator_get_unchecked(&mut self, i: usize) -> &'a [T; N] {
2239 // SAFETY: The safety guarantees of `__iterator_get_unchecked` are
2240 // transferred to the caller.
2241 unsafe { self.iter.__iterator_get_unchecked(i) }
2245 #[unstable(feature = "array_chunks", issue = "74985")]
2246 impl<'a, T, const N: usize> DoubleEndedIterator for ArrayChunks<'a, T, N> {
2248 fn next_back(&mut self) -> Option<&'a [T; N]> {
2249 self.iter.next_back()
2253 fn nth_back(&mut self, n: usize) -> Option<Self::Item> {
2254 self.iter.nth_back(n)
2258 #[unstable(feature = "array_chunks", issue = "74985")]
2259 impl<T, const N: usize> ExactSizeIterator for ArrayChunks<'_, T, N> {
2260 fn is_empty(&self) -> bool {
2261 self.iter.is_empty()
2265 #[unstable(feature = "trusted_len", issue = "37572")]
2266 unsafe impl<T, const N: usize> TrustedLen for ArrayChunks<'_, T, N> {}
2268 #[unstable(feature = "array_chunks", issue = "74985")]
2269 impl<T, const N: usize> FusedIterator for ArrayChunks<'_, T, N> {}
2272 #[unstable(feature = "array_chunks", issue = "74985")]
2273 unsafe impl<'a, T, const N: usize> TrustedRandomAccess for ArrayChunks<'a, T, N> {}
2276 #[unstable(feature = "array_chunks", issue = "74985")]
2277 unsafe impl<'a, T, const N: usize> TrustedRandomAccessNoCoerce for ArrayChunks<'a, T, N> {
2278 const MAY_HAVE_SIDE_EFFECT: bool = false;
2281 /// An iterator over a slice in (non-overlapping) mutable chunks (`N` elements
2282 /// at a time), starting at the beginning of the slice.
2284 /// When the slice len is not evenly divided by the chunk size, the last
2285 /// up to `N-1` elements will be omitted but can be retrieved from
2286 /// the [`into_remainder`] function from the iterator.
2288 /// This struct is created by the [`array_chunks_mut`] method on [slices].
2293 /// #![feature(array_chunks)]
2295 /// let mut slice = ['l', 'o', 'r', 'e', 'm'];
2296 /// let iter = slice.array_chunks_mut::<2>();
2299 /// [`array_chunks_mut`]: slice::array_chunks_mut
2300 /// [`into_remainder`]: ../../std/slice/struct.ArrayChunksMut.html#method.into_remainder
2303 #[unstable(feature = "array_chunks", issue = "74985")]
2304 #[must_use = "iterators are lazy and do nothing unless consumed"]
2305 pub struct ArrayChunksMut<'a, T: 'a, const N: usize> {
2306 iter: IterMut<'a, [T; N]>,
2310 impl<'a, T, const N: usize> ArrayChunksMut<'a, T, N> {
2312 pub(super) fn new(slice: &'a mut [T]) -> Self {
2313 let (array_slice, rem) = slice.as_chunks_mut();
2314 Self { iter: array_slice.iter_mut(), rem }
2317 /// Returns the remainder of the original slice that is not going to be
2318 /// returned by the iterator. The returned slice has at most `N-1`
2320 #[must_use = "`self` will be dropped if the result is not used"]
2321 #[unstable(feature = "array_chunks", issue = "74985")]
2322 pub fn into_remainder(self) -> &'a mut [T] {
2327 #[unstable(feature = "array_chunks", issue = "74985")]
2328 impl<'a, T, const N: usize> Iterator for ArrayChunksMut<'a, T, N> {
2329 type Item = &'a mut [T; N];
2332 fn next(&mut self) -> Option<&'a mut [T; N]> {
2337 fn size_hint(&self) -> (usize, Option<usize>) {
2338 self.iter.size_hint()
2342 fn count(self) -> usize {
2347 fn nth(&mut self, n: usize) -> Option<Self::Item> {
2352 fn last(self) -> Option<Self::Item> {
2357 unsafe fn __iterator_get_unchecked(&mut self, i: usize) -> &'a mut [T; N] {
2358 // SAFETY: The safety guarantees of `__iterator_get_unchecked` are transferred to
2360 unsafe { self.iter.__iterator_get_unchecked(i) }
2364 #[unstable(feature = "array_chunks", issue = "74985")]
2365 impl<'a, T, const N: usize> DoubleEndedIterator for ArrayChunksMut<'a, T, N> {
2367 fn next_back(&mut self) -> Option<&'a mut [T; N]> {
2368 self.iter.next_back()
2372 fn nth_back(&mut self, n: usize) -> Option<Self::Item> {
2373 self.iter.nth_back(n)
2377 #[unstable(feature = "array_chunks", issue = "74985")]
2378 impl<T, const N: usize> ExactSizeIterator for ArrayChunksMut<'_, T, N> {
2379 fn is_empty(&self) -> bool {
2380 self.iter.is_empty()
2384 #[unstable(feature = "trusted_len", issue = "37572")]
2385 unsafe impl<T, const N: usize> TrustedLen for ArrayChunksMut<'_, T, N> {}
2387 #[unstable(feature = "array_chunks", issue = "74985")]
2388 impl<T, const N: usize> FusedIterator for ArrayChunksMut<'_, T, N> {}
2391 #[unstable(feature = "array_chunks", issue = "74985")]
2392 unsafe impl<'a, T, const N: usize> TrustedRandomAccess for ArrayChunksMut<'a, T, N> {}
2395 #[unstable(feature = "array_chunks", issue = "74985")]
2396 unsafe impl<'a, T, const N: usize> TrustedRandomAccessNoCoerce for ArrayChunksMut<'a, T, N> {
2397 const MAY_HAVE_SIDE_EFFECT: bool = false;
2400 /// An iterator over a slice in (non-overlapping) chunks (`chunk_size` elements at a
2401 /// time), starting at the end of the slice.
2403 /// When the slice len is not evenly divided by the chunk size, the last slice
2404 /// of the iteration will be the remainder.
2406 /// This struct is created by the [`rchunks`] method on [slices].
2411 /// let slice = ['l', 'o', 'r', 'e', 'm'];
2412 /// let iter = slice.rchunks(2);
2415 /// [`rchunks`]: slice::rchunks
2418 #[stable(feature = "rchunks", since = "1.31.0")]
2419 #[must_use = "iterators are lazy and do nothing unless consumed"]
2420 pub struct RChunks<'a, T: 'a> {
2425 impl<'a, T: 'a> RChunks<'a, T> {
2427 pub(super) fn new(slice: &'a [T], size: usize) -> Self {
2428 Self { v: slice, chunk_size: size }
2432 // FIXME(#26925) Remove in favor of `#[derive(Clone)]`
2433 #[stable(feature = "rchunks", since = "1.31.0")]
2434 impl<T> Clone for RChunks<'_, T> {
2435 fn clone(&self) -> Self {
2436 RChunks { v: self.v, chunk_size: self.chunk_size }
2440 #[stable(feature = "rchunks", since = "1.31.0")]
2441 impl<'a, T> Iterator for RChunks<'a, T> {
2442 type Item = &'a [T];
2445 fn next(&mut self) -> Option<&'a [T]> {
2446 if self.v.is_empty() {
2449 let len = self.v.len();
2450 let chunksz = cmp::min(len, self.chunk_size);
2451 // SAFETY: split_at_unchecked just requires the argument be less
2452 // than the length. This could only happen if the expression `len -
2453 // chunksz` overflows. This could only happen if `chunksz > len`,
2454 // which is impossible as we initialize it as the `min` of `len` and
2455 // `self.chunk_size`.
2456 let (fst, snd) = unsafe { self.v.split_at_unchecked(len - chunksz) };
2463 fn size_hint(&self) -> (usize, Option<usize>) {
2464 if self.v.is_empty() {
2467 let n = self.v.len() / self.chunk_size;
2468 let rem = self.v.len() % self.chunk_size;
2469 let n = if rem > 0 { n + 1 } else { n };
2475 fn count(self) -> usize {
2480 fn nth(&mut self, n: usize) -> Option<Self::Item> {
2481 let (end, overflow) = n.overflowing_mul(self.chunk_size);
2482 if end >= self.v.len() || overflow {
2486 // Can't underflow because of the check above
2487 let end = self.v.len() - end;
2488 let start = match end.checked_sub(self.chunk_size) {
2492 let nth = &self.v[start..end];
2493 self.v = &self.v[0..start];
2499 fn last(self) -> Option<Self::Item> {
2500 if self.v.is_empty() {
2503 let rem = self.v.len() % self.chunk_size;
2504 let end = if rem == 0 { self.chunk_size } else { rem };
2505 Some(&self.v[0..end])
2510 unsafe fn __iterator_get_unchecked(&mut self, idx: usize) -> Self::Item {
2511 let end = self.v.len() - idx * self.chunk_size;
2512 let start = match end.checked_sub(self.chunk_size) {
2514 Some(start) => start,
2516 // SAFETY: mostly identical to `Chunks::__iterator_get_unchecked`.
2517 unsafe { from_raw_parts(self.v.as_ptr().add(start), end - start) }
2521 #[stable(feature = "rchunks", since = "1.31.0")]
2522 impl<'a, T> DoubleEndedIterator for RChunks<'a, T> {
2524 fn next_back(&mut self) -> Option<&'a [T]> {
2525 if self.v.is_empty() {
2528 let remainder = self.v.len() % self.chunk_size;
2529 let chunksz = if remainder != 0 { remainder } else { self.chunk_size };
2530 // SAFETY: similar to Chunks::next_back
2531 let (fst, snd) = unsafe { self.v.split_at_unchecked(chunksz) };
2538 fn nth_back(&mut self, n: usize) -> Option<Self::Item> {
2539 let len = self.len();
2544 // can't underflow because `n < len`
2545 let offset_from_end = (len - 1 - n) * self.chunk_size;
2546 let end = self.v.len() - offset_from_end;
2547 let start = end.saturating_sub(self.chunk_size);
2548 let nth_back = &self.v[start..end];
2549 self.v = &self.v[end..];
2555 #[stable(feature = "rchunks", since = "1.31.0")]
2556 impl<T> ExactSizeIterator for RChunks<'_, T> {}
2558 #[unstable(feature = "trusted_len", issue = "37572")]
2559 unsafe impl<T> TrustedLen for RChunks<'_, T> {}
2561 #[stable(feature = "rchunks", since = "1.31.0")]
2562 impl<T> FusedIterator for RChunks<'_, T> {}
2565 #[unstable(feature = "trusted_random_access", issue = "none")]
2566 unsafe impl<'a, T> TrustedRandomAccess for RChunks<'a, T> {}
2569 #[unstable(feature = "trusted_random_access", issue = "none")]
2570 unsafe impl<'a, T> TrustedRandomAccessNoCoerce for RChunks<'a, T> {
2571 const MAY_HAVE_SIDE_EFFECT: bool = false;
2574 /// An iterator over a slice in (non-overlapping) mutable chunks (`chunk_size`
2575 /// elements at a time), starting at the end of the slice.
2577 /// When the slice len is not evenly divided by the chunk size, the last slice
2578 /// of the iteration will be the remainder.
2580 /// This struct is created by the [`rchunks_mut`] method on [slices].
2585 /// let mut slice = ['l', 'o', 'r', 'e', 'm'];
2586 /// let iter = slice.rchunks_mut(2);
2589 /// [`rchunks_mut`]: slice::rchunks_mut
2592 #[stable(feature = "rchunks", since = "1.31.0")]
2593 #[must_use = "iterators are lazy and do nothing unless consumed"]
2594 pub struct RChunksMut<'a, T: 'a> {
2599 impl<'a, T: 'a> RChunksMut<'a, T> {
2601 pub(super) fn new(slice: &'a mut [T], size: usize) -> Self {
2602 Self { v: slice, chunk_size: size }
2606 #[stable(feature = "rchunks", since = "1.31.0")]
2607 impl<'a, T> Iterator for RChunksMut<'a, T> {
2608 type Item = &'a mut [T];
2611 fn next(&mut self) -> Option<&'a mut [T]> {
2612 if self.v.is_empty() {
2615 let sz = cmp::min(self.v.len(), self.chunk_size);
2616 let tmp = mem::replace(&mut self.v, &mut []);
2617 let tmp_len = tmp.len();
2618 // SAFETY: split_at_mut_unchecked just requires the argument be less
2619 // than the length. This could only happen if the expression
2620 // `tmp_len - sz` overflows. This could only happen if `sz >
2621 // tmp_len`, which is impossible as we initialize it as the `min` of
2622 // `self.v.len()` (e.g. `tmp_len`) and `self.chunk_size`.
2623 let (head, tail) = unsafe { tmp.split_at_mut_unchecked(tmp_len - sz) };
2630 fn size_hint(&self) -> (usize, Option<usize>) {
2631 if self.v.is_empty() {
2634 let n = self.v.len() / self.chunk_size;
2635 let rem = self.v.len() % self.chunk_size;
2636 let n = if rem > 0 { n + 1 } else { n };
2642 fn count(self) -> usize {
2647 fn nth(&mut self, n: usize) -> Option<&'a mut [T]> {
2648 let (end, overflow) = n.overflowing_mul(self.chunk_size);
2649 if end >= self.v.len() || overflow {
2653 // Can't underflow because of the check above
2654 let end = self.v.len() - end;
2655 let start = match end.checked_sub(self.chunk_size) {
2659 let tmp = mem::replace(&mut self.v, &mut []);
2660 let (head, tail) = tmp.split_at_mut(start);
2661 let (nth, _) = tail.split_at_mut(end - start);
2668 fn last(self) -> Option<Self::Item> {
2669 if self.v.is_empty() {
2672 let rem = self.v.len() % self.chunk_size;
2673 let end = if rem == 0 { self.chunk_size } else { rem };
2674 Some(&mut self.v[0..end])
2679 unsafe fn __iterator_get_unchecked(&mut self, idx: usize) -> Self::Item {
2680 let end = self.v.len() - idx * self.chunk_size;
2681 let start = match end.checked_sub(self.chunk_size) {
2683 Some(start) => start,
2685 // SAFETY: see comments for `RChunks::__iterator_get_unchecked` and
2686 // `ChunksMut::__iterator_get_unchecked`
2687 unsafe { from_raw_parts_mut(self.v.as_mut_ptr().add(start), end - start) }
2691 #[stable(feature = "rchunks", since = "1.31.0")]
2692 impl<'a, T> DoubleEndedIterator for RChunksMut<'a, T> {
2694 fn next_back(&mut self) -> Option<&'a mut [T]> {
2695 if self.v.is_empty() {
2698 let remainder = self.v.len() % self.chunk_size;
2699 let sz = if remainder != 0 { remainder } else { self.chunk_size };
2700 let tmp = mem::replace(&mut self.v, &mut []);
2701 // SAFETY: Similar to `Chunks::next_back`
2702 let (head, tail) = unsafe { tmp.split_at_mut_unchecked(sz) };
2709 fn nth_back(&mut self, n: usize) -> Option<Self::Item> {
2710 let len = self.len();
2715 // can't underflow because `n < len`
2716 let offset_from_end = (len - 1 - n) * self.chunk_size;
2717 let end = self.v.len() - offset_from_end;
2718 let start = end.saturating_sub(self.chunk_size);
2719 let (tmp, tail) = mem::replace(&mut self.v, &mut []).split_at_mut(end);
2720 let (_, nth_back) = tmp.split_at_mut(start);
2727 #[stable(feature = "rchunks", since = "1.31.0")]
2728 impl<T> ExactSizeIterator for RChunksMut<'_, T> {}
2730 #[unstable(feature = "trusted_len", issue = "37572")]
2731 unsafe impl<T> TrustedLen for RChunksMut<'_, T> {}
2733 #[stable(feature = "rchunks", since = "1.31.0")]
2734 impl<T> FusedIterator for RChunksMut<'_, T> {}
2737 #[unstable(feature = "trusted_random_access", issue = "none")]
2738 unsafe impl<'a, T> TrustedRandomAccess for RChunksMut<'a, T> {}
2741 #[unstable(feature = "trusted_random_access", issue = "none")]
2742 unsafe impl<'a, T> TrustedRandomAccessNoCoerce for RChunksMut<'a, T> {
2743 const MAY_HAVE_SIDE_EFFECT: bool = false;
2746 /// An iterator over a slice in (non-overlapping) chunks (`chunk_size` elements at a
2747 /// time), starting at the end of the slice.
2749 /// When the slice len is not evenly divided by the chunk size, the last
2750 /// up to `chunk_size-1` elements will be omitted but can be retrieved from
2751 /// the [`remainder`] function from the iterator.
2753 /// This struct is created by the [`rchunks_exact`] method on [slices].
2758 /// let slice = ['l', 'o', 'r', 'e', 'm'];
2759 /// let iter = slice.rchunks_exact(2);
2762 /// [`rchunks_exact`]: slice::rchunks_exact
2763 /// [`remainder`]: ChunksExact::remainder
2766 #[stable(feature = "rchunks", since = "1.31.0")]
2767 #[must_use = "iterators are lazy and do nothing unless consumed"]
2768 pub struct RChunksExact<'a, T: 'a> {
2774 impl<'a, T> RChunksExact<'a, T> {
2776 pub(super) fn new(slice: &'a [T], chunk_size: usize) -> Self {
2777 let rem = slice.len() % chunk_size;
2778 // SAFETY: 0 <= rem <= slice.len() by construction above
2779 let (fst, snd) = unsafe { slice.split_at_unchecked(rem) };
2780 Self { v: snd, rem: fst, chunk_size }
2783 /// Returns the remainder of the original slice that is not going to be
2784 /// returned by the iterator. The returned slice has at most `chunk_size-1`
2787 #[stable(feature = "rchunks", since = "1.31.0")]
2788 pub fn remainder(&self) -> &'a [T] {
2793 // FIXME(#26925) Remove in favor of `#[derive(Clone)]`
2794 #[stable(feature = "rchunks", since = "1.31.0")]
2795 impl<'a, T> Clone for RChunksExact<'a, T> {
2796 fn clone(&self) -> RChunksExact<'a, T> {
2797 RChunksExact { v: self.v, rem: self.rem, chunk_size: self.chunk_size }
2801 #[stable(feature = "rchunks", since = "1.31.0")]
2802 impl<'a, T> Iterator for RChunksExact<'a, T> {
2803 type Item = &'a [T];
2806 fn next(&mut self) -> Option<&'a [T]> {
2807 if self.v.len() < self.chunk_size {
2810 let (fst, snd) = self.v.split_at(self.v.len() - self.chunk_size);
2817 fn size_hint(&self) -> (usize, Option<usize>) {
2818 let n = self.v.len() / self.chunk_size;
2823 fn count(self) -> usize {
2828 fn nth(&mut self, n: usize) -> Option<Self::Item> {
2829 let (end, overflow) = n.overflowing_mul(self.chunk_size);
2830 if end >= self.v.len() || overflow {
2834 let (fst, _) = self.v.split_at(self.v.len() - end);
2841 fn last(mut self) -> Option<Self::Item> {
2846 unsafe fn __iterator_get_unchecked(&mut self, idx: usize) -> Self::Item {
2847 let end = self.v.len() - idx * self.chunk_size;
2848 let start = end - self.chunk_size;
2850 // SAFETY: mostmy identical to `Chunks::__iterator_get_unchecked`.
2851 unsafe { from_raw_parts(self.v.as_ptr().add(start), self.chunk_size) }
2855 #[stable(feature = "rchunks", since = "1.31.0")]
2856 impl<'a, T> DoubleEndedIterator for RChunksExact<'a, T> {
2858 fn next_back(&mut self) -> Option<&'a [T]> {
2859 if self.v.len() < self.chunk_size {
2862 let (fst, snd) = self.v.split_at(self.chunk_size);
2869 fn nth_back(&mut self, n: usize) -> Option<Self::Item> {
2870 let len = self.len();
2875 // now that we know that `n` corresponds to a chunk,
2876 // none of these operations can underflow/overflow
2877 let offset = (len - n) * self.chunk_size;
2878 let start = self.v.len() - offset;
2879 let end = start + self.chunk_size;
2880 let nth_back = &self.v[start..end];
2881 self.v = &self.v[end..];
2887 #[stable(feature = "rchunks", since = "1.31.0")]
2888 impl<'a, T> ExactSizeIterator for RChunksExact<'a, T> {
2889 fn is_empty(&self) -> bool {
2894 #[unstable(feature = "trusted_len", issue = "37572")]
2895 unsafe impl<T> TrustedLen for RChunksExact<'_, T> {}
2897 #[stable(feature = "rchunks", since = "1.31.0")]
2898 impl<T> FusedIterator for RChunksExact<'_, T> {}
2901 #[unstable(feature = "trusted_random_access", issue = "none")]
2902 unsafe impl<'a, T> TrustedRandomAccess for RChunksExact<'a, T> {}
2905 #[unstable(feature = "trusted_random_access", issue = "none")]
2906 unsafe impl<'a, T> TrustedRandomAccessNoCoerce for RChunksExact<'a, T> {
2907 const MAY_HAVE_SIDE_EFFECT: bool = false;
2910 /// An iterator over a slice in (non-overlapping) mutable chunks (`chunk_size`
2911 /// elements at a time), starting at the end of the slice.
2913 /// When the slice len is not evenly divided by the chunk size, the last up to
2914 /// `chunk_size-1` elements will be omitted but can be retrieved from the
2915 /// [`into_remainder`] function from the iterator.
2917 /// This struct is created by the [`rchunks_exact_mut`] method on [slices].
2922 /// let mut slice = ['l', 'o', 'r', 'e', 'm'];
2923 /// let iter = slice.rchunks_exact_mut(2);
2926 /// [`rchunks_exact_mut`]: slice::rchunks_exact_mut
2927 /// [`into_remainder`]: ChunksExactMut::into_remainder
2930 #[stable(feature = "rchunks", since = "1.31.0")]
2931 #[must_use = "iterators are lazy and do nothing unless consumed"]
2932 pub struct RChunksExactMut<'a, T: 'a> {
2938 impl<'a, T> RChunksExactMut<'a, T> {
2940 pub(super) fn new(slice: &'a mut [T], chunk_size: usize) -> Self {
2941 let rem = slice.len() % chunk_size;
2942 // SAFETY: 0 <= rem <= slice.len() by construction above
2943 let (fst, snd) = unsafe { slice.split_at_mut_unchecked(rem) };
2944 Self { v: snd, rem: fst, chunk_size }
2947 /// Returns the remainder of the original slice that is not going to be
2948 /// returned by the iterator. The returned slice has at most `chunk_size-1`
2950 #[must_use = "`self` will be dropped if the result is not used"]
2951 #[stable(feature = "rchunks", since = "1.31.0")]
2952 pub fn into_remainder(self) -> &'a mut [T] {
2957 #[stable(feature = "rchunks", since = "1.31.0")]
2958 impl<'a, T> Iterator for RChunksExactMut<'a, T> {
2959 type Item = &'a mut [T];
2962 fn next(&mut self) -> Option<&'a mut [T]> {
2963 if self.v.len() < self.chunk_size {
2966 let tmp = mem::replace(&mut self.v, &mut []);
2967 let tmp_len = tmp.len();
2968 let (head, tail) = tmp.split_at_mut(tmp_len - self.chunk_size);
2975 fn size_hint(&self) -> (usize, Option<usize>) {
2976 let n = self.v.len() / self.chunk_size;
2981 fn count(self) -> usize {
2986 fn nth(&mut self, n: usize) -> Option<&'a mut [T]> {
2987 let (end, overflow) = n.overflowing_mul(self.chunk_size);
2988 if end >= self.v.len() || overflow {
2992 let tmp = mem::replace(&mut self.v, &mut []);
2993 let tmp_len = tmp.len();
2994 let (fst, _) = tmp.split_at_mut(tmp_len - end);
3001 fn last(mut self) -> Option<Self::Item> {
3006 unsafe fn __iterator_get_unchecked(&mut self, idx: usize) -> Self::Item {
3007 let end = self.v.len() - idx * self.chunk_size;
3008 let start = end - self.chunk_size;
3009 // SAFETY: see comments for `RChunksMut::__iterator_get_unchecked`.
3010 unsafe { from_raw_parts_mut(self.v.as_mut_ptr().add(start), self.chunk_size) }
3014 #[stable(feature = "rchunks", since = "1.31.0")]
3015 impl<'a, T> DoubleEndedIterator for RChunksExactMut<'a, T> {
3017 fn next_back(&mut self) -> Option<&'a mut [T]> {
3018 if self.v.len() < self.chunk_size {
3021 let tmp = mem::replace(&mut self.v, &mut []);
3022 let (head, tail) = tmp.split_at_mut(self.chunk_size);
3029 fn nth_back(&mut self, n: usize) -> Option<Self::Item> {
3030 let len = self.len();
3035 // now that we know that `n` corresponds to a chunk,
3036 // none of these operations can underflow/overflow
3037 let offset = (len - n) * self.chunk_size;
3038 let start = self.v.len() - offset;
3039 let end = start + self.chunk_size;
3040 let (tmp, tail) = mem::replace(&mut self.v, &mut []).split_at_mut(end);
3041 let (_, nth_back) = tmp.split_at_mut(start);
3048 #[stable(feature = "rchunks", since = "1.31.0")]
3049 impl<T> ExactSizeIterator for RChunksExactMut<'_, T> {
3050 fn is_empty(&self) -> bool {
3055 #[unstable(feature = "trusted_len", issue = "37572")]
3056 unsafe impl<T> TrustedLen for RChunksExactMut<'_, T> {}
3058 #[stable(feature = "rchunks", since = "1.31.0")]
3059 impl<T> FusedIterator for RChunksExactMut<'_, T> {}
3062 #[unstable(feature = "trusted_random_access", issue = "none")]
3063 unsafe impl<'a, T> TrustedRandomAccess for RChunksExactMut<'a, T> {}
3066 #[unstable(feature = "trusted_random_access", issue = "none")]
3067 unsafe impl<'a, T> TrustedRandomAccessNoCoerce for RChunksExactMut<'a, T> {
3068 const MAY_HAVE_SIDE_EFFECT: bool = false;
3072 #[unstable(feature = "trusted_random_access", issue = "none")]
3073 unsafe impl<'a, T> TrustedRandomAccess for Iter<'a, T> {}
3076 #[unstable(feature = "trusted_random_access", issue = "none")]
3077 unsafe impl<'a, T> TrustedRandomAccessNoCoerce for Iter<'a, T> {
3078 const MAY_HAVE_SIDE_EFFECT: bool = false;
3082 #[unstable(feature = "trusted_random_access", issue = "none")]
3083 unsafe impl<'a, T> TrustedRandomAccess for IterMut<'a, T> {}
3086 #[unstable(feature = "trusted_random_access", issue = "none")]
3087 unsafe impl<'a, T> TrustedRandomAccessNoCoerce for IterMut<'a, T> {
3088 const MAY_HAVE_SIDE_EFFECT: bool = false;
3091 /// An iterator over slice in (non-overlapping) chunks separated by a predicate.
3093 /// This struct is created by the [`group_by`] method on [slices].
3095 /// [`group_by`]: slice::group_by
3097 #[unstable(feature = "slice_group_by", issue = "80552")]
3098 #[must_use = "iterators are lazy and do nothing unless consumed"]
3099 pub struct GroupBy<'a, T: 'a, P> {
3104 #[unstable(feature = "slice_group_by", issue = "80552")]
3105 impl<'a, T: 'a, P> GroupBy<'a, T, P> {
3106 pub(super) fn new(slice: &'a [T], predicate: P) -> Self {
3107 GroupBy { slice, predicate }
3111 #[unstable(feature = "slice_group_by", issue = "80552")]
3112 impl<'a, T: 'a, P> Iterator for GroupBy<'a, T, P>
3114 P: FnMut(&T, &T) -> bool,
3116 type Item = &'a [T];
3119 fn next(&mut self) -> Option<Self::Item> {
3120 if self.slice.is_empty() {
3124 let mut iter = self.slice.windows(2);
3125 while let Some([l, r]) = iter.next() {
3126 if (self.predicate)(l, r) { len += 1 } else { break }
3128 let (head, tail) = self.slice.split_at(len);
3135 fn size_hint(&self) -> (usize, Option<usize>) {
3136 if self.slice.is_empty() { (0, Some(0)) } else { (1, Some(self.slice.len())) }
3140 fn last(mut self) -> Option<Self::Item> {
3145 #[unstable(feature = "slice_group_by", issue = "80552")]
3146 impl<'a, T: 'a, P> DoubleEndedIterator for GroupBy<'a, T, P>
3148 P: FnMut(&T, &T) -> bool,
3151 fn next_back(&mut self) -> Option<Self::Item> {
3152 if self.slice.is_empty() {
3156 let mut iter = self.slice.windows(2);
3157 while let Some([l, r]) = iter.next_back() {
3158 if (self.predicate)(l, r) { len += 1 } else { break }
3160 let (head, tail) = self.slice.split_at(self.slice.len() - len);
3167 #[unstable(feature = "slice_group_by", issue = "80552")]
3168 impl<'a, T: 'a, P> FusedIterator for GroupBy<'a, T, P> where P: FnMut(&T, &T) -> bool {}
3170 #[unstable(feature = "slice_group_by", issue = "80552")]
3171 impl<'a, T: 'a + fmt::Debug, P> fmt::Debug for GroupBy<'a, T, P> {
3172 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
3173 f.debug_struct("GroupBy").field("slice", &self.slice).finish()
3177 /// An iterator over slice in (non-overlapping) mutable chunks separated
3180 /// This struct is created by the [`group_by_mut`] method on [slices].
3182 /// [`group_by_mut`]: slice::group_by_mut
3184 #[unstable(feature = "slice_group_by", issue = "80552")]
3185 #[must_use = "iterators are lazy and do nothing unless consumed"]
3186 pub struct GroupByMut<'a, T: 'a, P> {
3191 #[unstable(feature = "slice_group_by", issue = "80552")]
3192 impl<'a, T: 'a, P> GroupByMut<'a, T, P> {
3193 pub(super) fn new(slice: &'a mut [T], predicate: P) -> Self {
3194 GroupByMut { slice, predicate }
3198 #[unstable(feature = "slice_group_by", issue = "80552")]
3199 impl<'a, T: 'a, P> Iterator for GroupByMut<'a, T, P>
3201 P: FnMut(&T, &T) -> bool,
3203 type Item = &'a mut [T];
3206 fn next(&mut self) -> Option<Self::Item> {
3207 if self.slice.is_empty() {
3211 let mut iter = self.slice.windows(2);
3212 while let Some([l, r]) = iter.next() {
3213 if (self.predicate)(l, r) { len += 1 } else { break }
3215 let slice = mem::take(&mut self.slice);
3216 let (head, tail) = slice.split_at_mut(len);
3223 fn size_hint(&self) -> (usize, Option<usize>) {
3224 if self.slice.is_empty() { (0, Some(0)) } else { (1, Some(self.slice.len())) }
3228 fn last(mut self) -> Option<Self::Item> {
3233 #[unstable(feature = "slice_group_by", issue = "80552")]
3234 impl<'a, T: 'a, P> DoubleEndedIterator for GroupByMut<'a, T, P>
3236 P: FnMut(&T, &T) -> bool,
3239 fn next_back(&mut self) -> Option<Self::Item> {
3240 if self.slice.is_empty() {
3244 let mut iter = self.slice.windows(2);
3245 while let Some([l, r]) = iter.next_back() {
3246 if (self.predicate)(l, r) { len += 1 } else { break }
3248 let slice = mem::take(&mut self.slice);
3249 let (head, tail) = slice.split_at_mut(slice.len() - len);
3256 #[unstable(feature = "slice_group_by", issue = "80552")]
3257 impl<'a, T: 'a, P> FusedIterator for GroupByMut<'a, T, P> where P: FnMut(&T, &T) -> bool {}
3259 #[unstable(feature = "slice_group_by", issue = "80552")]
3260 impl<'a, T: 'a + fmt::Debug, P> fmt::Debug for GroupByMut<'a, T, P> {
3261 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
3262 f.debug_struct("GroupByMut").field("slice", &self.slice).finish()