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 pub struct Iter<'a, T: 'a> {
67 end: *const T, // If T is a ZST, this is actually ptr+len. This encoding is picked so that
68 // ptr == end is a quick test for the Iterator being empty, that works
69 // for both ZST and non-ZST.
70 _marker: PhantomData<&'a T>,
73 #[stable(feature = "core_impl_debug", since = "1.9.0")]
74 impl<T: fmt::Debug> fmt::Debug for Iter<'_, T> {
75 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
76 f.debug_tuple("Iter").field(&self.as_slice()).finish()
80 #[stable(feature = "rust1", since = "1.0.0")]
81 unsafe impl<T: Sync> Sync for Iter<'_, T> {}
82 #[stable(feature = "rust1", since = "1.0.0")]
83 unsafe impl<T: Sync> Send for Iter<'_, T> {}
85 impl<'a, T> Iter<'a, T> {
87 pub(super) fn new(slice: &'a [T]) -> Self {
88 let ptr = slice.as_ptr();
89 // SAFETY: Similar to `IterMut::new`.
91 assume(!ptr.is_null());
93 let end = if mem::size_of::<T>() == 0 {
94 (ptr as *const u8).wrapping_add(slice.len()) as *const T
99 Self { ptr: NonNull::new_unchecked(ptr as *mut T), end, _marker: PhantomData }
103 /// Views the underlying data as a subslice of the original data.
105 /// This has the same lifetime as the original slice, and so the
106 /// iterator can continue to be used while this exists.
113 /// // First, we declare a type which has the `iter` method to get the `Iter`
114 /// // struct (`&[usize]` here):
115 /// let slice = &[1, 2, 3];
117 /// // Then, we get the iterator:
118 /// let mut iter = slice.iter();
119 /// // So if we print what `as_slice` method returns here, we have "[1, 2, 3]":
120 /// println!("{:?}", iter.as_slice());
122 /// // Next, we move to the second element of the slice:
124 /// // Now `as_slice` returns "[2, 3]":
125 /// println!("{:?}", iter.as_slice());
127 #[stable(feature = "iter_to_slice", since = "1.4.0")]
128 pub fn as_slice(&self) -> &'a [T] {
133 iterator! {struct Iter -> *const T, &'a T, const, {/* no mut */}, {
134 fn is_sorted_by<F>(self, mut compare: F) -> bool
137 F: FnMut(&Self::Item, &Self::Item) -> Option<Ordering>,
139 self.as_slice().windows(2).all(|w| {
140 compare(&&w[0], &&w[1]).map(|o| o != Ordering::Greater).unwrap_or(false)
145 #[stable(feature = "rust1", since = "1.0.0")]
146 impl<T> Clone for Iter<'_, T> {
147 fn clone(&self) -> Self {
148 Iter { ptr: self.ptr, end: self.end, _marker: self._marker }
152 #[stable(feature = "slice_iter_as_ref", since = "1.13.0")]
153 impl<T> AsRef<[T]> for Iter<'_, T> {
154 fn as_ref(&self) -> &[T] {
159 /// Mutable slice iterator.
161 /// This struct is created by the [`iter_mut`] method on [slices].
168 /// // First, we declare a type which has `iter_mut` method to get the `IterMut`
169 /// // struct (`&[usize]` here):
170 /// let mut slice = &mut [1, 2, 3];
172 /// // Then, we iterate over it and increment each element value:
173 /// for element in slice.iter_mut() {
177 /// // We now have "[2, 3, 4]":
178 /// println!("{:?}", slice);
181 /// [`iter_mut`]: slice::iter_mut
183 #[stable(feature = "rust1", since = "1.0.0")]
184 pub struct IterMut<'a, T: 'a> {
186 end: *mut T, // If T is a ZST, this is actually ptr+len. This encoding is picked so that
187 // ptr == end is a quick test for the Iterator being empty, that works
188 // for both ZST and non-ZST.
189 _marker: PhantomData<&'a mut T>,
192 #[stable(feature = "core_impl_debug", since = "1.9.0")]
193 impl<T: fmt::Debug> fmt::Debug for IterMut<'_, T> {
194 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
195 f.debug_tuple("IterMut").field(&self.make_slice()).finish()
199 #[stable(feature = "rust1", since = "1.0.0")]
200 unsafe impl<T: Sync> Sync for IterMut<'_, T> {}
201 #[stable(feature = "rust1", since = "1.0.0")]
202 unsafe impl<T: Send> Send for IterMut<'_, T> {}
204 impl<'a, T> IterMut<'a, T> {
206 pub(super) fn new(slice: &'a mut [T]) -> Self {
207 let ptr = slice.as_mut_ptr();
208 // SAFETY: There are several things here:
210 // `ptr` has been obtained by `slice.as_ptr()` where `slice` is a valid
211 // reference thus it is non-NUL and safe to use and pass to
212 // `NonNull::new_unchecked` .
214 // Adding `slice.len()` to the starting pointer gives a pointer
215 // at the end of `slice`. `end` will never be dereferenced, only checked
216 // for direct pointer equality with `ptr` to check if the iterator is
219 // In the case of a ZST, the end pointer is just the start pointer plus
220 // the length, to also allows for the fast `ptr == end` check.
222 // See the `next_unchecked!` and `is_empty!` macros as well as the
223 // `post_inc_start` method for more informations.
225 assume(!ptr.is_null());
227 let end = if mem::size_of::<T>() == 0 {
228 (ptr as *mut u8).wrapping_add(slice.len()) as *mut T
233 Self { ptr: NonNull::new_unchecked(ptr), end, _marker: PhantomData }
237 /// Views the underlying data as a subslice of the original data.
239 /// To avoid creating `&mut` references that alias, this is forced
240 /// to consume the iterator.
247 /// // First, we declare a type which has `iter_mut` method to get the `IterMut`
248 /// // struct (`&[usize]` here):
249 /// let mut slice = &mut [1, 2, 3];
252 /// // Then, we get the iterator:
253 /// let mut iter = slice.iter_mut();
254 /// // We move to next element:
256 /// // So if we print what `into_slice` method returns here, we have "[2, 3]":
257 /// println!("{:?}", iter.into_slice());
260 /// // Now let's modify a value of the slice:
262 /// // First we get back the iterator:
263 /// let mut iter = slice.iter_mut();
264 /// // We change the value of the first element of the slice returned by the `next` method:
265 /// *iter.next().unwrap() += 1;
267 /// // Now slice is "[2, 2, 3]":
268 /// println!("{:?}", slice);
270 #[stable(feature = "iter_to_slice", since = "1.4.0")]
271 pub fn into_slice(self) -> &'a mut [T] {
272 // SAFETY: the iterator was created from a mutable slice with pointer
273 // `self.ptr` and length `len!(self)`. This guarantees that all the prerequisites
274 // for `from_raw_parts_mut` are fulfilled.
275 unsafe { from_raw_parts_mut(self.ptr.as_ptr(), len!(self)) }
278 /// Views the underlying data as a subslice of the original data.
280 /// To avoid creating `&mut [T]` references that alias, the returned slice
281 /// borrows its lifetime from the iterator the method is applied on.
288 /// let mut slice: &mut [usize] = &mut [1, 2, 3];
290 /// // First, we get the iterator:
291 /// let mut iter = slice.iter_mut();
292 /// // So if we check what the `as_slice` method returns here, we have "[1, 2, 3]":
293 /// assert_eq!(iter.as_slice(), &[1, 2, 3]);
295 /// // Next, we move to the second element of the slice:
297 /// // Now `as_slice` returns "[2, 3]":
298 /// assert_eq!(iter.as_slice(), &[2, 3]);
300 #[stable(feature = "slice_iter_mut_as_slice", since = "1.53.0")]
301 pub fn as_slice(&self) -> &[T] {
306 #[stable(feature = "slice_iter_mut_as_slice", since = "1.53.0")]
307 impl<T> AsRef<[T]> for IterMut<'_, T> {
308 fn as_ref(&self) -> &[T] {
313 iterator! {struct IterMut -> *mut T, &'a mut T, mut, {mut}, {}}
315 /// An internal abstraction over the splitting iterators, so that
316 /// splitn, splitn_mut etc can be implemented once.
318 pub(super) trait SplitIter: DoubleEndedIterator {
319 /// Marks the underlying iterator as complete, extracting the remaining
320 /// portion of the slice.
321 fn finish(&mut self) -> Option<Self::Item>;
324 /// An iterator over subslices separated by elements that match a predicate
327 /// This struct is created by the [`split`] method on [slices].
332 /// let slice = [10, 40, 33, 20];
333 /// let mut iter = slice.split(|num| num % 3 == 0);
336 /// [`split`]: slice::split
338 #[stable(feature = "rust1", since = "1.0.0")]
339 pub struct Split<'a, T: 'a, P>
341 P: FnMut(&T) -> bool,
343 // Used for `SplitWhitespace` and `SplitAsciiWhitespace` `as_str` methods
344 pub(crate) v: &'a [T],
346 // Used for `SplitAsciiWhitespace` `as_str` method
347 pub(crate) finished: bool,
350 impl<'a, T: 'a, P: FnMut(&T) -> bool> Split<'a, T, P> {
352 pub(super) fn new(slice: &'a [T], pred: P) -> Self {
353 Self { v: slice, pred, finished: false }
357 #[stable(feature = "core_impl_debug", since = "1.9.0")]
358 impl<T: fmt::Debug, P> fmt::Debug for Split<'_, T, P>
360 P: FnMut(&T) -> bool,
362 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
363 f.debug_struct("Split").field("v", &self.v).field("finished", &self.finished).finish()
367 // FIXME(#26925) Remove in favor of `#[derive(Clone)]`
368 #[stable(feature = "rust1", since = "1.0.0")]
369 impl<T, P> Clone for Split<'_, T, P>
371 P: Clone + FnMut(&T) -> bool,
373 fn clone(&self) -> Self {
374 Split { v: self.v, pred: self.pred.clone(), finished: self.finished }
378 #[stable(feature = "rust1", since = "1.0.0")]
379 impl<'a, T, P> Iterator for Split<'a, T, P>
381 P: FnMut(&T) -> bool,
386 fn next(&mut self) -> Option<&'a [T]> {
391 match self.v.iter().position(|x| (self.pred)(x)) {
392 None => self.finish(),
394 let ret = Some(&self.v[..idx]);
395 self.v = &self.v[idx + 1..];
402 fn size_hint(&self) -> (usize, Option<usize>) {
406 // If the predicate doesn't match anything, we yield one slice.
407 // If it matches every element, we yield `len() + 1` empty slices.
408 (1, Some(self.v.len() + 1))
413 #[stable(feature = "rust1", since = "1.0.0")]
414 impl<'a, T, P> DoubleEndedIterator for Split<'a, T, P>
416 P: FnMut(&T) -> bool,
419 fn next_back(&mut self) -> Option<&'a [T]> {
424 match self.v.iter().rposition(|x| (self.pred)(x)) {
425 None => self.finish(),
427 let ret = Some(&self.v[idx + 1..]);
428 self.v = &self.v[..idx];
435 impl<'a, T, P> SplitIter for Split<'a, T, P>
437 P: FnMut(&T) -> bool,
440 fn finish(&mut self) -> Option<&'a [T]> {
444 self.finished = true;
450 #[stable(feature = "fused", since = "1.26.0")]
451 impl<T, P> FusedIterator for Split<'_, T, P> where P: FnMut(&T) -> bool {}
453 /// An iterator over subslices separated by elements that match a predicate
454 /// function. Unlike `Split`, it contains the matched part as a terminator
457 /// This struct is created by the [`split_inclusive`] method on [slices].
462 /// let slice = [10, 40, 33, 20];
463 /// let mut iter = slice.split_inclusive(|num| num % 3 == 0);
466 /// [`split_inclusive`]: slice::split_inclusive
468 #[stable(feature = "split_inclusive", since = "1.51.0")]
469 pub struct SplitInclusive<'a, T: 'a, P>
471 P: FnMut(&T) -> bool,
478 impl<'a, T: 'a, P: FnMut(&T) -> bool> SplitInclusive<'a, T, P> {
480 pub(super) fn new(slice: &'a [T], pred: P) -> Self {
481 Self { v: slice, pred, finished: false }
485 #[stable(feature = "split_inclusive", since = "1.51.0")]
486 impl<T: fmt::Debug, P> fmt::Debug for SplitInclusive<'_, T, P>
488 P: FnMut(&T) -> bool,
490 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
491 f.debug_struct("SplitInclusive")
493 .field("finished", &self.finished)
498 // FIXME(#26925) Remove in favor of `#[derive(Clone)]`
499 #[stable(feature = "split_inclusive", since = "1.51.0")]
500 impl<T, P> Clone for SplitInclusive<'_, T, P>
502 P: Clone + FnMut(&T) -> bool,
504 fn clone(&self) -> Self {
505 SplitInclusive { v: self.v, pred: self.pred.clone(), finished: self.finished }
509 #[stable(feature = "split_inclusive", since = "1.51.0")]
510 impl<'a, T, P> Iterator for SplitInclusive<'a, T, P>
512 P: FnMut(&T) -> bool,
517 fn next(&mut self) -> Option<&'a [T]> {
523 self.v.iter().position(|x| (self.pred)(x)).map(|idx| idx + 1).unwrap_or(self.v.len());
524 if idx == self.v.len() {
525 self.finished = true;
527 let ret = Some(&self.v[..idx]);
528 self.v = &self.v[idx..];
533 fn size_hint(&self) -> (usize, Option<usize>) {
537 // If the predicate doesn't match anything, we yield one slice.
538 // If it matches every element, we yield `len()` one-element slices,
539 // or a single empty slice.
540 (1, Some(cmp::max(1, self.v.len())))
545 #[stable(feature = "split_inclusive", since = "1.51.0")]
546 impl<'a, T, P> DoubleEndedIterator for SplitInclusive<'a, T, P>
548 P: FnMut(&T) -> bool,
551 fn next_back(&mut self) -> Option<&'a [T]> {
556 // The last index of self.v is already checked and found to match
557 // by the last iteration, so we start searching a new match
558 // one index to the left.
559 let remainder = if self.v.is_empty() { &[] } else { &self.v[..(self.v.len() - 1)] };
560 let idx = remainder.iter().rposition(|x| (self.pred)(x)).map(|idx| idx + 1).unwrap_or(0);
562 self.finished = true;
564 let ret = Some(&self.v[idx..]);
565 self.v = &self.v[..idx];
570 #[stable(feature = "split_inclusive", since = "1.51.0")]
571 impl<T, P> FusedIterator for SplitInclusive<'_, T, P> where P: FnMut(&T) -> bool {}
573 /// An iterator over the mutable subslices of the vector which are separated
574 /// by elements that match `pred`.
576 /// This struct is created by the [`split_mut`] method on [slices].
581 /// let mut v = [10, 40, 30, 20, 60, 50];
582 /// let iter = v.split_mut(|num| *num % 3 == 0);
585 /// [`split_mut`]: slice::split_mut
587 #[stable(feature = "rust1", since = "1.0.0")]
588 pub struct SplitMut<'a, T: 'a, P>
590 P: FnMut(&T) -> bool,
597 impl<'a, T: 'a, P: FnMut(&T) -> bool> SplitMut<'a, T, P> {
599 pub(super) fn new(slice: &'a mut [T], pred: P) -> Self {
600 Self { v: slice, pred, finished: false }
604 #[stable(feature = "core_impl_debug", since = "1.9.0")]
605 impl<T: fmt::Debug, P> fmt::Debug for SplitMut<'_, T, P>
607 P: FnMut(&T) -> bool,
609 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
610 f.debug_struct("SplitMut").field("v", &self.v).field("finished", &self.finished).finish()
614 impl<'a, T, P> SplitIter for SplitMut<'a, T, P>
616 P: FnMut(&T) -> bool,
619 fn finish(&mut self) -> Option<&'a mut [T]> {
623 self.finished = true;
624 Some(mem::replace(&mut self.v, &mut []))
629 #[stable(feature = "rust1", since = "1.0.0")]
630 impl<'a, T, P> Iterator for SplitMut<'a, T, P>
632 P: FnMut(&T) -> bool,
634 type Item = &'a mut [T];
637 fn next(&mut self) -> Option<&'a mut [T]> {
643 // work around borrowck limitations
644 let pred = &mut self.pred;
645 self.v.iter().position(|x| (*pred)(x))
648 None => self.finish(),
650 let tmp = mem::replace(&mut self.v, &mut []);
651 let (head, tail) = tmp.split_at_mut(idx);
652 self.v = &mut tail[1..];
659 fn size_hint(&self) -> (usize, Option<usize>) {
663 // If the predicate doesn't match anything, we yield one slice.
664 // If it matches every element, we yield `len() + 1` empty slices.
665 (1, Some(self.v.len() + 1))
670 #[stable(feature = "rust1", since = "1.0.0")]
671 impl<'a, T, P> DoubleEndedIterator for SplitMut<'a, T, P>
673 P: FnMut(&T) -> bool,
676 fn next_back(&mut self) -> Option<&'a mut [T]> {
682 // work around borrowck limitations
683 let pred = &mut self.pred;
684 self.v.iter().rposition(|x| (*pred)(x))
687 None => self.finish(),
689 let tmp = mem::replace(&mut self.v, &mut []);
690 let (head, tail) = tmp.split_at_mut(idx);
698 #[stable(feature = "fused", since = "1.26.0")]
699 impl<T, P> FusedIterator for SplitMut<'_, T, P> where P: FnMut(&T) -> bool {}
701 /// An iterator over the mutable subslices of the vector which are separated
702 /// by elements that match `pred`. Unlike `SplitMut`, it contains the matched
703 /// parts in the ends of the subslices.
705 /// This struct is created by the [`split_inclusive_mut`] method on [slices].
710 /// let mut v = [10, 40, 30, 20, 60, 50];
711 /// let iter = v.split_inclusive_mut(|num| *num % 3 == 0);
714 /// [`split_inclusive_mut`]: slice::split_inclusive_mut
716 #[stable(feature = "split_inclusive", since = "1.51.0")]
717 pub struct SplitInclusiveMut<'a, T: 'a, P>
719 P: FnMut(&T) -> bool,
726 impl<'a, T: 'a, P: FnMut(&T) -> bool> SplitInclusiveMut<'a, T, P> {
728 pub(super) fn new(slice: &'a mut [T], pred: P) -> Self {
729 Self { v: slice, pred, finished: false }
733 #[stable(feature = "split_inclusive", since = "1.51.0")]
734 impl<T: fmt::Debug, P> fmt::Debug for SplitInclusiveMut<'_, T, P>
736 P: FnMut(&T) -> bool,
738 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
739 f.debug_struct("SplitInclusiveMut")
741 .field("finished", &self.finished)
746 #[stable(feature = "split_inclusive", since = "1.51.0")]
747 impl<'a, T, P> Iterator for SplitInclusiveMut<'a, T, P>
749 P: FnMut(&T) -> bool,
751 type Item = &'a mut [T];
754 fn next(&mut self) -> Option<&'a mut [T]> {
760 // work around borrowck limitations
761 let pred = &mut self.pred;
762 self.v.iter().position(|x| (*pred)(x))
764 let idx = idx_opt.map(|idx| idx + 1).unwrap_or(self.v.len());
765 if idx == self.v.len() {
766 self.finished = true;
768 let tmp = mem::replace(&mut self.v, &mut []);
769 let (head, tail) = tmp.split_at_mut(idx);
775 fn size_hint(&self) -> (usize, Option<usize>) {
779 // If the predicate doesn't match anything, we yield one slice.
780 // If it matches every element, we yield `len()` one-element slices,
781 // or a single empty slice.
782 (1, Some(cmp::max(1, self.v.len())))
787 #[stable(feature = "split_inclusive", since = "1.51.0")]
788 impl<'a, T, P> DoubleEndedIterator for SplitInclusiveMut<'a, T, P>
790 P: FnMut(&T) -> bool,
793 fn next_back(&mut self) -> Option<&'a mut [T]> {
798 let idx_opt = if self.v.is_empty() {
801 // work around borrowck limitations
802 let pred = &mut self.pred;
804 // The last index of self.v is already checked and found to match
805 // by the last iteration, so we start searching a new match
806 // one index to the left.
807 let remainder = &self.v[..(self.v.len() - 1)];
808 remainder.iter().rposition(|x| (*pred)(x))
810 let idx = idx_opt.map(|idx| idx + 1).unwrap_or(0);
812 self.finished = true;
814 let tmp = mem::replace(&mut self.v, &mut []);
815 let (head, tail) = tmp.split_at_mut(idx);
821 #[stable(feature = "split_inclusive", since = "1.51.0")]
822 impl<T, P> FusedIterator for SplitInclusiveMut<'_, T, P> where P: FnMut(&T) -> bool {}
824 /// An iterator over subslices separated by elements that match a predicate
825 /// function, starting from the end of the slice.
827 /// This struct is created by the [`rsplit`] method on [slices].
832 /// let slice = [11, 22, 33, 0, 44, 55];
833 /// let iter = slice.rsplit(|num| *num == 0);
836 /// [`rsplit`]: slice::rsplit
838 #[stable(feature = "slice_rsplit", since = "1.27.0")]
839 #[derive(Clone)] // Is this correct, or does it incorrectly require `T: Clone`?
840 pub struct RSplit<'a, T: 'a, P>
842 P: FnMut(&T) -> bool,
844 inner: Split<'a, T, P>,
847 impl<'a, T: 'a, P: FnMut(&T) -> bool> RSplit<'a, T, P> {
849 pub(super) fn new(slice: &'a [T], pred: P) -> Self {
850 Self { inner: Split::new(slice, pred) }
854 #[stable(feature = "slice_rsplit", since = "1.27.0")]
855 impl<T: fmt::Debug, P> fmt::Debug for RSplit<'_, T, P>
857 P: FnMut(&T) -> bool,
859 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
860 f.debug_struct("RSplit")
861 .field("v", &self.inner.v)
862 .field("finished", &self.inner.finished)
867 #[stable(feature = "slice_rsplit", since = "1.27.0")]
868 impl<'a, T, P> Iterator for RSplit<'a, T, P>
870 P: FnMut(&T) -> bool,
875 fn next(&mut self) -> Option<&'a [T]> {
876 self.inner.next_back()
880 fn size_hint(&self) -> (usize, Option<usize>) {
881 self.inner.size_hint()
885 #[stable(feature = "slice_rsplit", since = "1.27.0")]
886 impl<'a, T, P> DoubleEndedIterator for RSplit<'a, T, P>
888 P: FnMut(&T) -> bool,
891 fn next_back(&mut self) -> Option<&'a [T]> {
896 #[stable(feature = "slice_rsplit", since = "1.27.0")]
897 impl<'a, T, P> SplitIter for RSplit<'a, T, P>
899 P: FnMut(&T) -> bool,
902 fn finish(&mut self) -> Option<&'a [T]> {
907 #[stable(feature = "slice_rsplit", since = "1.27.0")]
908 impl<T, P> FusedIterator for RSplit<'_, T, P> where P: FnMut(&T) -> bool {}
910 /// An iterator over the subslices of the vector which are separated
911 /// by elements that match `pred`, starting from the end of the slice.
913 /// This struct is created by the [`rsplit_mut`] method on [slices].
918 /// let mut slice = [11, 22, 33, 0, 44, 55];
919 /// let iter = slice.rsplit_mut(|num| *num == 0);
922 /// [`rsplit_mut`]: slice::rsplit_mut
924 #[stable(feature = "slice_rsplit", since = "1.27.0")]
925 pub struct RSplitMut<'a, T: 'a, P>
927 P: FnMut(&T) -> bool,
929 inner: SplitMut<'a, T, P>,
932 impl<'a, T: 'a, P: FnMut(&T) -> bool> RSplitMut<'a, T, P> {
934 pub(super) fn new(slice: &'a mut [T], pred: P) -> Self {
935 Self { inner: SplitMut::new(slice, pred) }
939 #[stable(feature = "slice_rsplit", since = "1.27.0")]
940 impl<T: fmt::Debug, P> fmt::Debug for RSplitMut<'_, T, P>
942 P: FnMut(&T) -> bool,
944 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
945 f.debug_struct("RSplitMut")
946 .field("v", &self.inner.v)
947 .field("finished", &self.inner.finished)
952 #[stable(feature = "slice_rsplit", since = "1.27.0")]
953 impl<'a, T, P> SplitIter for RSplitMut<'a, T, P>
955 P: FnMut(&T) -> bool,
958 fn finish(&mut self) -> Option<&'a mut [T]> {
963 #[stable(feature = "slice_rsplit", since = "1.27.0")]
964 impl<'a, T, P> Iterator for RSplitMut<'a, T, P>
966 P: FnMut(&T) -> bool,
968 type Item = &'a mut [T];
971 fn next(&mut self) -> Option<&'a mut [T]> {
972 self.inner.next_back()
976 fn size_hint(&self) -> (usize, Option<usize>) {
977 self.inner.size_hint()
981 #[stable(feature = "slice_rsplit", since = "1.27.0")]
982 impl<'a, T, P> DoubleEndedIterator for RSplitMut<'a, T, P>
984 P: FnMut(&T) -> bool,
987 fn next_back(&mut self) -> Option<&'a mut [T]> {
992 #[stable(feature = "slice_rsplit", since = "1.27.0")]
993 impl<T, P> FusedIterator for RSplitMut<'_, T, P> where P: FnMut(&T) -> bool {}
995 /// An private iterator over subslices separated by elements that
996 /// match a predicate function, splitting at most a fixed number of
999 struct GenericSplitN<I> {
1004 impl<T, I: SplitIter<Item = T>> Iterator for GenericSplitN<I> {
1008 fn next(&mut self) -> Option<T> {
1023 fn size_hint(&self) -> (usize, Option<usize>) {
1024 let (lower, upper_opt) = self.iter.size_hint();
1026 cmp::min(self.count, lower),
1027 Some(upper_opt.map_or(self.count, |upper| cmp::min(self.count, upper))),
1032 /// An iterator over subslices separated by elements that match a predicate
1033 /// function, limited to a given number of splits.
1035 /// This struct is created by the [`splitn`] method on [slices].
1040 /// let slice = [10, 40, 30, 20, 60, 50];
1041 /// let iter = slice.splitn(2, |num| *num % 3 == 0);
1044 /// [`splitn`]: slice::splitn
1046 #[stable(feature = "rust1", since = "1.0.0")]
1047 pub struct SplitN<'a, T: 'a, P>
1049 P: FnMut(&T) -> bool,
1051 inner: GenericSplitN<Split<'a, T, P>>,
1054 impl<'a, T: 'a, P: FnMut(&T) -> bool> SplitN<'a, T, P> {
1056 pub(super) fn new(s: Split<'a, T, P>, n: usize) -> Self {
1057 Self { inner: GenericSplitN { iter: s, count: n } }
1061 #[stable(feature = "core_impl_debug", since = "1.9.0")]
1062 impl<T: fmt::Debug, P> fmt::Debug for SplitN<'_, T, P>
1064 P: FnMut(&T) -> bool,
1066 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
1067 f.debug_struct("SplitN").field("inner", &self.inner).finish()
1071 /// An iterator over subslices separated by elements that match a
1072 /// predicate function, limited to a given number of splits, starting
1073 /// from the end of the slice.
1075 /// This struct is created by the [`rsplitn`] method on [slices].
1080 /// let slice = [10, 40, 30, 20, 60, 50];
1081 /// let iter = slice.rsplitn(2, |num| *num % 3 == 0);
1084 /// [`rsplitn`]: slice::rsplitn
1086 #[stable(feature = "rust1", since = "1.0.0")]
1087 pub struct RSplitN<'a, T: 'a, P>
1089 P: FnMut(&T) -> bool,
1091 inner: GenericSplitN<RSplit<'a, T, P>>,
1094 impl<'a, T: 'a, P: FnMut(&T) -> bool> RSplitN<'a, T, P> {
1096 pub(super) fn new(s: RSplit<'a, T, P>, n: usize) -> Self {
1097 Self { inner: GenericSplitN { iter: s, count: n } }
1101 #[stable(feature = "core_impl_debug", since = "1.9.0")]
1102 impl<T: fmt::Debug, P> fmt::Debug for RSplitN<'_, T, P>
1104 P: FnMut(&T) -> bool,
1106 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
1107 f.debug_struct("RSplitN").field("inner", &self.inner).finish()
1111 /// An iterator over subslices separated by elements that match a predicate
1112 /// function, limited to a given number of splits.
1114 /// This struct is created by the [`splitn_mut`] method on [slices].
1119 /// let mut slice = [10, 40, 30, 20, 60, 50];
1120 /// let iter = slice.splitn_mut(2, |num| *num % 3 == 0);
1123 /// [`splitn_mut`]: slice::splitn_mut
1125 #[stable(feature = "rust1", since = "1.0.0")]
1126 pub struct SplitNMut<'a, T: 'a, P>
1128 P: FnMut(&T) -> bool,
1130 inner: GenericSplitN<SplitMut<'a, T, P>>,
1133 impl<'a, T: 'a, P: FnMut(&T) -> bool> SplitNMut<'a, T, P> {
1135 pub(super) fn new(s: SplitMut<'a, T, P>, n: usize) -> Self {
1136 Self { inner: GenericSplitN { iter: s, count: n } }
1140 #[stable(feature = "core_impl_debug", since = "1.9.0")]
1141 impl<T: fmt::Debug, P> fmt::Debug for SplitNMut<'_, T, P>
1143 P: FnMut(&T) -> bool,
1145 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
1146 f.debug_struct("SplitNMut").field("inner", &self.inner).finish()
1150 /// An iterator over subslices separated by elements that match a
1151 /// predicate function, limited to a given number of splits, starting
1152 /// from the end of the slice.
1154 /// This struct is created by the [`rsplitn_mut`] method on [slices].
1159 /// let mut slice = [10, 40, 30, 20, 60, 50];
1160 /// let iter = slice.rsplitn_mut(2, |num| *num % 3 == 0);
1163 /// [`rsplitn_mut`]: slice::rsplitn_mut
1165 #[stable(feature = "rust1", since = "1.0.0")]
1166 pub struct RSplitNMut<'a, T: 'a, P>
1168 P: FnMut(&T) -> bool,
1170 inner: GenericSplitN<RSplitMut<'a, T, P>>,
1173 impl<'a, T: 'a, P: FnMut(&T) -> bool> RSplitNMut<'a, T, P> {
1175 pub(super) fn new(s: RSplitMut<'a, T, P>, n: usize) -> Self {
1176 Self { inner: GenericSplitN { iter: s, count: n } }
1180 #[stable(feature = "core_impl_debug", since = "1.9.0")]
1181 impl<T: fmt::Debug, P> fmt::Debug for RSplitNMut<'_, T, P>
1183 P: FnMut(&T) -> bool,
1185 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
1186 f.debug_struct("RSplitNMut").field("inner", &self.inner).finish()
1190 forward_iterator! { SplitN: T, &'a [T] }
1191 forward_iterator! { RSplitN: T, &'a [T] }
1192 forward_iterator! { SplitNMut: T, &'a mut [T] }
1193 forward_iterator! { RSplitNMut: T, &'a mut [T] }
1195 /// An iterator over overlapping subslices of length `size`.
1197 /// This struct is created by the [`windows`] method on [slices].
1202 /// let slice = ['r', 'u', 's', 't'];
1203 /// let iter = slice.windows(2);
1206 /// [`windows`]: slice::windows
1209 #[stable(feature = "rust1", since = "1.0.0")]
1210 pub struct Windows<'a, T: 'a> {
1215 impl<'a, T: 'a> Windows<'a, T> {
1217 pub(super) fn new(slice: &'a [T], size: NonZeroUsize) -> Self {
1218 Self { v: slice, size }
1222 // FIXME(#26925) Remove in favor of `#[derive(Clone)]`
1223 #[stable(feature = "rust1", since = "1.0.0")]
1224 impl<T> Clone for Windows<'_, T> {
1225 fn clone(&self) -> Self {
1226 Windows { v: self.v, size: self.size }
1230 #[stable(feature = "rust1", since = "1.0.0")]
1231 impl<'a, T> Iterator for Windows<'a, T> {
1232 type Item = &'a [T];
1235 fn next(&mut self) -> Option<&'a [T]> {
1236 if self.size.get() > self.v.len() {
1239 let ret = Some(&self.v[..self.size.get()]);
1240 self.v = &self.v[1..];
1246 fn size_hint(&self) -> (usize, Option<usize>) {
1247 if self.size.get() > self.v.len() {
1250 let size = self.v.len() - self.size.get() + 1;
1256 fn count(self) -> usize {
1261 fn nth(&mut self, n: usize) -> Option<Self::Item> {
1262 let (end, overflow) = self.size.get().overflowing_add(n);
1263 if end > self.v.len() || overflow {
1267 let nth = &self.v[n..end];
1268 self.v = &self.v[n + 1..];
1274 fn last(self) -> Option<Self::Item> {
1275 if self.size.get() > self.v.len() {
1278 let start = self.v.len() - self.size.get();
1279 Some(&self.v[start..])
1284 unsafe fn __iterator_get_unchecked(&mut self, idx: usize) -> Self::Item {
1285 // SAFETY: since the caller guarantees that `i` is in bounds,
1286 // which means that `i` cannot overflow an `isize`, and the
1287 // slice created by `from_raw_parts` is a subslice of `self.v`
1288 // thus is guaranteed to be valid for the lifetime `'a` of `self.v`.
1289 unsafe { from_raw_parts(self.v.as_ptr().add(idx), self.size.get()) }
1293 #[stable(feature = "rust1", since = "1.0.0")]
1294 impl<'a, T> DoubleEndedIterator for Windows<'a, T> {
1296 fn next_back(&mut self) -> Option<&'a [T]> {
1297 if self.size.get() > self.v.len() {
1300 let ret = Some(&self.v[self.v.len() - self.size.get()..]);
1301 self.v = &self.v[..self.v.len() - 1];
1307 fn nth_back(&mut self, n: usize) -> Option<Self::Item> {
1308 let (end, overflow) = self.v.len().overflowing_sub(n);
1309 if end < self.size.get() || overflow {
1313 let ret = &self.v[end - self.size.get()..end];
1314 self.v = &self.v[..end - 1];
1320 #[stable(feature = "rust1", since = "1.0.0")]
1321 impl<T> ExactSizeIterator for Windows<'_, T> {}
1323 #[unstable(feature = "trusted_len", issue = "37572")]
1324 unsafe impl<T> TrustedLen for Windows<'_, T> {}
1326 #[stable(feature = "fused", since = "1.26.0")]
1327 impl<T> FusedIterator for Windows<'_, T> {}
1330 #[unstable(feature = "trusted_random_access", issue = "none")]
1331 unsafe impl<'a, T> TrustedRandomAccess for Windows<'a, T> {}
1334 #[unstable(feature = "trusted_random_access", issue = "none")]
1335 unsafe impl<'a, T> TrustedRandomAccessNoCoerce for Windows<'a, T> {
1336 const MAY_HAVE_SIDE_EFFECT: bool = false;
1339 /// An iterator over a slice in (non-overlapping) chunks (`chunk_size` elements at a
1340 /// time), starting at the beginning of the slice.
1342 /// When the slice len is not evenly divided by the chunk size, the last slice
1343 /// of the iteration will be the remainder.
1345 /// This struct is created by the [`chunks`] method on [slices].
1350 /// let slice = ['l', 'o', 'r', 'e', 'm'];
1351 /// let iter = slice.chunks(2);
1354 /// [`chunks`]: slice::chunks
1357 #[stable(feature = "rust1", since = "1.0.0")]
1358 pub struct Chunks<'a, T: 'a> {
1363 impl<'a, T: 'a> Chunks<'a, T> {
1365 pub(super) fn new(slice: &'a [T], size: usize) -> Self {
1366 Self { v: slice, chunk_size: size }
1370 // FIXME(#26925) Remove in favor of `#[derive(Clone)]`
1371 #[stable(feature = "rust1", since = "1.0.0")]
1372 impl<T> Clone for Chunks<'_, T> {
1373 fn clone(&self) -> Self {
1374 Chunks { v: self.v, chunk_size: self.chunk_size }
1378 #[stable(feature = "rust1", since = "1.0.0")]
1379 impl<'a, T> Iterator for Chunks<'a, T> {
1380 type Item = &'a [T];
1383 fn next(&mut self) -> Option<&'a [T]> {
1384 if self.v.is_empty() {
1387 let chunksz = cmp::min(self.v.len(), self.chunk_size);
1388 let (fst, snd) = self.v.split_at(chunksz);
1395 fn size_hint(&self) -> (usize, Option<usize>) {
1396 if self.v.is_empty() {
1399 let n = self.v.len() / self.chunk_size;
1400 let rem = self.v.len() % self.chunk_size;
1401 let n = if rem > 0 { n + 1 } else { n };
1407 fn count(self) -> usize {
1412 fn nth(&mut self, n: usize) -> Option<Self::Item> {
1413 let (start, overflow) = n.overflowing_mul(self.chunk_size);
1414 if start >= self.v.len() || overflow {
1418 let end = match start.checked_add(self.chunk_size) {
1419 Some(sum) => cmp::min(self.v.len(), sum),
1420 None => self.v.len(),
1422 let nth = &self.v[start..end];
1423 self.v = &self.v[end..];
1429 fn last(self) -> Option<Self::Item> {
1430 if self.v.is_empty() {
1433 let start = (self.v.len() - 1) / self.chunk_size * self.chunk_size;
1434 Some(&self.v[start..])
1439 unsafe fn __iterator_get_unchecked(&mut self, idx: usize) -> Self::Item {
1440 let start = idx * self.chunk_size;
1441 // SAFETY: the caller guarantees that `i` is in bounds,
1442 // which means that `start` must be in bounds of the
1443 // underlying `self.v` slice, and we made sure that `len`
1444 // is also in bounds of `self.v`. Thus, `start` cannot overflow
1445 // an `isize`, and the slice constructed by `from_raw_parts`
1446 // is a subslice of `self.v` which is guaranteed to be valid
1447 // for the lifetime `'a` of `self.v`.
1449 let len = cmp::min(self.v.len().unchecked_sub(start), self.chunk_size);
1450 from_raw_parts(self.v.as_ptr().add(start), len)
1455 #[stable(feature = "rust1", since = "1.0.0")]
1456 impl<'a, T> DoubleEndedIterator for Chunks<'a, T> {
1458 fn next_back(&mut self) -> Option<&'a [T]> {
1459 if self.v.is_empty() {
1462 let remainder = self.v.len() % self.chunk_size;
1463 let chunksz = if remainder != 0 { remainder } else { self.chunk_size };
1464 let (fst, snd) = self.v.split_at(self.v.len() - chunksz);
1471 fn nth_back(&mut self, n: usize) -> Option<Self::Item> {
1472 let len = self.len();
1477 let start = (len - 1 - n) * self.chunk_size;
1478 let end = match start.checked_add(self.chunk_size) {
1479 Some(res) => cmp::min(self.v.len(), res),
1480 None => self.v.len(),
1482 let nth_back = &self.v[start..end];
1483 self.v = &self.v[..start];
1489 #[stable(feature = "rust1", since = "1.0.0")]
1490 impl<T> ExactSizeIterator for Chunks<'_, T> {}
1492 #[unstable(feature = "trusted_len", issue = "37572")]
1493 unsafe impl<T> TrustedLen for Chunks<'_, T> {}
1495 #[stable(feature = "fused", since = "1.26.0")]
1496 impl<T> FusedIterator for Chunks<'_, T> {}
1499 #[unstable(feature = "trusted_random_access", issue = "none")]
1500 unsafe impl<'a, T> TrustedRandomAccess for Chunks<'a, T> {}
1503 #[unstable(feature = "trusted_random_access", issue = "none")]
1504 unsafe impl<'a, T> TrustedRandomAccessNoCoerce for Chunks<'a, T> {
1505 const MAY_HAVE_SIDE_EFFECT: bool = false;
1508 /// An iterator over a slice in (non-overlapping) mutable chunks (`chunk_size`
1509 /// elements at a time), starting at the beginning of the slice.
1511 /// When the slice len is not evenly divided by the chunk size, the last slice
1512 /// of the iteration will be the remainder.
1514 /// This struct is created by the [`chunks_mut`] method on [slices].
1519 /// let mut slice = ['l', 'o', 'r', 'e', 'm'];
1520 /// let iter = slice.chunks_mut(2);
1523 /// [`chunks_mut`]: slice::chunks_mut
1526 #[stable(feature = "rust1", since = "1.0.0")]
1527 pub struct ChunksMut<'a, T: 'a> {
1532 impl<'a, T: 'a> ChunksMut<'a, T> {
1534 pub(super) fn new(slice: &'a mut [T], size: usize) -> Self {
1535 Self { v: slice, chunk_size: size }
1539 #[stable(feature = "rust1", since = "1.0.0")]
1540 impl<'a, T> Iterator for ChunksMut<'a, T> {
1541 type Item = &'a mut [T];
1544 fn next(&mut self) -> Option<&'a mut [T]> {
1545 if self.v.is_empty() {
1548 let sz = cmp::min(self.v.len(), self.chunk_size);
1549 let tmp = mem::replace(&mut self.v, &mut []);
1550 let (head, tail) = tmp.split_at_mut(sz);
1557 fn size_hint(&self) -> (usize, Option<usize>) {
1558 if self.v.is_empty() {
1561 let n = self.v.len() / self.chunk_size;
1562 let rem = self.v.len() % self.chunk_size;
1563 let n = if rem > 0 { n + 1 } else { n };
1569 fn count(self) -> usize {
1574 fn nth(&mut self, n: usize) -> Option<&'a mut [T]> {
1575 let (start, overflow) = n.overflowing_mul(self.chunk_size);
1576 if start >= self.v.len() || overflow {
1580 let end = match start.checked_add(self.chunk_size) {
1581 Some(sum) => cmp::min(self.v.len(), sum),
1582 None => self.v.len(),
1584 let tmp = mem::replace(&mut self.v, &mut []);
1585 let (head, tail) = tmp.split_at_mut(end);
1586 let (_, nth) = head.split_at_mut(start);
1593 fn last(self) -> Option<Self::Item> {
1594 if self.v.is_empty() {
1597 let start = (self.v.len() - 1) / self.chunk_size * self.chunk_size;
1598 Some(&mut self.v[start..])
1603 unsafe fn __iterator_get_unchecked(&mut self, idx: usize) -> Self::Item {
1604 let start = idx * self.chunk_size;
1605 // SAFETY: see comments for `Chunks::__iterator_get_unchecked`.
1607 // Also note that the caller also guarantees that we're never called
1608 // with the same index again, and that no other methods that will
1609 // access this subslice are called, so it is valid for the returned
1610 // slice to be mutable.
1612 let len = cmp::min(self.v.len().unchecked_sub(start), self.chunk_size);
1613 from_raw_parts_mut(self.v.as_mut_ptr().add(start), len)
1618 #[stable(feature = "rust1", since = "1.0.0")]
1619 impl<'a, T> DoubleEndedIterator for ChunksMut<'a, T> {
1621 fn next_back(&mut self) -> Option<&'a mut [T]> {
1622 if self.v.is_empty() {
1625 let remainder = self.v.len() % self.chunk_size;
1626 let sz = if remainder != 0 { remainder } else { self.chunk_size };
1627 let tmp = mem::replace(&mut self.v, &mut []);
1628 let tmp_len = tmp.len();
1629 let (head, tail) = tmp.split_at_mut(tmp_len - sz);
1636 fn nth_back(&mut self, n: usize) -> Option<Self::Item> {
1637 let len = self.len();
1642 let start = (len - 1 - n) * self.chunk_size;
1643 let end = match start.checked_add(self.chunk_size) {
1644 Some(res) => cmp::min(self.v.len(), res),
1645 None => self.v.len(),
1647 let (temp, _tail) = mem::replace(&mut self.v, &mut []).split_at_mut(end);
1648 let (head, nth_back) = temp.split_at_mut(start);
1655 #[stable(feature = "rust1", since = "1.0.0")]
1656 impl<T> ExactSizeIterator for ChunksMut<'_, T> {}
1658 #[unstable(feature = "trusted_len", issue = "37572")]
1659 unsafe impl<T> TrustedLen for ChunksMut<'_, T> {}
1661 #[stable(feature = "fused", since = "1.26.0")]
1662 impl<T> FusedIterator for ChunksMut<'_, T> {}
1665 #[unstable(feature = "trusted_random_access", issue = "none")]
1666 unsafe impl<'a, T> TrustedRandomAccess for ChunksMut<'a, T> {}
1669 #[unstable(feature = "trusted_random_access", issue = "none")]
1670 unsafe impl<'a, T> TrustedRandomAccessNoCoerce for ChunksMut<'a, T> {
1671 const MAY_HAVE_SIDE_EFFECT: bool = false;
1674 /// An iterator over a slice in (non-overlapping) chunks (`chunk_size` elements at a
1675 /// time), starting at the beginning of the slice.
1677 /// When the slice len is not evenly divided by the chunk size, the last
1678 /// up to `chunk_size-1` elements will be omitted but can be retrieved from
1679 /// the [`remainder`] function from the iterator.
1681 /// This struct is created by the [`chunks_exact`] method on [slices].
1686 /// let slice = ['l', 'o', 'r', 'e', 'm'];
1687 /// let iter = slice.chunks_exact(2);
1690 /// [`chunks_exact`]: slice::chunks_exact
1691 /// [`remainder`]: ChunksExact::remainder
1694 #[stable(feature = "chunks_exact", since = "1.31.0")]
1695 pub struct ChunksExact<'a, T: 'a> {
1701 impl<'a, T> ChunksExact<'a, T> {
1703 pub(super) fn new(slice: &'a [T], chunk_size: usize) -> Self {
1704 let rem = slice.len() % chunk_size;
1705 let fst_len = slice.len() - rem;
1706 // SAFETY: 0 <= fst_len <= slice.len() by construction above
1707 let (fst, snd) = unsafe { slice.split_at_unchecked(fst_len) };
1708 Self { v: fst, rem: snd, chunk_size }
1711 /// Returns the remainder of the original slice that is not going to be
1712 /// returned by the iterator. The returned slice has at most `chunk_size-1`
1714 #[stable(feature = "chunks_exact", since = "1.31.0")]
1715 pub fn remainder(&self) -> &'a [T] {
1720 // FIXME(#26925) Remove in favor of `#[derive(Clone)]`
1721 #[stable(feature = "chunks_exact", since = "1.31.0")]
1722 impl<T> Clone for ChunksExact<'_, T> {
1723 fn clone(&self) -> Self {
1724 ChunksExact { v: self.v, rem: self.rem, chunk_size: self.chunk_size }
1728 #[stable(feature = "chunks_exact", since = "1.31.0")]
1729 impl<'a, T> Iterator for ChunksExact<'a, T> {
1730 type Item = &'a [T];
1733 fn next(&mut self) -> Option<&'a [T]> {
1734 if self.v.len() < self.chunk_size {
1737 let (fst, snd) = self.v.split_at(self.chunk_size);
1744 fn size_hint(&self) -> (usize, Option<usize>) {
1745 let n = self.v.len() / self.chunk_size;
1750 fn count(self) -> usize {
1755 fn nth(&mut self, n: usize) -> Option<Self::Item> {
1756 let (start, overflow) = n.overflowing_mul(self.chunk_size);
1757 if start >= self.v.len() || overflow {
1761 let (_, snd) = self.v.split_at(start);
1768 fn last(mut self) -> Option<Self::Item> {
1773 unsafe fn __iterator_get_unchecked(&mut self, idx: usize) -> Self::Item {
1774 let start = idx * self.chunk_size;
1775 // SAFETY: mostly identical to `Chunks::__iterator_get_unchecked`.
1776 unsafe { from_raw_parts(self.v.as_ptr().add(start), self.chunk_size) }
1780 #[stable(feature = "chunks_exact", since = "1.31.0")]
1781 impl<'a, T> DoubleEndedIterator for ChunksExact<'a, T> {
1783 fn next_back(&mut self) -> Option<&'a [T]> {
1784 if self.v.len() < self.chunk_size {
1787 let (fst, snd) = self.v.split_at(self.v.len() - self.chunk_size);
1794 fn nth_back(&mut self, n: usize) -> Option<Self::Item> {
1795 let len = self.len();
1800 let start = (len - 1 - n) * self.chunk_size;
1801 let end = start + self.chunk_size;
1802 let nth_back = &self.v[start..end];
1803 self.v = &self.v[..start];
1809 #[stable(feature = "chunks_exact", since = "1.31.0")]
1810 impl<T> ExactSizeIterator for ChunksExact<'_, T> {
1811 fn is_empty(&self) -> bool {
1816 #[unstable(feature = "trusted_len", issue = "37572")]
1817 unsafe impl<T> TrustedLen for ChunksExact<'_, T> {}
1819 #[stable(feature = "chunks_exact", since = "1.31.0")]
1820 impl<T> FusedIterator for ChunksExact<'_, T> {}
1823 #[unstable(feature = "trusted_random_access", issue = "none")]
1824 unsafe impl<'a, T> TrustedRandomAccess for ChunksExact<'a, T> {}
1827 #[unstable(feature = "trusted_random_access", issue = "none")]
1828 unsafe impl<'a, T> TrustedRandomAccessNoCoerce for ChunksExact<'a, T> {
1829 const MAY_HAVE_SIDE_EFFECT: bool = false;
1832 /// An iterator over a slice in (non-overlapping) mutable chunks (`chunk_size`
1833 /// elements at a time), starting at the beginning of the slice.
1835 /// When the slice len is not evenly divided by the chunk size, the last up to
1836 /// `chunk_size-1` elements will be omitted but can be retrieved from the
1837 /// [`into_remainder`] function from the iterator.
1839 /// This struct is created by the [`chunks_exact_mut`] method on [slices].
1844 /// let mut slice = ['l', 'o', 'r', 'e', 'm'];
1845 /// let iter = slice.chunks_exact_mut(2);
1848 /// [`chunks_exact_mut`]: slice::chunks_exact_mut
1849 /// [`into_remainder`]: ChunksExactMut::into_remainder
1852 #[stable(feature = "chunks_exact", since = "1.31.0")]
1853 pub struct ChunksExactMut<'a, T: 'a> {
1859 impl<'a, T> ChunksExactMut<'a, T> {
1861 pub(super) fn new(slice: &'a mut [T], chunk_size: usize) -> Self {
1862 let rem = slice.len() % chunk_size;
1863 let fst_len = slice.len() - rem;
1864 // SAFETY: 0 <= fst_len <= slice.len() by construction above
1865 let (fst, snd) = unsafe { slice.split_at_mut_unchecked(fst_len) };
1866 Self { v: fst, rem: snd, chunk_size }
1869 /// Returns the remainder of the original slice that is not going to be
1870 /// returned by the iterator. The returned slice has at most `chunk_size-1`
1872 #[stable(feature = "chunks_exact", since = "1.31.0")]
1873 pub fn into_remainder(self) -> &'a mut [T] {
1878 #[stable(feature = "chunks_exact", since = "1.31.0")]
1879 impl<'a, T> Iterator for ChunksExactMut<'a, T> {
1880 type Item = &'a mut [T];
1883 fn next(&mut self) -> Option<&'a mut [T]> {
1884 if self.v.len() < self.chunk_size {
1887 let tmp = mem::replace(&mut self.v, &mut []);
1888 let (head, tail) = tmp.split_at_mut(self.chunk_size);
1895 fn size_hint(&self) -> (usize, Option<usize>) {
1896 let n = self.v.len() / self.chunk_size;
1901 fn count(self) -> usize {
1906 fn nth(&mut self, n: usize) -> Option<&'a mut [T]> {
1907 let (start, overflow) = n.overflowing_mul(self.chunk_size);
1908 if start >= self.v.len() || overflow {
1912 let tmp = mem::replace(&mut self.v, &mut []);
1913 let (_, snd) = tmp.split_at_mut(start);
1920 fn last(mut self) -> Option<Self::Item> {
1925 unsafe fn __iterator_get_unchecked(&mut self, idx: usize) -> Self::Item {
1926 let start = idx * self.chunk_size;
1927 // SAFETY: see comments for `ChunksMut::__iterator_get_unchecked`.
1928 unsafe { from_raw_parts_mut(self.v.as_mut_ptr().add(start), self.chunk_size) }
1932 #[stable(feature = "chunks_exact", since = "1.31.0")]
1933 impl<'a, T> DoubleEndedIterator for ChunksExactMut<'a, T> {
1935 fn next_back(&mut self) -> Option<&'a mut [T]> {
1936 if self.v.len() < self.chunk_size {
1939 let tmp = mem::replace(&mut self.v, &mut []);
1940 let tmp_len = tmp.len();
1941 let (head, tail) = tmp.split_at_mut(tmp_len - self.chunk_size);
1948 fn nth_back(&mut self, n: usize) -> Option<Self::Item> {
1949 let len = self.len();
1954 let start = (len - 1 - n) * self.chunk_size;
1955 let end = start + self.chunk_size;
1956 let (temp, _tail) = mem::replace(&mut self.v, &mut []).split_at_mut(end);
1957 let (head, nth_back) = temp.split_at_mut(start);
1964 #[stable(feature = "chunks_exact", since = "1.31.0")]
1965 impl<T> ExactSizeIterator for ChunksExactMut<'_, T> {
1966 fn is_empty(&self) -> bool {
1971 #[unstable(feature = "trusted_len", issue = "37572")]
1972 unsafe impl<T> TrustedLen for ChunksExactMut<'_, T> {}
1974 #[stable(feature = "chunks_exact", since = "1.31.0")]
1975 impl<T> FusedIterator for ChunksExactMut<'_, T> {}
1978 #[unstable(feature = "trusted_random_access", issue = "none")]
1979 unsafe impl<'a, T> TrustedRandomAccess for ChunksExactMut<'a, T> {}
1982 #[unstable(feature = "trusted_random_access", issue = "none")]
1983 unsafe impl<'a, T> TrustedRandomAccessNoCoerce for ChunksExactMut<'a, T> {
1984 const MAY_HAVE_SIDE_EFFECT: bool = false;
1987 /// A windowed iterator over a slice in overlapping chunks (`N` elements at a
1988 /// time), starting at the beginning of the slice
1990 /// This struct is created by the [`array_windows`] method on [slices].
1995 /// #![feature(array_windows)]
1997 /// let slice = [0, 1, 2, 3];
1998 /// let iter = slice.array_windows::<2>();
2001 /// [`array_windows`]: slice::array_windows
2003 #[derive(Debug, Clone, Copy)]
2004 #[unstable(feature = "array_windows", issue = "75027")]
2005 pub struct ArrayWindows<'a, T: 'a, const N: usize> {
2006 slice_head: *const T,
2008 marker: PhantomData<&'a [T; N]>,
2011 impl<'a, T: 'a, const N: usize> ArrayWindows<'a, T, N> {
2013 pub(super) fn new(slice: &'a [T]) -> Self {
2014 let num_windows = slice.len().saturating_sub(N - 1);
2015 Self { slice_head: slice.as_ptr(), num: num_windows, marker: PhantomData }
2019 #[unstable(feature = "array_windows", issue = "75027")]
2020 impl<'a, T, const N: usize> Iterator for ArrayWindows<'a, T, N> {
2021 type Item = &'a [T; N];
2024 fn next(&mut self) -> Option<Self::Item> {
2029 // This is safe because it's indexing into a slice guaranteed to be length > N.
2030 let ret = unsafe { &*self.slice_head.cast::<[T; N]>() };
2031 // SAFETY: Guaranteed that there are at least 1 item remaining otherwise
2032 // earlier branch would've been hit
2033 self.slice_head = unsafe { self.slice_head.add(1) };
2040 fn size_hint(&self) -> (usize, Option<usize>) {
2041 (self.num, Some(self.num))
2045 fn count(self) -> usize {
2050 fn nth(&mut self, n: usize) -> Option<Self::Item> {
2056 // This is safe because it's indexing into a slice guaranteed to be length > N.
2057 let ret = unsafe { &*self.slice_head.add(n).cast::<[T; N]>() };
2058 // SAFETY: Guaranteed that there are at least n items remaining
2059 self.slice_head = unsafe { self.slice_head.add(n + 1) };
2066 fn last(mut self) -> Option<Self::Item> {
2067 self.nth(self.num.checked_sub(1)?)
2071 #[unstable(feature = "array_windows", issue = "75027")]
2072 impl<'a, T, const N: usize> DoubleEndedIterator for ArrayWindows<'a, T, N> {
2074 fn next_back(&mut self) -> Option<&'a [T; N]> {
2078 // SAFETY: Guaranteed that there are n items remaining, n-1 for 0-indexing.
2079 let ret = unsafe { &*self.slice_head.add(self.num - 1).cast::<[T; N]>() };
2085 fn nth_back(&mut self, n: usize) -> Option<&'a [T; N]> {
2090 // SAFETY: Guaranteed that there are n items remaining, n-1 for 0-indexing.
2091 let ret = unsafe { &*self.slice_head.add(self.num - (n + 1)).cast::<[T; N]>() };
2097 #[unstable(feature = "array_windows", issue = "75027")]
2098 impl<T, const N: usize> ExactSizeIterator for ArrayWindows<'_, T, N> {
2099 fn is_empty(&self) -> bool {
2104 /// An iterator over a slice in (non-overlapping) chunks (`N` elements at a
2105 /// time), starting at the beginning of the slice.
2107 /// When the slice len is not evenly divided by the chunk size, the last
2108 /// up to `N-1` elements will be omitted but can be retrieved from
2109 /// the [`remainder`] function from the iterator.
2111 /// This struct is created by the [`array_chunks`] method on [slices].
2116 /// #![feature(array_chunks)]
2118 /// let slice = ['l', 'o', 'r', 'e', 'm'];
2119 /// let iter = slice.array_chunks::<2>();
2122 /// [`array_chunks`]: slice::array_chunks
2123 /// [`remainder`]: ArrayChunks::remainder
2126 #[unstable(feature = "array_chunks", issue = "74985")]
2127 pub struct ArrayChunks<'a, T: 'a, const N: usize> {
2128 iter: Iter<'a, [T; N]>,
2132 impl<'a, T, const N: usize> ArrayChunks<'a, T, N> {
2134 pub(super) fn new(slice: &'a [T]) -> Self {
2135 let (array_slice, rem) = slice.as_chunks();
2136 Self { iter: array_slice.iter(), rem }
2139 /// Returns the remainder of the original slice that is not going to be
2140 /// returned by the iterator. The returned slice has at most `N-1`
2142 #[unstable(feature = "array_chunks", issue = "74985")]
2143 pub fn remainder(&self) -> &'a [T] {
2148 // FIXME(#26925) Remove in favor of `#[derive(Clone)]`
2149 #[unstable(feature = "array_chunks", issue = "74985")]
2150 impl<T, const N: usize> Clone for ArrayChunks<'_, T, N> {
2151 fn clone(&self) -> Self {
2152 ArrayChunks { iter: self.iter.clone(), rem: self.rem }
2156 #[unstable(feature = "array_chunks", issue = "74985")]
2157 impl<'a, T, const N: usize> Iterator for ArrayChunks<'a, T, N> {
2158 type Item = &'a [T; N];
2161 fn next(&mut self) -> Option<&'a [T; N]> {
2166 fn size_hint(&self) -> (usize, Option<usize>) {
2167 self.iter.size_hint()
2171 fn count(self) -> usize {
2176 fn nth(&mut self, n: usize) -> Option<Self::Item> {
2181 fn last(self) -> Option<Self::Item> {
2186 unsafe fn __iterator_get_unchecked(&mut self, i: usize) -> &'a [T; N] {
2187 // SAFETY: The safety guarantees of `__iterator_get_unchecked` are
2188 // transferred to the caller.
2189 unsafe { self.iter.__iterator_get_unchecked(i) }
2193 #[unstable(feature = "array_chunks", issue = "74985")]
2194 impl<'a, T, const N: usize> DoubleEndedIterator for ArrayChunks<'a, T, N> {
2196 fn next_back(&mut self) -> Option<&'a [T; N]> {
2197 self.iter.next_back()
2201 fn nth_back(&mut self, n: usize) -> Option<Self::Item> {
2202 self.iter.nth_back(n)
2206 #[unstable(feature = "array_chunks", issue = "74985")]
2207 impl<T, const N: usize> ExactSizeIterator for ArrayChunks<'_, T, N> {
2208 fn is_empty(&self) -> bool {
2209 self.iter.is_empty()
2213 #[unstable(feature = "trusted_len", issue = "37572")]
2214 unsafe impl<T, const N: usize> TrustedLen for ArrayChunks<'_, T, N> {}
2216 #[unstable(feature = "array_chunks", issue = "74985")]
2217 impl<T, const N: usize> FusedIterator for ArrayChunks<'_, T, N> {}
2220 #[unstable(feature = "array_chunks", issue = "74985")]
2221 unsafe impl<'a, T, const N: usize> TrustedRandomAccess for ArrayChunks<'a, T, N> {}
2224 #[unstable(feature = "array_chunks", issue = "74985")]
2225 unsafe impl<'a, T, const N: usize> TrustedRandomAccessNoCoerce for ArrayChunks<'a, T, N> {
2226 const MAY_HAVE_SIDE_EFFECT: bool = false;
2229 /// An iterator over a slice in (non-overlapping) mutable chunks (`N` elements
2230 /// at a time), starting at the beginning of the slice.
2232 /// When the slice len is not evenly divided by the chunk size, the last
2233 /// up to `N-1` elements will be omitted but can be retrieved from
2234 /// the [`into_remainder`] function from the iterator.
2236 /// This struct is created by the [`array_chunks_mut`] method on [slices].
2241 /// #![feature(array_chunks)]
2243 /// let mut slice = ['l', 'o', 'r', 'e', 'm'];
2244 /// let iter = slice.array_chunks_mut::<2>();
2247 /// [`array_chunks_mut`]: slice::array_chunks_mut
2248 /// [`into_remainder`]: ../../std/slice/struct.ArrayChunksMut.html#method.into_remainder
2251 #[unstable(feature = "array_chunks", issue = "74985")]
2252 pub struct ArrayChunksMut<'a, T: 'a, const N: usize> {
2253 iter: IterMut<'a, [T; N]>,
2257 impl<'a, T, const N: usize> ArrayChunksMut<'a, T, N> {
2259 pub(super) fn new(slice: &'a mut [T]) -> Self {
2260 let (array_slice, rem) = slice.as_chunks_mut();
2261 Self { iter: array_slice.iter_mut(), rem }
2264 /// Returns the remainder of the original slice that is not going to be
2265 /// returned by the iterator. The returned slice has at most `N-1`
2267 #[unstable(feature = "array_chunks", issue = "74985")]
2268 pub fn into_remainder(self) -> &'a mut [T] {
2273 #[unstable(feature = "array_chunks", issue = "74985")]
2274 impl<'a, T, const N: usize> Iterator for ArrayChunksMut<'a, T, N> {
2275 type Item = &'a mut [T; N];
2278 fn next(&mut self) -> Option<&'a mut [T; N]> {
2283 fn size_hint(&self) -> (usize, Option<usize>) {
2284 self.iter.size_hint()
2288 fn count(self) -> usize {
2293 fn nth(&mut self, n: usize) -> Option<Self::Item> {
2298 fn last(self) -> Option<Self::Item> {
2303 unsafe fn __iterator_get_unchecked(&mut self, i: usize) -> &'a mut [T; N] {
2304 // SAFETY: The safety guarantees of `__iterator_get_unchecked` are transferred to
2306 unsafe { self.iter.__iterator_get_unchecked(i) }
2310 #[unstable(feature = "array_chunks", issue = "74985")]
2311 impl<'a, T, const N: usize> DoubleEndedIterator for ArrayChunksMut<'a, T, N> {
2313 fn next_back(&mut self) -> Option<&'a mut [T; N]> {
2314 self.iter.next_back()
2318 fn nth_back(&mut self, n: usize) -> Option<Self::Item> {
2319 self.iter.nth_back(n)
2323 #[unstable(feature = "array_chunks", issue = "74985")]
2324 impl<T, const N: usize> ExactSizeIterator for ArrayChunksMut<'_, T, N> {
2325 fn is_empty(&self) -> bool {
2326 self.iter.is_empty()
2330 #[unstable(feature = "trusted_len", issue = "37572")]
2331 unsafe impl<T, const N: usize> TrustedLen for ArrayChunksMut<'_, T, N> {}
2333 #[unstable(feature = "array_chunks", issue = "74985")]
2334 impl<T, const N: usize> FusedIterator for ArrayChunksMut<'_, T, N> {}
2337 #[unstable(feature = "array_chunks", issue = "74985")]
2338 unsafe impl<'a, T, const N: usize> TrustedRandomAccess for ArrayChunksMut<'a, T, N> {}
2341 #[unstable(feature = "array_chunks", issue = "74985")]
2342 unsafe impl<'a, T, const N: usize> TrustedRandomAccessNoCoerce for ArrayChunksMut<'a, T, N> {
2343 const MAY_HAVE_SIDE_EFFECT: bool = false;
2346 /// An iterator over a slice in (non-overlapping) chunks (`chunk_size` elements at a
2347 /// time), starting at the end of the slice.
2349 /// When the slice len is not evenly divided by the chunk size, the last slice
2350 /// of the iteration will be the remainder.
2352 /// This struct is created by the [`rchunks`] method on [slices].
2357 /// let slice = ['l', 'o', 'r', 'e', 'm'];
2358 /// let iter = slice.rchunks(2);
2361 /// [`rchunks`]: slice::rchunks
2364 #[stable(feature = "rchunks", since = "1.31.0")]
2365 pub struct RChunks<'a, T: 'a> {
2370 impl<'a, T: 'a> RChunks<'a, T> {
2372 pub(super) fn new(slice: &'a [T], size: usize) -> Self {
2373 Self { v: slice, chunk_size: size }
2377 // FIXME(#26925) Remove in favor of `#[derive(Clone)]`
2378 #[stable(feature = "rchunks", since = "1.31.0")]
2379 impl<T> Clone for RChunks<'_, T> {
2380 fn clone(&self) -> Self {
2381 RChunks { v: self.v, chunk_size: self.chunk_size }
2385 #[stable(feature = "rchunks", since = "1.31.0")]
2386 impl<'a, T> Iterator for RChunks<'a, T> {
2387 type Item = &'a [T];
2390 fn next(&mut self) -> Option<&'a [T]> {
2391 if self.v.is_empty() {
2394 let chunksz = cmp::min(self.v.len(), self.chunk_size);
2395 let (fst, snd) = self.v.split_at(self.v.len() - chunksz);
2402 fn size_hint(&self) -> (usize, Option<usize>) {
2403 if self.v.is_empty() {
2406 let n = self.v.len() / self.chunk_size;
2407 let rem = self.v.len() % self.chunk_size;
2408 let n = if rem > 0 { n + 1 } else { n };
2414 fn count(self) -> usize {
2419 fn nth(&mut self, n: usize) -> Option<Self::Item> {
2420 let (end, overflow) = n.overflowing_mul(self.chunk_size);
2421 if end >= self.v.len() || overflow {
2425 // Can't underflow because of the check above
2426 let end = self.v.len() - end;
2427 let start = match end.checked_sub(self.chunk_size) {
2431 let nth = &self.v[start..end];
2432 self.v = &self.v[0..start];
2438 fn last(self) -> Option<Self::Item> {
2439 if self.v.is_empty() {
2442 let rem = self.v.len() % self.chunk_size;
2443 let end = if rem == 0 { self.chunk_size } else { rem };
2444 Some(&self.v[0..end])
2449 unsafe fn __iterator_get_unchecked(&mut self, idx: usize) -> Self::Item {
2450 let end = self.v.len() - idx * self.chunk_size;
2451 let start = match end.checked_sub(self.chunk_size) {
2453 Some(start) => start,
2455 // SAFETY: mostly identical to `Chunks::__iterator_get_unchecked`.
2456 unsafe { from_raw_parts(self.v.as_ptr().add(start), end - start) }
2460 #[stable(feature = "rchunks", since = "1.31.0")]
2461 impl<'a, T> DoubleEndedIterator for RChunks<'a, T> {
2463 fn next_back(&mut self) -> Option<&'a [T]> {
2464 if self.v.is_empty() {
2467 let remainder = self.v.len() % self.chunk_size;
2468 let chunksz = if remainder != 0 { remainder } else { self.chunk_size };
2469 let (fst, snd) = self.v.split_at(chunksz);
2476 fn nth_back(&mut self, n: usize) -> Option<Self::Item> {
2477 let len = self.len();
2482 // can't underflow because `n < len`
2483 let offset_from_end = (len - 1 - n) * self.chunk_size;
2484 let end = self.v.len() - offset_from_end;
2485 let start = end.saturating_sub(self.chunk_size);
2486 let nth_back = &self.v[start..end];
2487 self.v = &self.v[end..];
2493 #[stable(feature = "rchunks", since = "1.31.0")]
2494 impl<T> ExactSizeIterator for RChunks<'_, T> {}
2496 #[unstable(feature = "trusted_len", issue = "37572")]
2497 unsafe impl<T> TrustedLen for RChunks<'_, T> {}
2499 #[stable(feature = "rchunks", since = "1.31.0")]
2500 impl<T> FusedIterator for RChunks<'_, T> {}
2503 #[unstable(feature = "trusted_random_access", issue = "none")]
2504 unsafe impl<'a, T> TrustedRandomAccess for RChunks<'a, T> {}
2507 #[unstable(feature = "trusted_random_access", issue = "none")]
2508 unsafe impl<'a, T> TrustedRandomAccessNoCoerce for RChunks<'a, T> {
2509 const MAY_HAVE_SIDE_EFFECT: bool = false;
2512 /// An iterator over a slice in (non-overlapping) mutable chunks (`chunk_size`
2513 /// elements at a time), starting at the end of the slice.
2515 /// When the slice len is not evenly divided by the chunk size, the last slice
2516 /// of the iteration will be the remainder.
2518 /// This struct is created by the [`rchunks_mut`] method on [slices].
2523 /// let mut slice = ['l', 'o', 'r', 'e', 'm'];
2524 /// let iter = slice.rchunks_mut(2);
2527 /// [`rchunks_mut`]: slice::rchunks_mut
2530 #[stable(feature = "rchunks", since = "1.31.0")]
2531 pub struct RChunksMut<'a, T: 'a> {
2536 impl<'a, T: 'a> RChunksMut<'a, T> {
2538 pub(super) fn new(slice: &'a mut [T], size: usize) -> Self {
2539 Self { v: slice, chunk_size: size }
2543 #[stable(feature = "rchunks", since = "1.31.0")]
2544 impl<'a, T> Iterator for RChunksMut<'a, T> {
2545 type Item = &'a mut [T];
2548 fn next(&mut self) -> Option<&'a mut [T]> {
2549 if self.v.is_empty() {
2552 let sz = cmp::min(self.v.len(), self.chunk_size);
2553 let tmp = mem::replace(&mut self.v, &mut []);
2554 let tmp_len = tmp.len();
2555 let (head, tail) = tmp.split_at_mut(tmp_len - sz);
2562 fn size_hint(&self) -> (usize, Option<usize>) {
2563 if self.v.is_empty() {
2566 let n = self.v.len() / self.chunk_size;
2567 let rem = self.v.len() % self.chunk_size;
2568 let n = if rem > 0 { n + 1 } else { n };
2574 fn count(self) -> usize {
2579 fn nth(&mut self, n: usize) -> Option<&'a mut [T]> {
2580 let (end, overflow) = n.overflowing_mul(self.chunk_size);
2581 if end >= self.v.len() || overflow {
2585 // Can't underflow because of the check above
2586 let end = self.v.len() - end;
2587 let start = match end.checked_sub(self.chunk_size) {
2591 let tmp = mem::replace(&mut self.v, &mut []);
2592 let (head, tail) = tmp.split_at_mut(start);
2593 let (nth, _) = tail.split_at_mut(end - start);
2600 fn last(self) -> Option<Self::Item> {
2601 if self.v.is_empty() {
2604 let rem = self.v.len() % self.chunk_size;
2605 let end = if rem == 0 { self.chunk_size } else { rem };
2606 Some(&mut self.v[0..end])
2611 unsafe fn __iterator_get_unchecked(&mut self, idx: usize) -> Self::Item {
2612 let end = self.v.len() - idx * self.chunk_size;
2613 let start = match end.checked_sub(self.chunk_size) {
2615 Some(start) => start,
2617 // SAFETY: see comments for `RChunks::__iterator_get_unchecked` and
2618 // `ChunksMut::__iterator_get_unchecked`
2619 unsafe { from_raw_parts_mut(self.v.as_mut_ptr().add(start), end - start) }
2623 #[stable(feature = "rchunks", since = "1.31.0")]
2624 impl<'a, T> DoubleEndedIterator for RChunksMut<'a, T> {
2626 fn next_back(&mut self) -> Option<&'a mut [T]> {
2627 if self.v.is_empty() {
2630 let remainder = self.v.len() % self.chunk_size;
2631 let sz = if remainder != 0 { remainder } else { self.chunk_size };
2632 let tmp = mem::replace(&mut self.v, &mut []);
2633 let (head, tail) = tmp.split_at_mut(sz);
2640 fn nth_back(&mut self, n: usize) -> Option<Self::Item> {
2641 let len = self.len();
2646 // can't underflow because `n < len`
2647 let offset_from_end = (len - 1 - n) * self.chunk_size;
2648 let end = self.v.len() - offset_from_end;
2649 let start = end.saturating_sub(self.chunk_size);
2650 let (tmp, tail) = mem::replace(&mut self.v, &mut []).split_at_mut(end);
2651 let (_, nth_back) = tmp.split_at_mut(start);
2658 #[stable(feature = "rchunks", since = "1.31.0")]
2659 impl<T> ExactSizeIterator for RChunksMut<'_, T> {}
2661 #[unstable(feature = "trusted_len", issue = "37572")]
2662 unsafe impl<T> TrustedLen for RChunksMut<'_, T> {}
2664 #[stable(feature = "rchunks", since = "1.31.0")]
2665 impl<T> FusedIterator for RChunksMut<'_, T> {}
2668 #[unstable(feature = "trusted_random_access", issue = "none")]
2669 unsafe impl<'a, T> TrustedRandomAccess for RChunksMut<'a, T> {}
2672 #[unstable(feature = "trusted_random_access", issue = "none")]
2673 unsafe impl<'a, T> TrustedRandomAccessNoCoerce for RChunksMut<'a, T> {
2674 const MAY_HAVE_SIDE_EFFECT: bool = false;
2677 /// An iterator over a slice in (non-overlapping) chunks (`chunk_size` elements at a
2678 /// time), starting at the end of the slice.
2680 /// When the slice len is not evenly divided by the chunk size, the last
2681 /// up to `chunk_size-1` elements will be omitted but can be retrieved from
2682 /// the [`remainder`] function from the iterator.
2684 /// This struct is created by the [`rchunks_exact`] method on [slices].
2689 /// let slice = ['l', 'o', 'r', 'e', 'm'];
2690 /// let iter = slice.rchunks_exact(2);
2693 /// [`rchunks_exact`]: slice::rchunks_exact
2694 /// [`remainder`]: ChunksExact::remainder
2697 #[stable(feature = "rchunks", since = "1.31.0")]
2698 pub struct RChunksExact<'a, T: 'a> {
2704 impl<'a, T> RChunksExact<'a, T> {
2706 pub(super) fn new(slice: &'a [T], chunk_size: usize) -> Self {
2707 let rem = slice.len() % chunk_size;
2708 // SAFETY: 0 <= rem <= slice.len() by construction above
2709 let (fst, snd) = unsafe { slice.split_at_unchecked(rem) };
2710 Self { v: snd, rem: fst, chunk_size }
2713 /// Returns the remainder of the original slice that is not going to be
2714 /// returned by the iterator. The returned slice has at most `chunk_size-1`
2716 #[stable(feature = "rchunks", since = "1.31.0")]
2717 pub fn remainder(&self) -> &'a [T] {
2722 // FIXME(#26925) Remove in favor of `#[derive(Clone)]`
2723 #[stable(feature = "rchunks", since = "1.31.0")]
2724 impl<'a, T> Clone for RChunksExact<'a, T> {
2725 fn clone(&self) -> RChunksExact<'a, T> {
2726 RChunksExact { v: self.v, rem: self.rem, chunk_size: self.chunk_size }
2730 #[stable(feature = "rchunks", since = "1.31.0")]
2731 impl<'a, T> Iterator for RChunksExact<'a, T> {
2732 type Item = &'a [T];
2735 fn next(&mut self) -> Option<&'a [T]> {
2736 if self.v.len() < self.chunk_size {
2739 let (fst, snd) = self.v.split_at(self.v.len() - self.chunk_size);
2746 fn size_hint(&self) -> (usize, Option<usize>) {
2747 let n = self.v.len() / self.chunk_size;
2752 fn count(self) -> usize {
2757 fn nth(&mut self, n: usize) -> Option<Self::Item> {
2758 let (end, overflow) = n.overflowing_mul(self.chunk_size);
2759 if end >= self.v.len() || overflow {
2763 let (fst, _) = self.v.split_at(self.v.len() - end);
2770 fn last(mut self) -> Option<Self::Item> {
2775 unsafe fn __iterator_get_unchecked(&mut self, idx: usize) -> Self::Item {
2776 let end = self.v.len() - idx * self.chunk_size;
2777 let start = end - self.chunk_size;
2779 // SAFETY: mostmy identical to `Chunks::__iterator_get_unchecked`.
2780 unsafe { from_raw_parts(self.v.as_ptr().add(start), self.chunk_size) }
2784 #[stable(feature = "rchunks", since = "1.31.0")]
2785 impl<'a, T> DoubleEndedIterator for RChunksExact<'a, T> {
2787 fn next_back(&mut self) -> Option<&'a [T]> {
2788 if self.v.len() < self.chunk_size {
2791 let (fst, snd) = self.v.split_at(self.chunk_size);
2798 fn nth_back(&mut self, n: usize) -> Option<Self::Item> {
2799 let len = self.len();
2804 // now that we know that `n` corresponds to a chunk,
2805 // none of these operations can underflow/overflow
2806 let offset = (len - n) * self.chunk_size;
2807 let start = self.v.len() - offset;
2808 let end = start + self.chunk_size;
2809 let nth_back = &self.v[start..end];
2810 self.v = &self.v[end..];
2816 #[stable(feature = "rchunks", since = "1.31.0")]
2817 impl<'a, T> ExactSizeIterator for RChunksExact<'a, T> {
2818 fn is_empty(&self) -> bool {
2823 #[unstable(feature = "trusted_len", issue = "37572")]
2824 unsafe impl<T> TrustedLen for RChunksExact<'_, T> {}
2826 #[stable(feature = "rchunks", since = "1.31.0")]
2827 impl<T> FusedIterator for RChunksExact<'_, T> {}
2830 #[unstable(feature = "trusted_random_access", issue = "none")]
2831 unsafe impl<'a, T> TrustedRandomAccess for RChunksExact<'a, T> {}
2834 #[unstable(feature = "trusted_random_access", issue = "none")]
2835 unsafe impl<'a, T> TrustedRandomAccessNoCoerce for RChunksExact<'a, T> {
2836 const MAY_HAVE_SIDE_EFFECT: bool = false;
2839 /// An iterator over a slice in (non-overlapping) mutable chunks (`chunk_size`
2840 /// elements at a time), starting at the end of the slice.
2842 /// When the slice len is not evenly divided by the chunk size, the last up to
2843 /// `chunk_size-1` elements will be omitted but can be retrieved from the
2844 /// [`into_remainder`] function from the iterator.
2846 /// This struct is created by the [`rchunks_exact_mut`] method on [slices].
2851 /// let mut slice = ['l', 'o', 'r', 'e', 'm'];
2852 /// let iter = slice.rchunks_exact_mut(2);
2855 /// [`rchunks_exact_mut`]: slice::rchunks_exact_mut
2856 /// [`into_remainder`]: ChunksExactMut::into_remainder
2859 #[stable(feature = "rchunks", since = "1.31.0")]
2860 pub struct RChunksExactMut<'a, T: 'a> {
2866 impl<'a, T> RChunksExactMut<'a, T> {
2868 pub(super) fn new(slice: &'a mut [T], chunk_size: usize) -> Self {
2869 let rem = slice.len() % chunk_size;
2870 // SAFETY: 0 <= rem <= slice.len() by construction above
2871 let (fst, snd) = unsafe { slice.split_at_mut_unchecked(rem) };
2872 Self { v: snd, rem: fst, chunk_size }
2875 /// Returns the remainder of the original slice that is not going to be
2876 /// returned by the iterator. The returned slice has at most `chunk_size-1`
2878 #[stable(feature = "rchunks", since = "1.31.0")]
2879 pub fn into_remainder(self) -> &'a mut [T] {
2884 #[stable(feature = "rchunks", since = "1.31.0")]
2885 impl<'a, T> Iterator for RChunksExactMut<'a, T> {
2886 type Item = &'a mut [T];
2889 fn next(&mut self) -> Option<&'a mut [T]> {
2890 if self.v.len() < self.chunk_size {
2893 let tmp = mem::replace(&mut self.v, &mut []);
2894 let tmp_len = tmp.len();
2895 let (head, tail) = tmp.split_at_mut(tmp_len - self.chunk_size);
2902 fn size_hint(&self) -> (usize, Option<usize>) {
2903 let n = self.v.len() / self.chunk_size;
2908 fn count(self) -> usize {
2913 fn nth(&mut self, n: usize) -> Option<&'a mut [T]> {
2914 let (end, overflow) = n.overflowing_mul(self.chunk_size);
2915 if end >= self.v.len() || overflow {
2919 let tmp = mem::replace(&mut self.v, &mut []);
2920 let tmp_len = tmp.len();
2921 let (fst, _) = tmp.split_at_mut(tmp_len - end);
2928 fn last(mut self) -> Option<Self::Item> {
2933 unsafe fn __iterator_get_unchecked(&mut self, idx: usize) -> Self::Item {
2934 let end = self.v.len() - idx * self.chunk_size;
2935 let start = end - self.chunk_size;
2936 // SAFETY: see comments for `RChunksMut::__iterator_get_unchecked`.
2937 unsafe { from_raw_parts_mut(self.v.as_mut_ptr().add(start), self.chunk_size) }
2941 #[stable(feature = "rchunks", since = "1.31.0")]
2942 impl<'a, T> DoubleEndedIterator for RChunksExactMut<'a, T> {
2944 fn next_back(&mut self) -> Option<&'a mut [T]> {
2945 if self.v.len() < self.chunk_size {
2948 let tmp = mem::replace(&mut self.v, &mut []);
2949 let (head, tail) = tmp.split_at_mut(self.chunk_size);
2956 fn nth_back(&mut self, n: usize) -> Option<Self::Item> {
2957 let len = self.len();
2962 // now that we know that `n` corresponds to a chunk,
2963 // none of these operations can underflow/overflow
2964 let offset = (len - n) * self.chunk_size;
2965 let start = self.v.len() - offset;
2966 let end = start + self.chunk_size;
2967 let (tmp, tail) = mem::replace(&mut self.v, &mut []).split_at_mut(end);
2968 let (_, nth_back) = tmp.split_at_mut(start);
2975 #[stable(feature = "rchunks", since = "1.31.0")]
2976 impl<T> ExactSizeIterator for RChunksExactMut<'_, T> {
2977 fn is_empty(&self) -> bool {
2982 #[unstable(feature = "trusted_len", issue = "37572")]
2983 unsafe impl<T> TrustedLen for RChunksExactMut<'_, T> {}
2985 #[stable(feature = "rchunks", since = "1.31.0")]
2986 impl<T> FusedIterator for RChunksExactMut<'_, T> {}
2989 #[unstable(feature = "trusted_random_access", issue = "none")]
2990 unsafe impl<'a, T> TrustedRandomAccess for RChunksExactMut<'a, T> {}
2993 #[unstable(feature = "trusted_random_access", issue = "none")]
2994 unsafe impl<'a, T> TrustedRandomAccessNoCoerce for RChunksExactMut<'a, T> {
2995 const MAY_HAVE_SIDE_EFFECT: bool = false;
2999 #[unstable(feature = "trusted_random_access", issue = "none")]
3000 unsafe impl<'a, T> TrustedRandomAccess for Iter<'a, T> {}
3003 #[unstable(feature = "trusted_random_access", issue = "none")]
3004 unsafe impl<'a, T> TrustedRandomAccessNoCoerce for Iter<'a, T> {
3005 const MAY_HAVE_SIDE_EFFECT: bool = false;
3009 #[unstable(feature = "trusted_random_access", issue = "none")]
3010 unsafe impl<'a, T> TrustedRandomAccess for IterMut<'a, T> {}
3013 #[unstable(feature = "trusted_random_access", issue = "none")]
3014 unsafe impl<'a, T> TrustedRandomAccessNoCoerce for IterMut<'a, T> {
3015 const MAY_HAVE_SIDE_EFFECT: bool = false;
3018 /// An iterator over slice in (non-overlapping) chunks separated by a predicate.
3020 /// This struct is created by the [`group_by`] method on [slices].
3022 /// [`group_by`]: slice::group_by
3024 #[unstable(feature = "slice_group_by", issue = "80552")]
3025 pub struct GroupBy<'a, T: 'a, P> {
3030 #[unstable(feature = "slice_group_by", issue = "80552")]
3031 impl<'a, T: 'a, P> GroupBy<'a, T, P> {
3032 pub(super) fn new(slice: &'a [T], predicate: P) -> Self {
3033 GroupBy { slice, predicate }
3037 #[unstable(feature = "slice_group_by", issue = "80552")]
3038 impl<'a, T: 'a, P> Iterator for GroupBy<'a, T, P>
3040 P: FnMut(&T, &T) -> bool,
3042 type Item = &'a [T];
3045 fn next(&mut self) -> Option<Self::Item> {
3046 if self.slice.is_empty() {
3050 let mut iter = self.slice.windows(2);
3051 while let Some([l, r]) = iter.next() {
3052 if (self.predicate)(l, r) { len += 1 } else { break }
3054 let (head, tail) = self.slice.split_at(len);
3061 fn size_hint(&self) -> (usize, Option<usize>) {
3062 if self.slice.is_empty() { (0, Some(0)) } else { (1, Some(self.slice.len())) }
3066 fn last(mut self) -> Option<Self::Item> {
3071 #[unstable(feature = "slice_group_by", issue = "80552")]
3072 impl<'a, T: 'a, P> DoubleEndedIterator for GroupBy<'a, T, P>
3074 P: FnMut(&T, &T) -> bool,
3077 fn next_back(&mut self) -> Option<Self::Item> {
3078 if self.slice.is_empty() {
3082 let mut iter = self.slice.windows(2);
3083 while let Some([l, r]) = iter.next_back() {
3084 if (self.predicate)(l, r) { len += 1 } else { break }
3086 let (head, tail) = self.slice.split_at(self.slice.len() - len);
3093 #[unstable(feature = "slice_group_by", issue = "80552")]
3094 impl<'a, T: 'a, P> FusedIterator for GroupBy<'a, T, P> where P: FnMut(&T, &T) -> bool {}
3096 #[unstable(feature = "slice_group_by", issue = "80552")]
3097 impl<'a, T: 'a + fmt::Debug, P> fmt::Debug for GroupBy<'a, T, P> {
3098 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
3099 f.debug_struct("GroupBy").field("slice", &self.slice).finish()
3103 /// An iterator over slice in (non-overlapping) mutable chunks separated
3106 /// This struct is created by the [`group_by_mut`] method on [slices].
3108 /// [`group_by_mut`]: slice::group_by_mut
3110 #[unstable(feature = "slice_group_by", issue = "80552")]
3111 pub struct GroupByMut<'a, T: 'a, P> {
3116 #[unstable(feature = "slice_group_by", issue = "80552")]
3117 impl<'a, T: 'a, P> GroupByMut<'a, T, P> {
3118 pub(super) fn new(slice: &'a mut [T], predicate: P) -> Self {
3119 GroupByMut { slice, predicate }
3123 #[unstable(feature = "slice_group_by", issue = "80552")]
3124 impl<'a, T: 'a, P> Iterator for GroupByMut<'a, T, P>
3126 P: FnMut(&T, &T) -> bool,
3128 type Item = &'a mut [T];
3131 fn next(&mut self) -> Option<Self::Item> {
3132 if self.slice.is_empty() {
3136 let mut iter = self.slice.windows(2);
3137 while let Some([l, r]) = iter.next() {
3138 if (self.predicate)(l, r) { len += 1 } else { break }
3140 let slice = mem::take(&mut self.slice);
3141 let (head, tail) = slice.split_at_mut(len);
3148 fn size_hint(&self) -> (usize, Option<usize>) {
3149 if self.slice.is_empty() { (0, Some(0)) } else { (1, Some(self.slice.len())) }
3153 fn last(mut self) -> Option<Self::Item> {
3158 #[unstable(feature = "slice_group_by", issue = "80552")]
3159 impl<'a, T: 'a, P> DoubleEndedIterator for GroupByMut<'a, T, P>
3161 P: FnMut(&T, &T) -> bool,
3164 fn next_back(&mut self) -> Option<Self::Item> {
3165 if self.slice.is_empty() {
3169 let mut iter = self.slice.windows(2);
3170 while let Some([l, r]) = iter.next_back() {
3171 if (self.predicate)(l, r) { len += 1 } else { break }
3173 let slice = mem::take(&mut self.slice);
3174 let (head, tail) = slice.split_at_mut(slice.len() - len);
3181 #[unstable(feature = "slice_group_by", issue = "80552")]
3182 impl<'a, T: 'a, P> FusedIterator for GroupByMut<'a, T, P> where P: FnMut(&T, &T) -> bool {}
3184 #[unstable(feature = "slice_group_by", issue = "80552")]
3185 impl<'a, T: 'a + fmt::Debug, P> fmt::Debug for GroupByMut<'a, T, P> {
3186 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
3187 f.debug_struct("GroupByMut").field("slice", &self.slice).finish()