1 // ignore-tidy-filelength
2 //! Definitions of a bunch of iterators for `[T]`.
4 #[macro_use] // import iterator! and forward_iterator!
8 use crate::cmp::Ordering;
10 use crate::intrinsics::{assume, exact_div, unchecked_sub};
11 use crate::iter::{FusedIterator, TrustedLen, TrustedRandomAccess};
12 use crate::marker::{PhantomData, Send, Sized, Sync};
14 use crate::num::NonZeroUsize;
15 use crate::ptr::NonNull;
17 use super::{from_raw_parts, from_raw_parts_mut};
19 #[stable(feature = "rust1", since = "1.0.0")]
20 impl<'a, T> IntoIterator for &'a [T] {
22 type IntoIter = Iter<'a, T>;
24 fn into_iter(self) -> Iter<'a, T> {
29 #[stable(feature = "rust1", since = "1.0.0")]
30 impl<'a, T> IntoIterator for &'a mut [T] {
31 type Item = &'a mut T;
32 type IntoIter = IterMut<'a, T>;
34 fn into_iter(self) -> IterMut<'a, T> {
39 // Macro helper functions
41 fn size_from_ptr<T>(_: *const T) -> usize {
45 /// Immutable slice iterator
47 /// This struct is created by the [`iter`] method on [slices].
54 /// // First, we declare a type which has `iter` method to get the `Iter` struct (`&[usize]` here):
55 /// let slice = &[1, 2, 3];
57 /// // Then, we iterate over it:
58 /// for element in slice.iter() {
59 /// println!("{}", element);
63 /// [`iter`]: slice::iter
65 #[stable(feature = "rust1", since = "1.0.0")]
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());
128 #[stable(feature = "iter_to_slice", since = "1.4.0")]
129 pub fn as_slice(&self) -> &'a [T] {
134 iterator! {struct Iter -> *const T, &'a T, const, {/* no mut */}, {
135 fn is_sorted_by<F>(self, mut compare: F) -> bool
138 F: FnMut(&Self::Item, &Self::Item) -> Option<Ordering>,
140 self.as_slice().windows(2).all(|w| {
141 compare(&&w[0], &&w[1]).map(|o| o != Ordering::Greater).unwrap_or(false)
146 #[stable(feature = "rust1", since = "1.0.0")]
147 impl<T> Clone for Iter<'_, T> {
148 fn clone(&self) -> Self {
149 Iter { ptr: self.ptr, end: self.end, _marker: self._marker }
153 #[stable(feature = "slice_iter_as_ref", since = "1.13.0")]
154 impl<T> AsRef<[T]> for Iter<'_, T> {
155 fn as_ref(&self) -> &[T] {
160 /// Mutable slice iterator.
162 /// This struct is created by the [`iter_mut`] method on [slices].
169 /// // First, we declare a type which has `iter_mut` method to get the `IterMut`
170 /// // struct (`&[usize]` here):
171 /// let mut slice = &mut [1, 2, 3];
173 /// // Then, we iterate over it and increment each element value:
174 /// for element in slice.iter_mut() {
178 /// // We now have "[2, 3, 4]":
179 /// println!("{:?}", slice);
182 /// [`iter_mut`]: slice::iter_mut
184 #[stable(feature = "rust1", since = "1.0.0")]
185 pub struct IterMut<'a, T: 'a> {
187 end: *mut T, // If T is a ZST, this is actually ptr+len. This encoding is picked so that
188 // ptr == end is a quick test for the Iterator being empty, that works
189 // for both ZST and non-ZST.
190 _marker: PhantomData<&'a mut T>,
193 #[stable(feature = "core_impl_debug", since = "1.9.0")]
194 impl<T: fmt::Debug> fmt::Debug for IterMut<'_, T> {
195 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
196 f.debug_tuple("IterMut").field(&self.make_slice()).finish()
200 #[stable(feature = "rust1", since = "1.0.0")]
201 unsafe impl<T: Sync> Sync for IterMut<'_, T> {}
202 #[stable(feature = "rust1", since = "1.0.0")]
203 unsafe impl<T: Send> Send for IterMut<'_, T> {}
205 impl<'a, T> IterMut<'a, T> {
207 pub(super) fn new(slice: &'a mut [T]) -> Self {
208 let ptr = slice.as_mut_ptr();
209 // SAFETY: There are several things here:
211 // `ptr` has been obtained by `slice.as_ptr()` where `slice` is a valid
212 // reference thus it is non-NUL and safe to use and pass to
213 // `NonNull::new_unchecked` .
215 // Adding `slice.len()` to the starting pointer gives a pointer
216 // at the end of `slice`. `end` will never be dereferenced, only checked
217 // for direct pointer equality with `ptr` to check if the iterator is
220 // In the case of a ZST, the end pointer is just the start pointer plus
221 // the length, to also allows for the fast `ptr == end` check.
223 // See the `next_unchecked!` and `is_empty!` macros as well as the
224 // `post_inc_start` method for more informations.
226 assume(!ptr.is_null());
228 let end = if mem::size_of::<T>() == 0 {
229 (ptr as *mut u8).wrapping_add(slice.len()) as *mut T
234 Self { ptr: NonNull::new_unchecked(ptr), end, _marker: PhantomData }
238 /// Views the underlying data as a subslice of the original data.
240 /// To avoid creating `&mut` references that alias, this is forced
241 /// to consume the iterator.
248 /// // First, we declare a type which has `iter_mut` method to get the `IterMut`
249 /// // struct (`&[usize]` here):
250 /// let mut slice = &mut [1, 2, 3];
253 /// // Then, we get the iterator:
254 /// let mut iter = slice.iter_mut();
255 /// // We move to next element:
257 /// // So if we print what `into_slice` method returns here, we have "[2, 3]":
258 /// println!("{:?}", iter.into_slice());
261 /// // Now let's modify a value of the slice:
263 /// // First we get back the iterator:
264 /// let mut iter = slice.iter_mut();
265 /// // We change the value of the first element of the slice returned by the `next` method:
266 /// *iter.next().unwrap() += 1;
268 /// // Now slice is "[2, 2, 3]":
269 /// println!("{:?}", slice);
271 #[stable(feature = "iter_to_slice", since = "1.4.0")]
272 pub fn into_slice(self) -> &'a mut [T] {
273 // SAFETY: the iterator was created from a mutable slice with pointer
274 // `self.ptr` and length `len!(self)`. This guarantees that all the prerequisites
275 // for `from_raw_parts_mut` are fulfilled.
276 unsafe { from_raw_parts_mut(self.ptr.as_ptr(), len!(self)) }
279 /// Views the underlying data as a subslice of the original data.
281 /// To avoid creating `&mut [T]` references that alias, the returned slice
282 /// borrows its lifetime from the iterator the method is applied on.
289 /// # #![feature(slice_iter_mut_as_slice)]
290 /// let mut slice: &mut [usize] = &mut [1, 2, 3];
292 /// // First, we get the iterator:
293 /// let mut iter = slice.iter_mut();
294 /// // So if we check what the `as_slice` method returns here, we have "[1, 2, 3]":
295 /// assert_eq!(iter.as_slice(), &[1, 2, 3]);
297 /// // Next, we move to the second element of the slice:
299 /// // Now `as_slice` returns "[2, 3]":
300 /// assert_eq!(iter.as_slice(), &[2, 3]);
302 #[unstable(feature = "slice_iter_mut_as_slice", reason = "recently added", issue = "58957")]
303 pub fn as_slice(&self) -> &[T] {
308 iterator! {struct IterMut -> *mut T, &'a mut T, mut, {mut}, {}}
310 /// An internal abstraction over the splitting iterators, so that
311 /// splitn, splitn_mut etc can be implemented once.
313 pub(super) trait SplitIter: DoubleEndedIterator {
314 /// Marks the underlying iterator as complete, extracting the remaining
315 /// portion of the slice.
316 fn finish(&mut self) -> Option<Self::Item>;
319 /// An iterator over subslices separated by elements that match a predicate
322 /// This struct is created by the [`split`] method on [slices].
327 /// let slice = [10, 40, 33, 20];
328 /// let mut iter = slice.split(|num| num % 3 == 0);
331 /// [`split`]: slice::split
333 #[stable(feature = "rust1", since = "1.0.0")]
334 pub struct Split<'a, T: 'a, P>
336 P: FnMut(&T) -> bool,
343 impl<'a, T: 'a, P: FnMut(&T) -> bool> Split<'a, T, P> {
345 pub(super) fn new(slice: &'a [T], pred: P) -> Self {
346 Self { v: slice, pred, finished: false }
350 #[stable(feature = "core_impl_debug", since = "1.9.0")]
351 impl<T: fmt::Debug, P> fmt::Debug for Split<'_, T, P>
353 P: FnMut(&T) -> bool,
355 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
356 f.debug_struct("Split").field("v", &self.v).field("finished", &self.finished).finish()
360 // FIXME(#26925) Remove in favor of `#[derive(Clone)]`
361 #[stable(feature = "rust1", since = "1.0.0")]
362 impl<T, P> Clone for Split<'_, T, P>
364 P: Clone + FnMut(&T) -> bool,
366 fn clone(&self) -> Self {
367 Split { v: self.v, pred: self.pred.clone(), finished: self.finished }
371 #[stable(feature = "rust1", since = "1.0.0")]
372 impl<'a, T, P> Iterator for Split<'a, T, P>
374 P: FnMut(&T) -> bool,
379 fn next(&mut self) -> Option<&'a [T]> {
384 match self.v.iter().position(|x| (self.pred)(x)) {
385 None => self.finish(),
387 let ret = Some(&self.v[..idx]);
388 self.v = &self.v[idx + 1..];
395 fn size_hint(&self) -> (usize, Option<usize>) {
396 if self.finished { (0, Some(0)) } else { (1, Some(self.v.len() + 1)) }
400 #[stable(feature = "rust1", since = "1.0.0")]
401 impl<'a, T, P> DoubleEndedIterator for Split<'a, T, P>
403 P: FnMut(&T) -> bool,
406 fn next_back(&mut self) -> Option<&'a [T]> {
411 match self.v.iter().rposition(|x| (self.pred)(x)) {
412 None => self.finish(),
414 let ret = Some(&self.v[idx + 1..]);
415 self.v = &self.v[..idx];
422 impl<'a, T, P> SplitIter for Split<'a, T, P>
424 P: FnMut(&T) -> bool,
427 fn finish(&mut self) -> Option<&'a [T]> {
431 self.finished = true;
437 #[stable(feature = "fused", since = "1.26.0")]
438 impl<T, P> FusedIterator for Split<'_, T, P> where P: FnMut(&T) -> bool {}
440 /// An iterator over subslices separated by elements that match a predicate
441 /// function. Unlike `Split`, it contains the matched part as a terminator
444 /// This struct is created by the [`split_inclusive`] method on [slices].
449 /// let slice = [10, 40, 33, 20];
450 /// let mut iter = slice.split_inclusive(|num| num % 3 == 0);
453 /// [`split_inclusive`]: slice::split_inclusive
455 #[stable(feature = "split_inclusive", since = "1.51.0")]
456 pub struct SplitInclusive<'a, T: 'a, P>
458 P: FnMut(&T) -> bool,
465 impl<'a, T: 'a, P: FnMut(&T) -> bool> SplitInclusive<'a, T, P> {
467 pub(super) fn new(slice: &'a [T], pred: P) -> Self {
468 Self { v: slice, pred, finished: false }
472 #[stable(feature = "split_inclusive", since = "1.51.0")]
473 impl<T: fmt::Debug, P> fmt::Debug for SplitInclusive<'_, T, P>
475 P: FnMut(&T) -> bool,
477 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
478 f.debug_struct("SplitInclusive")
480 .field("finished", &self.finished)
485 // FIXME(#26925) Remove in favor of `#[derive(Clone)]`
486 #[stable(feature = "split_inclusive", since = "1.51.0")]
487 impl<T, P> Clone for SplitInclusive<'_, T, P>
489 P: Clone + FnMut(&T) -> bool,
491 fn clone(&self) -> Self {
492 SplitInclusive { v: self.v, pred: self.pred.clone(), finished: self.finished }
496 #[stable(feature = "split_inclusive", since = "1.51.0")]
497 impl<'a, T, P> Iterator for SplitInclusive<'a, T, P>
499 P: FnMut(&T) -> bool,
504 fn next(&mut self) -> Option<&'a [T]> {
510 self.v.iter().position(|x| (self.pred)(x)).map(|idx| idx + 1).unwrap_or(self.v.len());
511 if idx == self.v.len() {
512 self.finished = true;
514 let ret = Some(&self.v[..idx]);
515 self.v = &self.v[idx..];
520 fn size_hint(&self) -> (usize, Option<usize>) {
521 if self.finished { (0, Some(0)) } else { (1, Some(self.v.len() + 1)) }
525 #[stable(feature = "split_inclusive", since = "1.51.0")]
526 impl<'a, T, P> DoubleEndedIterator for SplitInclusive<'a, T, P>
528 P: FnMut(&T) -> bool,
531 fn next_back(&mut self) -> Option<&'a [T]> {
536 // The last index of self.v is already checked and found to match
537 // by the last iteration, so we start searching a new match
538 // one index to the left.
539 let remainder = if self.v.is_empty() { &[] } else { &self.v[..(self.v.len() - 1)] };
540 let idx = remainder.iter().rposition(|x| (self.pred)(x)).map(|idx| idx + 1).unwrap_or(0);
542 self.finished = true;
544 let ret = Some(&self.v[idx..]);
545 self.v = &self.v[..idx];
550 #[stable(feature = "split_inclusive", since = "1.51.0")]
551 impl<T, P> FusedIterator for SplitInclusive<'_, T, P> where P: FnMut(&T) -> bool {}
553 /// An iterator over the mutable subslices of the vector which are separated
554 /// by elements that match `pred`.
556 /// This struct is created by the [`split_mut`] method on [slices].
561 /// let mut v = [10, 40, 30, 20, 60, 50];
562 /// let iter = v.split_mut(|num| *num % 3 == 0);
565 /// [`split_mut`]: slice::split_mut
567 #[stable(feature = "rust1", since = "1.0.0")]
568 pub struct SplitMut<'a, T: 'a, P>
570 P: FnMut(&T) -> bool,
577 impl<'a, T: 'a, P: FnMut(&T) -> bool> SplitMut<'a, T, P> {
579 pub(super) fn new(slice: &'a mut [T], pred: P) -> Self {
580 Self { v: slice, pred, finished: false }
584 #[stable(feature = "core_impl_debug", since = "1.9.0")]
585 impl<T: fmt::Debug, P> fmt::Debug for SplitMut<'_, T, P>
587 P: FnMut(&T) -> bool,
589 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
590 f.debug_struct("SplitMut").field("v", &self.v).field("finished", &self.finished).finish()
594 impl<'a, T, P> SplitIter for SplitMut<'a, T, P>
596 P: FnMut(&T) -> bool,
599 fn finish(&mut self) -> Option<&'a mut [T]> {
603 self.finished = true;
604 Some(mem::replace(&mut self.v, &mut []))
609 #[stable(feature = "rust1", since = "1.0.0")]
610 impl<'a, T, P> Iterator for SplitMut<'a, T, P>
612 P: FnMut(&T) -> bool,
614 type Item = &'a mut [T];
617 fn next(&mut self) -> Option<&'a mut [T]> {
623 // work around borrowck limitations
624 let pred = &mut self.pred;
625 self.v.iter().position(|x| (*pred)(x))
628 None => self.finish(),
630 let tmp = mem::replace(&mut self.v, &mut []);
631 let (head, tail) = tmp.split_at_mut(idx);
632 self.v = &mut tail[1..];
639 fn size_hint(&self) -> (usize, Option<usize>) {
643 // if the predicate doesn't match anything, we yield one slice
644 // if it matches every element, we yield len+1 empty slices.
645 (1, Some(self.v.len() + 1))
650 #[stable(feature = "rust1", since = "1.0.0")]
651 impl<'a, T, P> DoubleEndedIterator for SplitMut<'a, T, P>
653 P: FnMut(&T) -> bool,
656 fn next_back(&mut self) -> Option<&'a mut [T]> {
662 // work around borrowck limitations
663 let pred = &mut self.pred;
664 self.v.iter().rposition(|x| (*pred)(x))
667 None => self.finish(),
669 let tmp = mem::replace(&mut self.v, &mut []);
670 let (head, tail) = tmp.split_at_mut(idx);
678 #[stable(feature = "fused", since = "1.26.0")]
679 impl<T, P> FusedIterator for SplitMut<'_, T, P> where P: FnMut(&T) -> bool {}
681 /// An iterator over the mutable subslices of the vector which are separated
682 /// by elements that match `pred`. Unlike `SplitMut`, it contains the matched
683 /// parts in the ends of the subslices.
685 /// This struct is created by the [`split_inclusive_mut`] method on [slices].
690 /// let mut v = [10, 40, 30, 20, 60, 50];
691 /// let iter = v.split_inclusive_mut(|num| *num % 3 == 0);
694 /// [`split_inclusive_mut`]: slice::split_inclusive_mut
696 #[stable(feature = "split_inclusive", since = "1.51.0")]
697 pub struct SplitInclusiveMut<'a, T: 'a, P>
699 P: FnMut(&T) -> bool,
706 impl<'a, T: 'a, P: FnMut(&T) -> bool> SplitInclusiveMut<'a, T, P> {
708 pub(super) fn new(slice: &'a mut [T], pred: P) -> Self {
709 Self { v: slice, pred, finished: false }
713 #[stable(feature = "split_inclusive", since = "1.51.0")]
714 impl<T: fmt::Debug, P> fmt::Debug for SplitInclusiveMut<'_, T, P>
716 P: FnMut(&T) -> bool,
718 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
719 f.debug_struct("SplitInclusiveMut")
721 .field("finished", &self.finished)
726 #[stable(feature = "split_inclusive", since = "1.51.0")]
727 impl<'a, T, P> Iterator for SplitInclusiveMut<'a, T, P>
729 P: FnMut(&T) -> bool,
731 type Item = &'a mut [T];
734 fn next(&mut self) -> Option<&'a mut [T]> {
740 // work around borrowck limitations
741 let pred = &mut self.pred;
742 self.v.iter().position(|x| (*pred)(x))
744 let idx = idx_opt.map(|idx| idx + 1).unwrap_or(self.v.len());
745 if idx == self.v.len() {
746 self.finished = true;
748 let tmp = mem::replace(&mut self.v, &mut []);
749 let (head, tail) = tmp.split_at_mut(idx);
755 fn size_hint(&self) -> (usize, Option<usize>) {
759 // if the predicate doesn't match anything, we yield one slice
760 // if it matches every element, we yield len+1 empty slices.
761 (1, Some(self.v.len() + 1))
766 #[stable(feature = "split_inclusive", since = "1.51.0")]
767 impl<'a, T, P> DoubleEndedIterator for SplitInclusiveMut<'a, T, P>
769 P: FnMut(&T) -> bool,
772 fn next_back(&mut self) -> Option<&'a mut [T]> {
777 let idx_opt = if self.v.is_empty() {
780 // work around borrowck limitations
781 let pred = &mut self.pred;
783 // The last index of self.v is already checked and found to match
784 // by the last iteration, so we start searching a new match
785 // one index to the left.
786 let remainder = &self.v[..(self.v.len() - 1)];
787 remainder.iter().rposition(|x| (*pred)(x))
789 let idx = idx_opt.map(|idx| idx + 1).unwrap_or(0);
791 self.finished = true;
793 let tmp = mem::replace(&mut self.v, &mut []);
794 let (head, tail) = tmp.split_at_mut(idx);
800 #[stable(feature = "split_inclusive", since = "1.51.0")]
801 impl<T, P> FusedIterator for SplitInclusiveMut<'_, T, P> where P: FnMut(&T) -> bool {}
803 /// An iterator over subslices separated by elements that match a predicate
804 /// function, starting from the end of the slice.
806 /// This struct is created by the [`rsplit`] method on [slices].
811 /// let slice = [11, 22, 33, 0, 44, 55];
812 /// let iter = slice.rsplit(|num| *num == 0);
815 /// [`rsplit`]: slice::rsplit
817 #[stable(feature = "slice_rsplit", since = "1.27.0")]
818 #[derive(Clone)] // Is this correct, or does it incorrectly require `T: Clone`?
819 pub struct RSplit<'a, T: 'a, P>
821 P: FnMut(&T) -> bool,
823 inner: Split<'a, T, P>,
826 impl<'a, T: 'a, P: FnMut(&T) -> bool> RSplit<'a, T, P> {
828 pub(super) fn new(slice: &'a [T], pred: P) -> Self {
829 Self { inner: Split::new(slice, pred) }
833 #[stable(feature = "slice_rsplit", since = "1.27.0")]
834 impl<T: fmt::Debug, P> fmt::Debug for RSplit<'_, T, P>
836 P: FnMut(&T) -> bool,
838 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
839 f.debug_struct("RSplit")
840 .field("v", &self.inner.v)
841 .field("finished", &self.inner.finished)
846 #[stable(feature = "slice_rsplit", since = "1.27.0")]
847 impl<'a, T, P> Iterator for RSplit<'a, T, P>
849 P: FnMut(&T) -> bool,
854 fn next(&mut self) -> Option<&'a [T]> {
855 self.inner.next_back()
859 fn size_hint(&self) -> (usize, Option<usize>) {
860 self.inner.size_hint()
864 #[stable(feature = "slice_rsplit", since = "1.27.0")]
865 impl<'a, T, P> DoubleEndedIterator for RSplit<'a, T, P>
867 P: FnMut(&T) -> bool,
870 fn next_back(&mut self) -> Option<&'a [T]> {
875 #[stable(feature = "slice_rsplit", since = "1.27.0")]
876 impl<'a, T, P> SplitIter for RSplit<'a, T, P>
878 P: FnMut(&T) -> bool,
881 fn finish(&mut self) -> Option<&'a [T]> {
886 #[stable(feature = "slice_rsplit", since = "1.27.0")]
887 impl<T, P> FusedIterator for RSplit<'_, T, P> where P: FnMut(&T) -> bool {}
889 /// An iterator over the subslices of the vector which are separated
890 /// by elements that match `pred`, starting from the end of the slice.
892 /// This struct is created by the [`rsplit_mut`] method on [slices].
897 /// let mut slice = [11, 22, 33, 0, 44, 55];
898 /// let iter = slice.rsplit_mut(|num| *num == 0);
901 /// [`rsplit_mut`]: slice::rsplit_mut
903 #[stable(feature = "slice_rsplit", since = "1.27.0")]
904 pub struct RSplitMut<'a, T: 'a, P>
906 P: FnMut(&T) -> bool,
908 inner: SplitMut<'a, T, P>,
911 impl<'a, T: 'a, P: FnMut(&T) -> bool> RSplitMut<'a, T, P> {
913 pub(super) fn new(slice: &'a mut [T], pred: P) -> Self {
914 Self { inner: SplitMut::new(slice, pred) }
918 #[stable(feature = "slice_rsplit", since = "1.27.0")]
919 impl<T: fmt::Debug, P> fmt::Debug for RSplitMut<'_, T, P>
921 P: FnMut(&T) -> bool,
923 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
924 f.debug_struct("RSplitMut")
925 .field("v", &self.inner.v)
926 .field("finished", &self.inner.finished)
931 #[stable(feature = "slice_rsplit", since = "1.27.0")]
932 impl<'a, T, P> SplitIter for RSplitMut<'a, T, P>
934 P: FnMut(&T) -> bool,
937 fn finish(&mut self) -> Option<&'a mut [T]> {
942 #[stable(feature = "slice_rsplit", since = "1.27.0")]
943 impl<'a, T, P> Iterator for RSplitMut<'a, T, P>
945 P: FnMut(&T) -> bool,
947 type Item = &'a mut [T];
950 fn next(&mut self) -> Option<&'a mut [T]> {
951 self.inner.next_back()
955 fn size_hint(&self) -> (usize, Option<usize>) {
956 self.inner.size_hint()
960 #[stable(feature = "slice_rsplit", since = "1.27.0")]
961 impl<'a, T, P> DoubleEndedIterator for RSplitMut<'a, T, P>
963 P: FnMut(&T) -> bool,
966 fn next_back(&mut self) -> Option<&'a mut [T]> {
971 #[stable(feature = "slice_rsplit", since = "1.27.0")]
972 impl<T, P> FusedIterator for RSplitMut<'_, T, P> where P: FnMut(&T) -> bool {}
974 /// An private iterator over subslices separated by elements that
975 /// match a predicate function, splitting at most a fixed number of
978 struct GenericSplitN<I> {
983 impl<T, I: SplitIter<Item = T>> Iterator for GenericSplitN<I> {
987 fn next(&mut self) -> Option<T> {
1002 fn size_hint(&self) -> (usize, Option<usize>) {
1003 let (lower, upper_opt) = self.iter.size_hint();
1004 (lower, upper_opt.map(|upper| cmp::min(self.count, upper)))
1008 /// An iterator over subslices separated by elements that match a predicate
1009 /// function, limited to a given number of splits.
1011 /// This struct is created by the [`splitn`] method on [slices].
1016 /// let slice = [10, 40, 30, 20, 60, 50];
1017 /// let iter = slice.splitn(2, |num| *num % 3 == 0);
1020 /// [`splitn`]: slice::splitn
1022 #[stable(feature = "rust1", since = "1.0.0")]
1023 pub struct SplitN<'a, T: 'a, P>
1025 P: FnMut(&T) -> bool,
1027 inner: GenericSplitN<Split<'a, T, P>>,
1030 impl<'a, T: 'a, P: FnMut(&T) -> bool> SplitN<'a, T, P> {
1032 pub(super) fn new(s: Split<'a, T, P>, n: usize) -> Self {
1033 Self { inner: GenericSplitN { iter: s, count: n } }
1037 #[stable(feature = "core_impl_debug", since = "1.9.0")]
1038 impl<T: fmt::Debug, P> fmt::Debug for SplitN<'_, T, P>
1040 P: FnMut(&T) -> bool,
1042 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
1043 f.debug_struct("SplitN").field("inner", &self.inner).finish()
1047 /// An iterator over subslices separated by elements that match a
1048 /// predicate function, limited to a given number of splits, starting
1049 /// from the end of the slice.
1051 /// This struct is created by the [`rsplitn`] method on [slices].
1056 /// let slice = [10, 40, 30, 20, 60, 50];
1057 /// let iter = slice.rsplitn(2, |num| *num % 3 == 0);
1060 /// [`rsplitn`]: slice::rsplitn
1062 #[stable(feature = "rust1", since = "1.0.0")]
1063 pub struct RSplitN<'a, T: 'a, P>
1065 P: FnMut(&T) -> bool,
1067 inner: GenericSplitN<RSplit<'a, T, P>>,
1070 impl<'a, T: 'a, P: FnMut(&T) -> bool> RSplitN<'a, T, P> {
1072 pub(super) fn new(s: RSplit<'a, T, P>, n: usize) -> Self {
1073 Self { inner: GenericSplitN { iter: s, count: n } }
1077 #[stable(feature = "core_impl_debug", since = "1.9.0")]
1078 impl<T: fmt::Debug, P> fmt::Debug for RSplitN<'_, T, P>
1080 P: FnMut(&T) -> bool,
1082 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
1083 f.debug_struct("RSplitN").field("inner", &self.inner).finish()
1087 /// An iterator over subslices separated by elements that match a predicate
1088 /// function, limited to a given number of splits.
1090 /// This struct is created by the [`splitn_mut`] method on [slices].
1095 /// let mut slice = [10, 40, 30, 20, 60, 50];
1096 /// let iter = slice.splitn_mut(2, |num| *num % 3 == 0);
1099 /// [`splitn_mut`]: slice::splitn_mut
1101 #[stable(feature = "rust1", since = "1.0.0")]
1102 pub struct SplitNMut<'a, T: 'a, P>
1104 P: FnMut(&T) -> bool,
1106 inner: GenericSplitN<SplitMut<'a, T, P>>,
1109 impl<'a, T: 'a, P: FnMut(&T) -> bool> SplitNMut<'a, T, P> {
1111 pub(super) fn new(s: SplitMut<'a, T, P>, n: usize) -> Self {
1112 Self { inner: GenericSplitN { iter: s, count: n } }
1116 #[stable(feature = "core_impl_debug", since = "1.9.0")]
1117 impl<T: fmt::Debug, P> fmt::Debug for SplitNMut<'_, T, P>
1119 P: FnMut(&T) -> bool,
1121 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
1122 f.debug_struct("SplitNMut").field("inner", &self.inner).finish()
1126 /// An iterator over subslices separated by elements that match a
1127 /// predicate function, limited to a given number of splits, starting
1128 /// from the end of the slice.
1130 /// This struct is created by the [`rsplitn_mut`] method on [slices].
1135 /// let mut slice = [10, 40, 30, 20, 60, 50];
1136 /// let iter = slice.rsplitn_mut(2, |num| *num % 3 == 0);
1139 /// [`rsplitn_mut`]: slice::rsplitn_mut
1141 #[stable(feature = "rust1", since = "1.0.0")]
1142 pub struct RSplitNMut<'a, T: 'a, P>
1144 P: FnMut(&T) -> bool,
1146 inner: GenericSplitN<RSplitMut<'a, T, P>>,
1149 impl<'a, T: 'a, P: FnMut(&T) -> bool> RSplitNMut<'a, T, P> {
1151 pub(super) fn new(s: RSplitMut<'a, T, P>, n: usize) -> Self {
1152 Self { inner: GenericSplitN { iter: s, count: n } }
1156 #[stable(feature = "core_impl_debug", since = "1.9.0")]
1157 impl<T: fmt::Debug, P> fmt::Debug for RSplitNMut<'_, T, P>
1159 P: FnMut(&T) -> bool,
1161 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
1162 f.debug_struct("RSplitNMut").field("inner", &self.inner).finish()
1166 forward_iterator! { SplitN: T, &'a [T] }
1167 forward_iterator! { RSplitN: T, &'a [T] }
1168 forward_iterator! { SplitNMut: T, &'a mut [T] }
1169 forward_iterator! { RSplitNMut: T, &'a mut [T] }
1171 /// An iterator over overlapping subslices of length `size`.
1173 /// This struct is created by the [`windows`] method on [slices].
1178 /// let slice = ['r', 'u', 's', 't'];
1179 /// let iter = slice.windows(2);
1182 /// [`windows`]: slice::windows
1185 #[stable(feature = "rust1", since = "1.0.0")]
1186 pub struct Windows<'a, T: 'a> {
1191 impl<'a, T: 'a> Windows<'a, T> {
1193 pub(super) fn new(slice: &'a [T], size: NonZeroUsize) -> Self {
1194 Self { v: slice, size }
1198 // FIXME(#26925) Remove in favor of `#[derive(Clone)]`
1199 #[stable(feature = "rust1", since = "1.0.0")]
1200 impl<T> Clone for Windows<'_, T> {
1201 fn clone(&self) -> Self {
1202 Windows { v: self.v, size: self.size }
1206 #[stable(feature = "rust1", since = "1.0.0")]
1207 impl<'a, T> Iterator for Windows<'a, T> {
1208 type Item = &'a [T];
1211 fn next(&mut self) -> Option<&'a [T]> {
1212 if self.size.get() > self.v.len() {
1215 let ret = Some(&self.v[..self.size.get()]);
1216 self.v = &self.v[1..];
1222 fn size_hint(&self) -> (usize, Option<usize>) {
1223 if self.size.get() > self.v.len() {
1226 let size = self.v.len() - self.size.get() + 1;
1232 fn count(self) -> usize {
1237 fn nth(&mut self, n: usize) -> Option<Self::Item> {
1238 let (end, overflow) = self.size.get().overflowing_add(n);
1239 if end > self.v.len() || overflow {
1243 let nth = &self.v[n..end];
1244 self.v = &self.v[n + 1..];
1250 fn last(self) -> Option<Self::Item> {
1251 if self.size.get() > self.v.len() {
1254 let start = self.v.len() - self.size.get();
1255 Some(&self.v[start..])
1260 unsafe fn __iterator_get_unchecked(&mut self, idx: usize) -> Self::Item {
1261 // SAFETY: since the caller guarantees that `i` is in bounds,
1262 // which means that `i` cannot overflow an `isize`, and the
1263 // slice created by `from_raw_parts` is a subslice of `self.v`
1264 // thus is guaranteed to be valid for the lifetime `'a` of `self.v`.
1265 unsafe { from_raw_parts(self.v.as_ptr().add(idx), self.size.get()) }
1269 #[stable(feature = "rust1", since = "1.0.0")]
1270 impl<'a, T> DoubleEndedIterator for Windows<'a, T> {
1272 fn next_back(&mut self) -> Option<&'a [T]> {
1273 if self.size.get() > self.v.len() {
1276 let ret = Some(&self.v[self.v.len() - self.size.get()..]);
1277 self.v = &self.v[..self.v.len() - 1];
1283 fn nth_back(&mut self, n: usize) -> Option<Self::Item> {
1284 let (end, overflow) = self.v.len().overflowing_sub(n);
1285 if end < self.size.get() || overflow {
1289 let ret = &self.v[end - self.size.get()..end];
1290 self.v = &self.v[..end - 1];
1296 #[stable(feature = "rust1", since = "1.0.0")]
1297 impl<T> ExactSizeIterator for Windows<'_, T> {}
1299 #[unstable(feature = "trusted_len", issue = "37572")]
1300 unsafe impl<T> TrustedLen for Windows<'_, T> {}
1302 #[stable(feature = "fused", since = "1.26.0")]
1303 impl<T> FusedIterator for Windows<'_, T> {}
1306 #[unstable(feature = "trusted_random_access", issue = "none")]
1307 unsafe impl<'a, T> TrustedRandomAccess for Windows<'a, T> {
1308 const MAY_HAVE_SIDE_EFFECT: bool = false;
1311 /// An iterator over a slice in (non-overlapping) chunks (`chunk_size` elements at a
1312 /// time), starting at the beginning of the slice.
1314 /// When the slice len is not evenly divided by the chunk size, the last slice
1315 /// of the iteration will be the remainder.
1317 /// This struct is created by the [`chunks`] method on [slices].
1322 /// let slice = ['l', 'o', 'r', 'e', 'm'];
1323 /// let iter = slice.chunks(2);
1326 /// [`chunks`]: slice::chunks
1329 #[stable(feature = "rust1", since = "1.0.0")]
1330 pub struct Chunks<'a, T: 'a> {
1335 impl<'a, T: 'a> Chunks<'a, T> {
1337 pub(super) fn new(slice: &'a [T], size: usize) -> Self {
1338 Self { v: slice, chunk_size: size }
1342 // FIXME(#26925) Remove in favor of `#[derive(Clone)]`
1343 #[stable(feature = "rust1", since = "1.0.0")]
1344 impl<T> Clone for Chunks<'_, T> {
1345 fn clone(&self) -> Self {
1346 Chunks { v: self.v, chunk_size: self.chunk_size }
1350 #[stable(feature = "rust1", since = "1.0.0")]
1351 impl<'a, T> Iterator for Chunks<'a, T> {
1352 type Item = &'a [T];
1355 fn next(&mut self) -> Option<&'a [T]> {
1356 if self.v.is_empty() {
1359 let chunksz = cmp::min(self.v.len(), self.chunk_size);
1360 let (fst, snd) = self.v.split_at(chunksz);
1367 fn size_hint(&self) -> (usize, Option<usize>) {
1368 if self.v.is_empty() {
1371 let n = self.v.len() / self.chunk_size;
1372 let rem = self.v.len() % self.chunk_size;
1373 let n = if rem > 0 { n + 1 } else { n };
1379 fn count(self) -> usize {
1384 fn nth(&mut self, n: usize) -> Option<Self::Item> {
1385 let (start, overflow) = n.overflowing_mul(self.chunk_size);
1386 if start >= self.v.len() || overflow {
1390 let end = match start.checked_add(self.chunk_size) {
1391 Some(sum) => cmp::min(self.v.len(), sum),
1392 None => self.v.len(),
1394 let nth = &self.v[start..end];
1395 self.v = &self.v[end..];
1401 fn last(self) -> Option<Self::Item> {
1402 if self.v.is_empty() {
1405 let start = (self.v.len() - 1) / self.chunk_size * self.chunk_size;
1406 Some(&self.v[start..])
1411 unsafe fn __iterator_get_unchecked(&mut self, idx: usize) -> Self::Item {
1412 let start = idx * self.chunk_size;
1413 let end = match start.checked_add(self.chunk_size) {
1414 None => self.v.len(),
1415 Some(end) => cmp::min(end, self.v.len()),
1417 // SAFETY: the caller guarantees that `i` is in bounds,
1418 // which means that `start` must be in bounds of the
1419 // underlying `self.v` slice, and we made sure that `end`
1420 // is also in bounds of `self.v`. Thus, `start` cannot overflow
1421 // an `isize`, and the slice constructed by `from_raw_parts`
1422 // is a subslice of `self.v` which is guaranteed to be valid
1423 // for the lifetime `'a` of `self.v`.
1424 unsafe { from_raw_parts(self.v.as_ptr().add(start), end - start) }
1428 #[stable(feature = "rust1", since = "1.0.0")]
1429 impl<'a, T> DoubleEndedIterator for Chunks<'a, T> {
1431 fn next_back(&mut self) -> Option<&'a [T]> {
1432 if self.v.is_empty() {
1435 let remainder = self.v.len() % self.chunk_size;
1436 let chunksz = if remainder != 0 { remainder } else { self.chunk_size };
1437 let (fst, snd) = self.v.split_at(self.v.len() - chunksz);
1444 fn nth_back(&mut self, n: usize) -> Option<Self::Item> {
1445 let len = self.len();
1450 let start = (len - 1 - n) * self.chunk_size;
1451 let end = match start.checked_add(self.chunk_size) {
1452 Some(res) => cmp::min(res, self.v.len()),
1453 None => self.v.len(),
1455 let nth_back = &self.v[start..end];
1456 self.v = &self.v[..start];
1462 #[stable(feature = "rust1", since = "1.0.0")]
1463 impl<T> ExactSizeIterator for Chunks<'_, T> {}
1465 #[unstable(feature = "trusted_len", issue = "37572")]
1466 unsafe impl<T> TrustedLen for Chunks<'_, T> {}
1468 #[stable(feature = "fused", since = "1.26.0")]
1469 impl<T> FusedIterator for Chunks<'_, T> {}
1472 #[unstable(feature = "trusted_random_access", issue = "none")]
1473 unsafe impl<'a, T> TrustedRandomAccess for Chunks<'a, T> {
1474 const MAY_HAVE_SIDE_EFFECT: bool = false;
1477 /// An iterator over a slice in (non-overlapping) mutable chunks (`chunk_size`
1478 /// elements at a time), starting at the beginning of the slice.
1480 /// When the slice len is not evenly divided by the chunk size, the last slice
1481 /// of the iteration will be the remainder.
1483 /// This struct is created by the [`chunks_mut`] method on [slices].
1488 /// let mut slice = ['l', 'o', 'r', 'e', 'm'];
1489 /// let iter = slice.chunks_mut(2);
1492 /// [`chunks_mut`]: slice::chunks_mut
1495 #[stable(feature = "rust1", since = "1.0.0")]
1496 pub struct ChunksMut<'a, T: 'a> {
1501 impl<'a, T: 'a> ChunksMut<'a, T> {
1503 pub(super) fn new(slice: &'a mut [T], size: usize) -> Self {
1504 Self { v: slice, chunk_size: size }
1508 #[stable(feature = "rust1", since = "1.0.0")]
1509 impl<'a, T> Iterator for ChunksMut<'a, T> {
1510 type Item = &'a mut [T];
1513 fn next(&mut self) -> Option<&'a mut [T]> {
1514 if self.v.is_empty() {
1517 let sz = cmp::min(self.v.len(), self.chunk_size);
1518 let tmp = mem::replace(&mut self.v, &mut []);
1519 let (head, tail) = tmp.split_at_mut(sz);
1526 fn size_hint(&self) -> (usize, Option<usize>) {
1527 if self.v.is_empty() {
1530 let n = self.v.len() / self.chunk_size;
1531 let rem = self.v.len() % self.chunk_size;
1532 let n = if rem > 0 { n + 1 } else { n };
1538 fn count(self) -> usize {
1543 fn nth(&mut self, n: usize) -> Option<&'a mut [T]> {
1544 let (start, overflow) = n.overflowing_mul(self.chunk_size);
1545 if start >= self.v.len() || overflow {
1549 let end = match start.checked_add(self.chunk_size) {
1550 Some(sum) => cmp::min(self.v.len(), sum),
1551 None => self.v.len(),
1553 let tmp = mem::replace(&mut self.v, &mut []);
1554 let (head, tail) = tmp.split_at_mut(end);
1555 let (_, nth) = head.split_at_mut(start);
1562 fn last(self) -> Option<Self::Item> {
1563 if self.v.is_empty() {
1566 let start = (self.v.len() - 1) / self.chunk_size * self.chunk_size;
1567 Some(&mut self.v[start..])
1572 unsafe fn __iterator_get_unchecked(&mut self, idx: usize) -> Self::Item {
1573 let start = idx * self.chunk_size;
1574 let end = match start.checked_add(self.chunk_size) {
1575 None => self.v.len(),
1576 Some(end) => cmp::min(end, self.v.len()),
1578 // SAFETY: see comments for `Chunks::__iterator_get_unchecked`.
1580 // Also note that the caller also guarantees that we're never called
1581 // with the same index again, and that no other methods that will
1582 // access this subslice are called, so it is valid for the returned
1583 // slice to be mutable.
1584 unsafe { from_raw_parts_mut(self.v.as_mut_ptr().add(start), end - start) }
1588 #[stable(feature = "rust1", since = "1.0.0")]
1589 impl<'a, T> DoubleEndedIterator for ChunksMut<'a, T> {
1591 fn next_back(&mut self) -> Option<&'a mut [T]> {
1592 if self.v.is_empty() {
1595 let remainder = self.v.len() % self.chunk_size;
1596 let sz = if remainder != 0 { remainder } else { self.chunk_size };
1597 let tmp = mem::replace(&mut self.v, &mut []);
1598 let tmp_len = tmp.len();
1599 let (head, tail) = tmp.split_at_mut(tmp_len - sz);
1606 fn nth_back(&mut self, n: usize) -> Option<Self::Item> {
1607 let len = self.len();
1612 let start = (len - 1 - n) * self.chunk_size;
1613 let end = match start.checked_add(self.chunk_size) {
1614 Some(res) => cmp::min(res, self.v.len()),
1615 None => self.v.len(),
1617 let (temp, _tail) = mem::replace(&mut self.v, &mut []).split_at_mut(end);
1618 let (head, nth_back) = temp.split_at_mut(start);
1625 #[stable(feature = "rust1", since = "1.0.0")]
1626 impl<T> ExactSizeIterator for ChunksMut<'_, T> {}
1628 #[unstable(feature = "trusted_len", issue = "37572")]
1629 unsafe impl<T> TrustedLen for ChunksMut<'_, T> {}
1631 #[stable(feature = "fused", since = "1.26.0")]
1632 impl<T> FusedIterator for ChunksMut<'_, T> {}
1635 #[unstable(feature = "trusted_random_access", issue = "none")]
1636 unsafe impl<'a, T> TrustedRandomAccess for ChunksMut<'a, T> {
1637 const MAY_HAVE_SIDE_EFFECT: bool = false;
1640 /// An iterator over a slice in (non-overlapping) chunks (`chunk_size` elements at a
1641 /// time), starting at the beginning of the slice.
1643 /// When the slice len is not evenly divided by the chunk size, the last
1644 /// up to `chunk_size-1` elements will be omitted but can be retrieved from
1645 /// the [`remainder`] function from the iterator.
1647 /// This struct is created by the [`chunks_exact`] method on [slices].
1652 /// let slice = ['l', 'o', 'r', 'e', 'm'];
1653 /// let iter = slice.chunks_exact(2);
1656 /// [`chunks_exact`]: slice::chunks_exact
1657 /// [`remainder`]: ChunksExact::remainder
1660 #[stable(feature = "chunks_exact", since = "1.31.0")]
1661 pub struct ChunksExact<'a, T: 'a> {
1667 impl<'a, T> ChunksExact<'a, T> {
1669 pub(super) fn new(slice: &'a [T], chunk_size: usize) -> Self {
1670 let rem = slice.len() % chunk_size;
1671 let fst_len = slice.len() - rem;
1672 // SAFETY: 0 <= fst_len <= slice.len() by construction above
1673 let (fst, snd) = unsafe { slice.split_at_unchecked(fst_len) };
1674 Self { v: fst, rem: snd, chunk_size }
1677 /// Returns the remainder of the original slice that is not going to be
1678 /// returned by the iterator. The returned slice has at most `chunk_size-1`
1680 #[stable(feature = "chunks_exact", since = "1.31.0")]
1681 pub fn remainder(&self) -> &'a [T] {
1686 // FIXME(#26925) Remove in favor of `#[derive(Clone)]`
1687 #[stable(feature = "chunks_exact", since = "1.31.0")]
1688 impl<T> Clone for ChunksExact<'_, T> {
1689 fn clone(&self) -> Self {
1690 ChunksExact { v: self.v, rem: self.rem, chunk_size: self.chunk_size }
1694 #[stable(feature = "chunks_exact", since = "1.31.0")]
1695 impl<'a, T> Iterator for ChunksExact<'a, T> {
1696 type Item = &'a [T];
1699 fn next(&mut self) -> Option<&'a [T]> {
1700 if self.v.len() < self.chunk_size {
1703 let (fst, snd) = self.v.split_at(self.chunk_size);
1710 fn size_hint(&self) -> (usize, Option<usize>) {
1711 let n = self.v.len() / self.chunk_size;
1716 fn count(self) -> usize {
1721 fn nth(&mut self, n: usize) -> Option<Self::Item> {
1722 let (start, overflow) = n.overflowing_mul(self.chunk_size);
1723 if start >= self.v.len() || overflow {
1727 let (_, snd) = self.v.split_at(start);
1734 fn last(mut self) -> Option<Self::Item> {
1739 unsafe fn __iterator_get_unchecked(&mut self, idx: usize) -> Self::Item {
1740 let start = idx * self.chunk_size;
1741 // SAFETY: mostly identical to `Chunks::__iterator_get_unchecked`.
1742 unsafe { from_raw_parts(self.v.as_ptr().add(start), self.chunk_size) }
1746 #[stable(feature = "chunks_exact", since = "1.31.0")]
1747 impl<'a, T> DoubleEndedIterator for ChunksExact<'a, T> {
1749 fn next_back(&mut self) -> Option<&'a [T]> {
1750 if self.v.len() < self.chunk_size {
1753 let (fst, snd) = self.v.split_at(self.v.len() - self.chunk_size);
1760 fn nth_back(&mut self, n: usize) -> Option<Self::Item> {
1761 let len = self.len();
1766 let start = (len - 1 - n) * self.chunk_size;
1767 let end = start + self.chunk_size;
1768 let nth_back = &self.v[start..end];
1769 self.v = &self.v[..start];
1775 #[stable(feature = "chunks_exact", since = "1.31.0")]
1776 impl<T> ExactSizeIterator for ChunksExact<'_, T> {
1777 fn is_empty(&self) -> bool {
1782 #[unstable(feature = "trusted_len", issue = "37572")]
1783 unsafe impl<T> TrustedLen for ChunksExact<'_, T> {}
1785 #[stable(feature = "chunks_exact", since = "1.31.0")]
1786 impl<T> FusedIterator for ChunksExact<'_, T> {}
1789 #[unstable(feature = "trusted_random_access", issue = "none")]
1790 unsafe impl<'a, T> TrustedRandomAccess for ChunksExact<'a, T> {
1791 const MAY_HAVE_SIDE_EFFECT: bool = false;
1794 /// An iterator over a slice in (non-overlapping) mutable chunks (`chunk_size`
1795 /// elements at a time), starting at the beginning of the slice.
1797 /// When the slice len is not evenly divided by the chunk size, the last up to
1798 /// `chunk_size-1` elements will be omitted but can be retrieved from the
1799 /// [`into_remainder`] function from the iterator.
1801 /// This struct is created by the [`chunks_exact_mut`] method on [slices].
1806 /// let mut slice = ['l', 'o', 'r', 'e', 'm'];
1807 /// let iter = slice.chunks_exact_mut(2);
1810 /// [`chunks_exact_mut`]: slice::chunks_exact_mut
1811 /// [`into_remainder`]: ChunksExactMut::into_remainder
1814 #[stable(feature = "chunks_exact", since = "1.31.0")]
1815 pub struct ChunksExactMut<'a, T: 'a> {
1821 impl<'a, T> ChunksExactMut<'a, T> {
1823 pub(super) fn new(slice: &'a mut [T], chunk_size: usize) -> Self {
1824 let rem = slice.len() % chunk_size;
1825 let fst_len = slice.len() - rem;
1826 // SAFETY: 0 <= fst_len <= slice.len() by construction above
1827 let (fst, snd) = unsafe { slice.split_at_mut_unchecked(fst_len) };
1828 Self { v: fst, rem: snd, chunk_size }
1831 /// Returns the remainder of the original slice that is not going to be
1832 /// returned by the iterator. The returned slice has at most `chunk_size-1`
1834 #[stable(feature = "chunks_exact", since = "1.31.0")]
1835 pub fn into_remainder(self) -> &'a mut [T] {
1840 #[stable(feature = "chunks_exact", since = "1.31.0")]
1841 impl<'a, T> Iterator for ChunksExactMut<'a, T> {
1842 type Item = &'a mut [T];
1845 fn next(&mut self) -> Option<&'a mut [T]> {
1846 if self.v.len() < self.chunk_size {
1849 let tmp = mem::replace(&mut self.v, &mut []);
1850 let (head, tail) = tmp.split_at_mut(self.chunk_size);
1857 fn size_hint(&self) -> (usize, Option<usize>) {
1858 let n = self.v.len() / self.chunk_size;
1863 fn count(self) -> usize {
1868 fn nth(&mut self, n: usize) -> Option<&'a mut [T]> {
1869 let (start, overflow) = n.overflowing_mul(self.chunk_size);
1870 if start >= self.v.len() || overflow {
1874 let tmp = mem::replace(&mut self.v, &mut []);
1875 let (_, snd) = tmp.split_at_mut(start);
1882 fn last(mut self) -> Option<Self::Item> {
1887 unsafe fn __iterator_get_unchecked(&mut self, idx: usize) -> Self::Item {
1888 let start = idx * self.chunk_size;
1889 // SAFETY: see comments for `ChunksMut::__iterator_get_unchecked`.
1890 unsafe { from_raw_parts_mut(self.v.as_mut_ptr().add(start), self.chunk_size) }
1894 #[stable(feature = "chunks_exact", since = "1.31.0")]
1895 impl<'a, T> DoubleEndedIterator for ChunksExactMut<'a, T> {
1897 fn next_back(&mut self) -> Option<&'a mut [T]> {
1898 if self.v.len() < self.chunk_size {
1901 let tmp = mem::replace(&mut self.v, &mut []);
1902 let tmp_len = tmp.len();
1903 let (head, tail) = tmp.split_at_mut(tmp_len - self.chunk_size);
1910 fn nth_back(&mut self, n: usize) -> Option<Self::Item> {
1911 let len = self.len();
1916 let start = (len - 1 - n) * self.chunk_size;
1917 let end = start + self.chunk_size;
1918 let (temp, _tail) = mem::replace(&mut self.v, &mut []).split_at_mut(end);
1919 let (head, nth_back) = temp.split_at_mut(start);
1926 #[stable(feature = "chunks_exact", since = "1.31.0")]
1927 impl<T> ExactSizeIterator for ChunksExactMut<'_, T> {
1928 fn is_empty(&self) -> bool {
1933 #[unstable(feature = "trusted_len", issue = "37572")]
1934 unsafe impl<T> TrustedLen for ChunksExactMut<'_, T> {}
1936 #[stable(feature = "chunks_exact", since = "1.31.0")]
1937 impl<T> FusedIterator for ChunksExactMut<'_, T> {}
1940 #[unstable(feature = "trusted_random_access", issue = "none")]
1941 unsafe impl<'a, T> TrustedRandomAccess for ChunksExactMut<'a, T> {
1942 const MAY_HAVE_SIDE_EFFECT: bool = false;
1945 /// A windowed iterator over a slice in overlapping chunks (`N` elements at a
1946 /// time), starting at the beginning of the slice
1948 /// This struct is created by the [`array_windows`] method on [slices].
1953 /// #![feature(array_windows)]
1955 /// let slice = [0, 1, 2, 3];
1956 /// let iter = slice.array_windows::<2>();
1959 /// [`array_windows`]: slice::array_windows
1961 #[derive(Debug, Clone, Copy)]
1962 #[unstable(feature = "array_windows", issue = "75027")]
1963 pub struct ArrayWindows<'a, T: 'a, const N: usize> {
1964 slice_head: *const T,
1966 marker: PhantomData<&'a [T; N]>,
1969 impl<'a, T: 'a, const N: usize> ArrayWindows<'a, T, N> {
1971 pub(super) fn new(slice: &'a [T]) -> Self {
1972 let num_windows = slice.len().saturating_sub(N - 1);
1973 Self { slice_head: slice.as_ptr(), num: num_windows, marker: PhantomData }
1977 #[unstable(feature = "array_windows", issue = "75027")]
1978 impl<'a, T, const N: usize> Iterator for ArrayWindows<'a, T, N> {
1979 type Item = &'a [T; N];
1982 fn next(&mut self) -> Option<Self::Item> {
1987 // This is safe because it's indexing into a slice guaranteed to be length > N.
1988 let ret = unsafe { &*self.slice_head.cast::<[T; N]>() };
1989 // SAFETY: Guaranteed that there are at least 1 item remaining otherwise
1990 // earlier branch would've been hit
1991 self.slice_head = unsafe { self.slice_head.add(1) };
1998 fn size_hint(&self) -> (usize, Option<usize>) {
1999 (self.num, Some(self.num))
2003 fn count(self) -> usize {
2008 fn nth(&mut self, n: usize) -> Option<Self::Item> {
2014 // This is safe because it's indexing into a slice guaranteed to be length > N.
2015 let ret = unsafe { &*self.slice_head.add(n).cast::<[T; N]>() };
2016 // SAFETY: Guaranteed that there are at least n items remaining
2017 self.slice_head = unsafe { self.slice_head.add(n + 1) };
2024 fn last(mut self) -> Option<Self::Item> {
2025 self.nth(self.num.checked_sub(1)?)
2029 #[unstable(feature = "array_windows", issue = "75027")]
2030 impl<'a, T, const N: usize> DoubleEndedIterator for ArrayWindows<'a, T, N> {
2032 fn next_back(&mut self) -> Option<&'a [T; N]> {
2036 // SAFETY: Guaranteed that there are n items remaining, n-1 for 0-indexing.
2037 let ret = unsafe { &*self.slice_head.add(self.num - 1).cast::<[T; N]>() };
2043 fn nth_back(&mut self, n: usize) -> Option<&'a [T; N]> {
2048 // SAFETY: Guaranteed that there are n items remaining, n-1 for 0-indexing.
2049 let ret = unsafe { &*self.slice_head.add(self.num - (n + 1)).cast::<[T; N]>() };
2055 #[unstable(feature = "array_windows", issue = "75027")]
2056 impl<T, const N: usize> ExactSizeIterator for ArrayWindows<'_, T, N> {
2057 fn is_empty(&self) -> bool {
2062 /// An iterator over a slice in (non-overlapping) chunks (`N` elements at a
2063 /// time), starting at the beginning of the slice.
2065 /// When the slice len is not evenly divided by the chunk size, the last
2066 /// up to `N-1` elements will be omitted but can be retrieved from
2067 /// the [`remainder`] function from the iterator.
2069 /// This struct is created by the [`array_chunks`] method on [slices].
2074 /// #![feature(array_chunks)]
2076 /// let slice = ['l', 'o', 'r', 'e', 'm'];
2077 /// let iter = slice.array_chunks::<2>();
2080 /// [`array_chunks`]: slice::array_chunks
2081 /// [`remainder`]: ArrayChunks::remainder
2084 #[unstable(feature = "array_chunks", issue = "74985")]
2085 pub struct ArrayChunks<'a, T: 'a, const N: usize> {
2086 iter: Iter<'a, [T; N]>,
2090 impl<'a, T, const N: usize> ArrayChunks<'a, T, N> {
2092 pub(super) fn new(slice: &'a [T]) -> Self {
2093 let (array_slice, rem) = slice.as_chunks();
2094 Self { iter: array_slice.iter(), rem }
2097 /// Returns the remainder of the original slice that is not going to be
2098 /// returned by the iterator. The returned slice has at most `N-1`
2100 #[unstable(feature = "array_chunks", issue = "74985")]
2101 pub fn remainder(&self) -> &'a [T] {
2106 // FIXME(#26925) Remove in favor of `#[derive(Clone)]`
2107 #[unstable(feature = "array_chunks", issue = "74985")]
2108 impl<T, const N: usize> Clone for ArrayChunks<'_, T, N> {
2109 fn clone(&self) -> Self {
2110 ArrayChunks { iter: self.iter.clone(), rem: self.rem }
2114 #[unstable(feature = "array_chunks", issue = "74985")]
2115 impl<'a, T, const N: usize> Iterator for ArrayChunks<'a, T, N> {
2116 type Item = &'a [T; N];
2119 fn next(&mut self) -> Option<&'a [T; N]> {
2124 fn size_hint(&self) -> (usize, Option<usize>) {
2125 self.iter.size_hint()
2129 fn count(self) -> usize {
2134 fn nth(&mut self, n: usize) -> Option<Self::Item> {
2139 fn last(self) -> Option<Self::Item> {
2143 unsafe fn __iterator_get_unchecked(&mut self, i: usize) -> &'a [T; N] {
2144 // SAFETY: The safety guarantees of `__iterator_get_unchecked` are
2145 // transferred to the caller.
2146 unsafe { self.iter.__iterator_get_unchecked(i) }
2150 #[unstable(feature = "array_chunks", issue = "74985")]
2151 impl<'a, T, const N: usize> DoubleEndedIterator for ArrayChunks<'a, T, N> {
2153 fn next_back(&mut self) -> Option<&'a [T; N]> {
2154 self.iter.next_back()
2158 fn nth_back(&mut self, n: usize) -> Option<Self::Item> {
2159 self.iter.nth_back(n)
2163 #[unstable(feature = "array_chunks", issue = "74985")]
2164 impl<T, const N: usize> ExactSizeIterator for ArrayChunks<'_, T, N> {
2165 fn is_empty(&self) -> bool {
2166 self.iter.is_empty()
2170 #[unstable(feature = "trusted_len", issue = "37572")]
2171 unsafe impl<T, const N: usize> TrustedLen for ArrayChunks<'_, T, N> {}
2173 #[unstable(feature = "array_chunks", issue = "74985")]
2174 impl<T, const N: usize> FusedIterator for ArrayChunks<'_, T, N> {}
2177 #[unstable(feature = "array_chunks", issue = "74985")]
2178 unsafe impl<'a, T, const N: usize> TrustedRandomAccess for ArrayChunks<'a, T, N> {
2179 const MAY_HAVE_SIDE_EFFECT: bool = false;
2182 /// An iterator over a slice in (non-overlapping) mutable chunks (`N` elements
2183 /// at a time), starting at the beginning of the slice.
2185 /// When the slice len is not evenly divided by the chunk size, the last
2186 /// up to `N-1` elements will be omitted but can be retrieved from
2187 /// the [`into_remainder`] function from the iterator.
2189 /// This struct is created by the [`array_chunks_mut`] method on [slices].
2194 /// #![feature(array_chunks)]
2196 /// let mut slice = ['l', 'o', 'r', 'e', 'm'];
2197 /// let iter = slice.array_chunks_mut::<2>();
2200 /// [`array_chunks_mut`]: slice::array_chunks_mut
2201 /// [`into_remainder`]: ../../std/slice/struct.ArrayChunksMut.html#method.into_remainder
2204 #[unstable(feature = "array_chunks", issue = "74985")]
2205 pub struct ArrayChunksMut<'a, T: 'a, const N: usize> {
2206 iter: IterMut<'a, [T; N]>,
2210 impl<'a, T, const N: usize> ArrayChunksMut<'a, T, N> {
2212 pub(super) fn new(slice: &'a mut [T]) -> Self {
2213 let (array_slice, rem) = slice.as_chunks_mut();
2214 Self { iter: array_slice.iter_mut(), rem }
2217 /// Returns the remainder of the original slice that is not going to be
2218 /// returned by the iterator. The returned slice has at most `N-1`
2220 #[unstable(feature = "array_chunks", issue = "74985")]
2221 pub fn into_remainder(self) -> &'a mut [T] {
2226 #[unstable(feature = "array_chunks", issue = "74985")]
2227 impl<'a, T, const N: usize> Iterator for ArrayChunksMut<'a, T, N> {
2228 type Item = &'a mut [T; N];
2231 fn next(&mut self) -> Option<&'a mut [T; N]> {
2236 fn size_hint(&self) -> (usize, Option<usize>) {
2237 self.iter.size_hint()
2241 fn count(self) -> usize {
2246 fn nth(&mut self, n: usize) -> Option<Self::Item> {
2251 fn last(self) -> Option<Self::Item> {
2255 unsafe fn __iterator_get_unchecked(&mut self, i: usize) -> &'a mut [T; N] {
2256 // SAFETY: The safety guarantees of `__iterator_get_unchecked` are transferred to
2258 unsafe { self.iter.__iterator_get_unchecked(i) }
2262 #[unstable(feature = "array_chunks", issue = "74985")]
2263 impl<'a, T, const N: usize> DoubleEndedIterator for ArrayChunksMut<'a, T, N> {
2265 fn next_back(&mut self) -> Option<&'a mut [T; N]> {
2266 self.iter.next_back()
2270 fn nth_back(&mut self, n: usize) -> Option<Self::Item> {
2271 self.iter.nth_back(n)
2275 #[unstable(feature = "array_chunks", issue = "74985")]
2276 impl<T, const N: usize> ExactSizeIterator for ArrayChunksMut<'_, T, N> {
2277 fn is_empty(&self) -> bool {
2278 self.iter.is_empty()
2282 #[unstable(feature = "trusted_len", issue = "37572")]
2283 unsafe impl<T, const N: usize> TrustedLen for ArrayChunksMut<'_, T, N> {}
2285 #[unstable(feature = "array_chunks", issue = "74985")]
2286 impl<T, const N: usize> FusedIterator for ArrayChunksMut<'_, T, N> {}
2289 #[unstable(feature = "array_chunks", issue = "74985")]
2290 unsafe impl<'a, T, const N: usize> TrustedRandomAccess for ArrayChunksMut<'a, T, N> {
2291 const MAY_HAVE_SIDE_EFFECT: bool = false;
2294 /// An iterator over a slice in (non-overlapping) chunks (`chunk_size` elements at a
2295 /// time), starting at the end of the slice.
2297 /// When the slice len is not evenly divided by the chunk size, the last slice
2298 /// of the iteration will be the remainder.
2300 /// This struct is created by the [`rchunks`] method on [slices].
2305 /// let slice = ['l', 'o', 'r', 'e', 'm'];
2306 /// let iter = slice.rchunks(2);
2309 /// [`rchunks`]: slice::rchunks
2312 #[stable(feature = "rchunks", since = "1.31.0")]
2313 pub struct RChunks<'a, T: 'a> {
2318 impl<'a, T: 'a> RChunks<'a, T> {
2320 pub(super) fn new(slice: &'a [T], size: usize) -> Self {
2321 Self { v: slice, chunk_size: size }
2325 // FIXME(#26925) Remove in favor of `#[derive(Clone)]`
2326 #[stable(feature = "rchunks", since = "1.31.0")]
2327 impl<T> Clone for RChunks<'_, T> {
2328 fn clone(&self) -> Self {
2329 RChunks { v: self.v, chunk_size: self.chunk_size }
2333 #[stable(feature = "rchunks", since = "1.31.0")]
2334 impl<'a, T> Iterator for RChunks<'a, T> {
2335 type Item = &'a [T];
2338 fn next(&mut self) -> Option<&'a [T]> {
2339 if self.v.is_empty() {
2342 let chunksz = cmp::min(self.v.len(), self.chunk_size);
2343 let (fst, snd) = self.v.split_at(self.v.len() - chunksz);
2350 fn size_hint(&self) -> (usize, Option<usize>) {
2351 if self.v.is_empty() {
2354 let n = self.v.len() / self.chunk_size;
2355 let rem = self.v.len() % self.chunk_size;
2356 let n = if rem > 0 { n + 1 } else { n };
2362 fn count(self) -> usize {
2367 fn nth(&mut self, n: usize) -> Option<Self::Item> {
2368 let (end, overflow) = n.overflowing_mul(self.chunk_size);
2369 if end >= self.v.len() || overflow {
2373 // Can't underflow because of the check above
2374 let end = self.v.len() - end;
2375 let start = match end.checked_sub(self.chunk_size) {
2379 let nth = &self.v[start..end];
2380 self.v = &self.v[0..start];
2386 fn last(self) -> Option<Self::Item> {
2387 if self.v.is_empty() {
2390 let rem = self.v.len() % self.chunk_size;
2391 let end = if rem == 0 { self.chunk_size } else { rem };
2392 Some(&self.v[0..end])
2397 unsafe fn __iterator_get_unchecked(&mut self, idx: usize) -> Self::Item {
2398 let end = self.v.len() - idx * self.chunk_size;
2399 let start = match end.checked_sub(self.chunk_size) {
2401 Some(start) => start,
2403 // SAFETY: mostly identical to `Chunks::__iterator_get_unchecked`.
2404 unsafe { from_raw_parts(self.v.as_ptr().add(start), end - start) }
2408 #[stable(feature = "rchunks", since = "1.31.0")]
2409 impl<'a, T> DoubleEndedIterator for RChunks<'a, T> {
2411 fn next_back(&mut self) -> Option<&'a [T]> {
2412 if self.v.is_empty() {
2415 let remainder = self.v.len() % self.chunk_size;
2416 let chunksz = if remainder != 0 { remainder } else { self.chunk_size };
2417 let (fst, snd) = self.v.split_at(chunksz);
2424 fn nth_back(&mut self, n: usize) -> Option<Self::Item> {
2425 let len = self.len();
2430 // can't underflow because `n < len`
2431 let offset_from_end = (len - 1 - n) * self.chunk_size;
2432 let end = self.v.len() - offset_from_end;
2433 let start = end.saturating_sub(self.chunk_size);
2434 let nth_back = &self.v[start..end];
2435 self.v = &self.v[end..];
2441 #[stable(feature = "rchunks", since = "1.31.0")]
2442 impl<T> ExactSizeIterator for RChunks<'_, T> {}
2444 #[unstable(feature = "trusted_len", issue = "37572")]
2445 unsafe impl<T> TrustedLen for RChunks<'_, T> {}
2447 #[stable(feature = "rchunks", since = "1.31.0")]
2448 impl<T> FusedIterator for RChunks<'_, T> {}
2451 #[unstable(feature = "trusted_random_access", issue = "none")]
2452 unsafe impl<'a, T> TrustedRandomAccess for RChunks<'a, T> {
2453 const MAY_HAVE_SIDE_EFFECT: bool = false;
2456 /// An iterator over a slice in (non-overlapping) mutable chunks (`chunk_size`
2457 /// elements at a time), starting at the end of the slice.
2459 /// When the slice len is not evenly divided by the chunk size, the last slice
2460 /// of the iteration will be the remainder.
2462 /// This struct is created by the [`rchunks_mut`] method on [slices].
2467 /// let mut slice = ['l', 'o', 'r', 'e', 'm'];
2468 /// let iter = slice.rchunks_mut(2);
2471 /// [`rchunks_mut`]: slice::rchunks_mut
2474 #[stable(feature = "rchunks", since = "1.31.0")]
2475 pub struct RChunksMut<'a, T: 'a> {
2480 impl<'a, T: 'a> RChunksMut<'a, T> {
2482 pub(super) fn new(slice: &'a mut [T], size: usize) -> Self {
2483 Self { v: slice, chunk_size: size }
2487 #[stable(feature = "rchunks", since = "1.31.0")]
2488 impl<'a, T> Iterator for RChunksMut<'a, T> {
2489 type Item = &'a mut [T];
2492 fn next(&mut self) -> Option<&'a mut [T]> {
2493 if self.v.is_empty() {
2496 let sz = cmp::min(self.v.len(), self.chunk_size);
2497 let tmp = mem::replace(&mut self.v, &mut []);
2498 let tmp_len = tmp.len();
2499 let (head, tail) = tmp.split_at_mut(tmp_len - sz);
2506 fn size_hint(&self) -> (usize, Option<usize>) {
2507 if self.v.is_empty() {
2510 let n = self.v.len() / self.chunk_size;
2511 let rem = self.v.len() % self.chunk_size;
2512 let n = if rem > 0 { n + 1 } else { n };
2518 fn count(self) -> usize {
2523 fn nth(&mut self, n: usize) -> Option<&'a mut [T]> {
2524 let (end, overflow) = n.overflowing_mul(self.chunk_size);
2525 if end >= self.v.len() || overflow {
2529 // Can't underflow because of the check above
2530 let end = self.v.len() - end;
2531 let start = match end.checked_sub(self.chunk_size) {
2535 let tmp = mem::replace(&mut self.v, &mut []);
2536 let (head, tail) = tmp.split_at_mut(start);
2537 let (nth, _) = tail.split_at_mut(end - start);
2544 fn last(self) -> Option<Self::Item> {
2545 if self.v.is_empty() {
2548 let rem = self.v.len() % self.chunk_size;
2549 let end = if rem == 0 { self.chunk_size } else { rem };
2550 Some(&mut self.v[0..end])
2555 unsafe fn __iterator_get_unchecked(&mut self, idx: usize) -> Self::Item {
2556 let end = self.v.len() - idx * self.chunk_size;
2557 let start = match end.checked_sub(self.chunk_size) {
2559 Some(start) => start,
2561 // SAFETY: see comments for `RChunks::__iterator_get_unchecked` and
2562 // `ChunksMut::__iterator_get_unchecked`
2563 unsafe { from_raw_parts_mut(self.v.as_mut_ptr().add(start), end - start) }
2567 #[stable(feature = "rchunks", since = "1.31.0")]
2568 impl<'a, T> DoubleEndedIterator for RChunksMut<'a, T> {
2570 fn next_back(&mut self) -> Option<&'a mut [T]> {
2571 if self.v.is_empty() {
2574 let remainder = self.v.len() % self.chunk_size;
2575 let sz = if remainder != 0 { remainder } else { self.chunk_size };
2576 let tmp = mem::replace(&mut self.v, &mut []);
2577 let (head, tail) = tmp.split_at_mut(sz);
2584 fn nth_back(&mut self, n: usize) -> Option<Self::Item> {
2585 let len = self.len();
2590 // can't underflow because `n < len`
2591 let offset_from_end = (len - 1 - n) * self.chunk_size;
2592 let end = self.v.len() - offset_from_end;
2593 let start = end.saturating_sub(self.chunk_size);
2594 let (tmp, tail) = mem::replace(&mut self.v, &mut []).split_at_mut(end);
2595 let (_, nth_back) = tmp.split_at_mut(start);
2602 #[stable(feature = "rchunks", since = "1.31.0")]
2603 impl<T> ExactSizeIterator for RChunksMut<'_, T> {}
2605 #[unstable(feature = "trusted_len", issue = "37572")]
2606 unsafe impl<T> TrustedLen for RChunksMut<'_, T> {}
2608 #[stable(feature = "rchunks", since = "1.31.0")]
2609 impl<T> FusedIterator for RChunksMut<'_, T> {}
2612 #[unstable(feature = "trusted_random_access", issue = "none")]
2613 unsafe impl<'a, T> TrustedRandomAccess for RChunksMut<'a, T> {
2614 const MAY_HAVE_SIDE_EFFECT: bool = false;
2617 /// An iterator over a slice in (non-overlapping) chunks (`chunk_size` elements at a
2618 /// time), starting at the end of the slice.
2620 /// When the slice len is not evenly divided by the chunk size, the last
2621 /// up to `chunk_size-1` elements will be omitted but can be retrieved from
2622 /// the [`remainder`] function from the iterator.
2624 /// This struct is created by the [`rchunks_exact`] method on [slices].
2629 /// let slice = ['l', 'o', 'r', 'e', 'm'];
2630 /// let iter = slice.rchunks_exact(2);
2633 /// [`rchunks_exact`]: slice::rchunks_exact
2634 /// [`remainder`]: ChunksExact::remainder
2637 #[stable(feature = "rchunks", since = "1.31.0")]
2638 pub struct RChunksExact<'a, T: 'a> {
2644 impl<'a, T> RChunksExact<'a, T> {
2646 pub(super) fn new(slice: &'a [T], chunk_size: usize) -> Self {
2647 let rem = slice.len() % chunk_size;
2648 // SAFETY: 0 <= rem <= slice.len() by construction above
2649 let (fst, snd) = unsafe { slice.split_at_unchecked(rem) };
2650 Self { v: snd, rem: fst, chunk_size }
2653 /// Returns the remainder of the original slice that is not going to be
2654 /// returned by the iterator. The returned slice has at most `chunk_size-1`
2656 #[stable(feature = "rchunks", since = "1.31.0")]
2657 pub fn remainder(&self) -> &'a [T] {
2662 // FIXME(#26925) Remove in favor of `#[derive(Clone)]`
2663 #[stable(feature = "rchunks", since = "1.31.0")]
2664 impl<'a, T> Clone for RChunksExact<'a, T> {
2665 fn clone(&self) -> RChunksExact<'a, T> {
2666 RChunksExact { v: self.v, rem: self.rem, chunk_size: self.chunk_size }
2670 #[stable(feature = "rchunks", since = "1.31.0")]
2671 impl<'a, T> Iterator for RChunksExact<'a, T> {
2672 type Item = &'a [T];
2675 fn next(&mut self) -> Option<&'a [T]> {
2676 if self.v.len() < self.chunk_size {
2679 let (fst, snd) = self.v.split_at(self.v.len() - self.chunk_size);
2686 fn size_hint(&self) -> (usize, Option<usize>) {
2687 let n = self.v.len() / self.chunk_size;
2692 fn count(self) -> usize {
2697 fn nth(&mut self, n: usize) -> Option<Self::Item> {
2698 let (end, overflow) = n.overflowing_mul(self.chunk_size);
2699 if end >= self.v.len() || overflow {
2703 let (fst, _) = self.v.split_at(self.v.len() - end);
2710 fn last(mut self) -> Option<Self::Item> {
2715 unsafe fn __iterator_get_unchecked(&mut self, idx: usize) -> Self::Item {
2716 let end = self.v.len() - idx * self.chunk_size;
2717 let start = end - self.chunk_size;
2719 // SAFETY: mostmy identical to `Chunks::__iterator_get_unchecked`.
2720 unsafe { from_raw_parts(self.v.as_ptr().add(start), self.chunk_size) }
2724 #[stable(feature = "rchunks", since = "1.31.0")]
2725 impl<'a, T> DoubleEndedIterator for RChunksExact<'a, T> {
2727 fn next_back(&mut self) -> Option<&'a [T]> {
2728 if self.v.len() < self.chunk_size {
2731 let (fst, snd) = self.v.split_at(self.chunk_size);
2738 fn nth_back(&mut self, n: usize) -> Option<Self::Item> {
2739 let len = self.len();
2744 // now that we know that `n` corresponds to a chunk,
2745 // none of these operations can underflow/overflow
2746 let offset = (len - n) * self.chunk_size;
2747 let start = self.v.len() - offset;
2748 let end = start + self.chunk_size;
2749 let nth_back = &self.v[start..end];
2750 self.v = &self.v[end..];
2756 #[stable(feature = "rchunks", since = "1.31.0")]
2757 impl<'a, T> ExactSizeIterator for RChunksExact<'a, T> {
2758 fn is_empty(&self) -> bool {
2763 #[unstable(feature = "trusted_len", issue = "37572")]
2764 unsafe impl<T> TrustedLen for RChunksExact<'_, T> {}
2766 #[stable(feature = "rchunks", since = "1.31.0")]
2767 impl<T> FusedIterator for RChunksExact<'_, T> {}
2770 #[unstable(feature = "trusted_random_access", issue = "none")]
2771 unsafe impl<'a, T> TrustedRandomAccess for RChunksExact<'a, T> {
2772 const MAY_HAVE_SIDE_EFFECT: bool = false;
2775 /// An iterator over a slice in (non-overlapping) mutable chunks (`chunk_size`
2776 /// elements at a time), starting at the end of the slice.
2778 /// When the slice len is not evenly divided by the chunk size, the last up to
2779 /// `chunk_size-1` elements will be omitted but can be retrieved from the
2780 /// [`into_remainder`] function from the iterator.
2782 /// This struct is created by the [`rchunks_exact_mut`] method on [slices].
2787 /// let mut slice = ['l', 'o', 'r', 'e', 'm'];
2788 /// let iter = slice.rchunks_exact_mut(2);
2791 /// [`rchunks_exact_mut`]: slice::rchunks_exact_mut
2792 /// [`into_remainder`]: ChunksExactMut::into_remainder
2795 #[stable(feature = "rchunks", since = "1.31.0")]
2796 pub struct RChunksExactMut<'a, T: 'a> {
2802 impl<'a, T> RChunksExactMut<'a, T> {
2804 pub(super) fn new(slice: &'a mut [T], chunk_size: usize) -> Self {
2805 let rem = slice.len() % chunk_size;
2806 // SAFETY: 0 <= rem <= slice.len() by construction above
2807 let (fst, snd) = unsafe { slice.split_at_mut_unchecked(rem) };
2808 Self { v: snd, rem: fst, chunk_size }
2811 /// Returns the remainder of the original slice that is not going to be
2812 /// returned by the iterator. The returned slice has at most `chunk_size-1`
2814 #[stable(feature = "rchunks", since = "1.31.0")]
2815 pub fn into_remainder(self) -> &'a mut [T] {
2820 #[stable(feature = "rchunks", since = "1.31.0")]
2821 impl<'a, T> Iterator for RChunksExactMut<'a, T> {
2822 type Item = &'a mut [T];
2825 fn next(&mut self) -> Option<&'a mut [T]> {
2826 if self.v.len() < self.chunk_size {
2829 let tmp = mem::replace(&mut self.v, &mut []);
2830 let tmp_len = tmp.len();
2831 let (head, tail) = tmp.split_at_mut(tmp_len - self.chunk_size);
2838 fn size_hint(&self) -> (usize, Option<usize>) {
2839 let n = self.v.len() / self.chunk_size;
2844 fn count(self) -> usize {
2849 fn nth(&mut self, n: usize) -> Option<&'a mut [T]> {
2850 let (end, overflow) = n.overflowing_mul(self.chunk_size);
2851 if end >= self.v.len() || overflow {
2855 let tmp = mem::replace(&mut self.v, &mut []);
2856 let tmp_len = tmp.len();
2857 let (fst, _) = tmp.split_at_mut(tmp_len - end);
2864 fn last(mut self) -> Option<Self::Item> {
2869 unsafe fn __iterator_get_unchecked(&mut self, idx: usize) -> Self::Item {
2870 let end = self.v.len() - idx * self.chunk_size;
2871 let start = end - self.chunk_size;
2872 // SAFETY: see comments for `RChunksMut::__iterator_get_unchecked`.
2873 unsafe { from_raw_parts_mut(self.v.as_mut_ptr().add(start), self.chunk_size) }
2877 #[stable(feature = "rchunks", since = "1.31.0")]
2878 impl<'a, T> DoubleEndedIterator for RChunksExactMut<'a, T> {
2880 fn next_back(&mut self) -> Option<&'a mut [T]> {
2881 if self.v.len() < self.chunk_size {
2884 let tmp = mem::replace(&mut self.v, &mut []);
2885 let (head, tail) = tmp.split_at_mut(self.chunk_size);
2892 fn nth_back(&mut self, n: usize) -> Option<Self::Item> {
2893 let len = self.len();
2898 // now that we know that `n` corresponds to a chunk,
2899 // none of these operations can underflow/overflow
2900 let offset = (len - n) * self.chunk_size;
2901 let start = self.v.len() - offset;
2902 let end = start + self.chunk_size;
2903 let (tmp, tail) = mem::replace(&mut self.v, &mut []).split_at_mut(end);
2904 let (_, nth_back) = tmp.split_at_mut(start);
2911 #[stable(feature = "rchunks", since = "1.31.0")]
2912 impl<T> ExactSizeIterator for RChunksExactMut<'_, T> {
2913 fn is_empty(&self) -> bool {
2918 #[unstable(feature = "trusted_len", issue = "37572")]
2919 unsafe impl<T> TrustedLen for RChunksExactMut<'_, T> {}
2921 #[stable(feature = "rchunks", since = "1.31.0")]
2922 impl<T> FusedIterator for RChunksExactMut<'_, T> {}
2925 #[unstable(feature = "trusted_random_access", issue = "none")]
2926 unsafe impl<'a, T> TrustedRandomAccess for RChunksExactMut<'a, T> {
2927 const MAY_HAVE_SIDE_EFFECT: bool = false;
2931 #[unstable(feature = "trusted_random_access", issue = "none")]
2932 unsafe impl<'a, T> TrustedRandomAccess for Iter<'a, T> {
2933 const MAY_HAVE_SIDE_EFFECT: bool = false;
2937 #[unstable(feature = "trusted_random_access", issue = "none")]
2938 unsafe impl<'a, T> TrustedRandomAccess for IterMut<'a, T> {
2939 const MAY_HAVE_SIDE_EFFECT: bool = false;
2942 /// An iterator over slice in (non-overlapping) chunks separated by a predicate.
2944 /// This struct is created by the [`group_by`] method on [slices].
2946 /// [`group_by`]: slice::group_by
2948 #[unstable(feature = "slice_group_by", issue = "80552")]
2949 pub struct GroupBy<'a, T: 'a, P> {
2954 #[unstable(feature = "slice_group_by", issue = "80552")]
2955 impl<'a, T: 'a, P> GroupBy<'a, T, P> {
2956 pub(super) fn new(slice: &'a [T], predicate: P) -> Self {
2957 GroupBy { slice, predicate }
2961 #[unstable(feature = "slice_group_by", issue = "80552")]
2962 impl<'a, T: 'a, P> Iterator for GroupBy<'a, T, P>
2964 P: FnMut(&T, &T) -> bool,
2966 type Item = &'a [T];
2969 fn next(&mut self) -> Option<Self::Item> {
2970 if self.slice.is_empty() {
2974 let mut iter = self.slice.windows(2);
2975 while let Some([l, r]) = iter.next() {
2976 if (self.predicate)(l, r) { len += 1 } else { break }
2978 let (head, tail) = self.slice.split_at(len);
2985 fn size_hint(&self) -> (usize, Option<usize>) {
2986 if self.slice.is_empty() { (0, Some(0)) } else { (1, Some(self.slice.len())) }
2990 fn last(mut self) -> Option<Self::Item> {
2995 #[unstable(feature = "slice_group_by", issue = "80552")]
2996 impl<'a, T: 'a, P> DoubleEndedIterator for GroupBy<'a, T, P>
2998 P: FnMut(&T, &T) -> bool,
3001 fn next_back(&mut self) -> Option<Self::Item> {
3002 if self.slice.is_empty() {
3006 let mut iter = self.slice.windows(2);
3007 while let Some([l, r]) = iter.next_back() {
3008 if (self.predicate)(l, r) { len += 1 } else { break }
3010 let (head, tail) = self.slice.split_at(self.slice.len() - len);
3017 #[unstable(feature = "slice_group_by", issue = "80552")]
3018 impl<'a, T: 'a, P> FusedIterator for GroupBy<'a, T, P> where P: FnMut(&T, &T) -> bool {}
3020 #[unstable(feature = "slice_group_by", issue = "80552")]
3021 impl<'a, T: 'a + fmt::Debug, P> fmt::Debug for GroupBy<'a, T, P> {
3022 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
3023 f.debug_struct("GroupBy").field("slice", &self.slice).finish()
3027 /// An iterator over slice in (non-overlapping) mutable chunks separated
3030 /// This struct is created by the [`group_by_mut`] method on [slices].
3032 /// [`group_by_mut`]: slice::group_by_mut
3034 #[unstable(feature = "slice_group_by", issue = "80552")]
3035 pub struct GroupByMut<'a, T: 'a, P> {
3040 #[unstable(feature = "slice_group_by", issue = "80552")]
3041 impl<'a, T: 'a, P> GroupByMut<'a, T, P> {
3042 pub(super) fn new(slice: &'a mut [T], predicate: P) -> Self {
3043 GroupByMut { slice, predicate }
3047 #[unstable(feature = "slice_group_by", issue = "80552")]
3048 impl<'a, T: 'a, P> Iterator for GroupByMut<'a, T, P>
3050 P: FnMut(&T, &T) -> bool,
3052 type Item = &'a mut [T];
3055 fn next(&mut self) -> Option<Self::Item> {
3056 if self.slice.is_empty() {
3060 let mut iter = self.slice.windows(2);
3061 while let Some([l, r]) = iter.next() {
3062 if (self.predicate)(l, r) { len += 1 } else { break }
3064 let slice = mem::take(&mut self.slice);
3065 let (head, tail) = slice.split_at_mut(len);
3072 fn size_hint(&self) -> (usize, Option<usize>) {
3073 if self.slice.is_empty() { (0, Some(0)) } else { (1, Some(self.slice.len())) }
3077 fn last(mut self) -> Option<Self::Item> {
3082 #[unstable(feature = "slice_group_by", issue = "80552")]
3083 impl<'a, T: 'a, P> DoubleEndedIterator for GroupByMut<'a, T, P>
3085 P: FnMut(&T, &T) -> bool,
3088 fn next_back(&mut self) -> Option<Self::Item> {
3089 if self.slice.is_empty() {
3093 let mut iter = self.slice.windows(2);
3094 while let Some([l, r]) = iter.next_back() {
3095 if (self.predicate)(l, r) { len += 1 } else { break }
3097 let slice = mem::take(&mut self.slice);
3098 let (head, tail) = slice.split_at_mut(slice.len() - len);
3105 #[unstable(feature = "slice_group_by", issue = "80552")]
3106 impl<'a, T: 'a, P> FusedIterator for GroupByMut<'a, T, P> where P: FnMut(&T, &T) -> bool {}
3108 #[unstable(feature = "slice_group_by", issue = "80552")]
3109 impl<'a, T: 'a + fmt::Debug, P> fmt::Debug for GroupByMut<'a, T, P> {
3110 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
3111 f.debug_struct("GroupByMut").field("slice", &self.slice).finish()