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};
12 use crate::mem::{self, SizedTypeProperties};
13 use crate::num::NonZeroUsize;
14 use crate::ptr::NonNull;
16 use super::{from_raw_parts, from_raw_parts_mut};
18 #[stable(feature = "rust1", since = "1.0.0")]
19 impl<'a, T> IntoIterator for &'a [T] {
21 type IntoIter = Iter<'a, T>;
23 fn into_iter(self) -> Iter<'a, T> {
28 #[stable(feature = "rust1", since = "1.0.0")]
29 impl<'a, T> IntoIterator for &'a mut [T] {
30 type Item = &'a mut T;
31 type IntoIter = IterMut<'a, T>;
33 fn into_iter(self) -> IterMut<'a, T> {
38 // Macro helper functions
40 fn size_from_ptr<T>(_: *const T) -> usize {
44 /// Immutable slice iterator
46 /// This struct is created by the [`iter`] method on [slices].
53 /// // First, we declare a type which has `iter` method to get the `Iter` struct (`&[usize]` here):
54 /// let slice = &[1, 2, 3];
56 /// // Then, we iterate over it:
57 /// for element in slice.iter() {
58 /// println!("{element}");
62 /// [`iter`]: slice::iter
64 #[stable(feature = "rust1", since = "1.0.0")]
65 #[must_use = "iterators are lazy and do nothing unless consumed"]
66 pub struct Iter<'a, T: 'a> {
68 end: *const T, // If T is a ZST, this is actually ptr+len. This encoding is picked so that
69 // ptr == end is a quick test for the Iterator being empty, that works
70 // for both ZST and non-ZST.
71 _marker: PhantomData<&'a T>,
74 #[stable(feature = "core_impl_debug", since = "1.9.0")]
75 impl<T: fmt::Debug> fmt::Debug for Iter<'_, T> {
76 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
77 f.debug_tuple("Iter").field(&self.as_slice()).finish()
81 #[stable(feature = "rust1", since = "1.0.0")]
82 unsafe impl<T: Sync> Sync for Iter<'_, T> {}
83 #[stable(feature = "rust1", since = "1.0.0")]
84 unsafe impl<T: Sync> Send for Iter<'_, T> {}
86 impl<'a, T> Iter<'a, T> {
88 pub(super) fn new(slice: &'a [T]) -> Self {
89 let ptr = slice.as_ptr();
90 // SAFETY: Similar to `IterMut::new`.
92 assume(!ptr.is_null());
95 if T::IS_ZST { ptr.wrapping_byte_add(slice.len()) } else { ptr.add(slice.len()) };
97 Self { ptr: NonNull::new_unchecked(ptr as *mut T), end, _marker: PhantomData }
101 /// Views the underlying data as a subslice of the original data.
103 /// This has the same lifetime as the original slice, and so the
104 /// iterator can continue to be used while this exists.
111 /// // First, we declare a type which has the `iter` method to get the `Iter`
112 /// // struct (`&[usize]` here):
113 /// let slice = &[1, 2, 3];
115 /// // Then, we get the iterator:
116 /// let mut iter = slice.iter();
117 /// // So if we print what `as_slice` method returns here, we have "[1, 2, 3]":
118 /// println!("{:?}", iter.as_slice());
120 /// // Next, we move to the second element of the slice:
122 /// // Now `as_slice` returns "[2, 3]":
123 /// println!("{:?}", iter.as_slice());
126 #[stable(feature = "iter_to_slice", since = "1.4.0")]
127 pub fn as_slice(&self) -> &'a [T] {
132 iterator! {struct Iter -> *const T, &'a T, const, {/* no mut */}, {
133 fn is_sorted_by<F>(self, mut compare: F) -> bool
136 F: FnMut(&Self::Item, &Self::Item) -> Option<Ordering>,
138 self.as_slice().windows(2).all(|w| {
139 compare(&&w[0], &&w[1]).map(|o| o != Ordering::Greater).unwrap_or(false)
144 #[stable(feature = "rust1", since = "1.0.0")]
145 impl<T> Clone for Iter<'_, T> {
146 fn clone(&self) -> Self {
147 Iter { ptr: self.ptr, end: self.end, _marker: self._marker }
151 #[stable(feature = "slice_iter_as_ref", since = "1.13.0")]
152 impl<T> AsRef<[T]> for Iter<'_, T> {
153 fn as_ref(&self) -> &[T] {
158 /// Mutable slice iterator.
160 /// This struct is created by the [`iter_mut`] method on [slices].
167 /// // First, we declare a type which has `iter_mut` method to get the `IterMut`
168 /// // struct (`&[usize]` here):
169 /// let mut slice = &mut [1, 2, 3];
171 /// // Then, we iterate over it and increment each element value:
172 /// for element in slice.iter_mut() {
176 /// // We now have "[2, 3, 4]":
177 /// println!("{slice:?}");
180 /// [`iter_mut`]: slice::iter_mut
182 #[stable(feature = "rust1", since = "1.0.0")]
183 #[must_use = "iterators are lazy and do nothing unless consumed"]
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 information.
225 assume(!ptr.is_null());
228 if T::IS_ZST { ptr.wrapping_byte_add(slice.len()) } else { ptr.add(slice.len()) };
230 Self { ptr: NonNull::new_unchecked(ptr), end, _marker: PhantomData }
234 /// Views the underlying data as a subslice of the original data.
236 /// To avoid creating `&mut` references that alias, this is forced
237 /// to consume the iterator.
244 /// // First, we declare a type which has `iter_mut` method to get the `IterMut`
245 /// // struct (`&[usize]` here):
246 /// let mut slice = &mut [1, 2, 3];
249 /// // Then, we get the iterator:
250 /// let mut iter = slice.iter_mut();
251 /// // We move to next element:
253 /// // So if we print what `into_slice` method returns here, we have "[2, 3]":
254 /// println!("{:?}", iter.into_slice());
257 /// // Now let's modify a value of the slice:
259 /// // First we get back the iterator:
260 /// let mut iter = slice.iter_mut();
261 /// // We change the value of the first element of the slice returned by the `next` method:
262 /// *iter.next().unwrap() += 1;
264 /// // Now slice is "[2, 2, 3]":
265 /// println!("{slice:?}");
267 #[must_use = "`self` will be dropped if the result is not used"]
268 #[stable(feature = "iter_to_slice", since = "1.4.0")]
269 pub fn into_slice(self) -> &'a mut [T] {
270 // SAFETY: the iterator was created from a mutable slice with pointer
271 // `self.ptr` and length `len!(self)`. This guarantees that all the prerequisites
272 // for `from_raw_parts_mut` are fulfilled.
273 unsafe { from_raw_parts_mut(self.ptr.as_ptr(), len!(self)) }
276 /// Views the underlying data as a subslice of the original data.
278 /// To avoid creating `&mut [T]` references that alias, the returned slice
279 /// borrows its lifetime from the iterator the method is applied on.
286 /// let mut slice: &mut [usize] = &mut [1, 2, 3];
288 /// // First, we get the iterator:
289 /// let mut iter = slice.iter_mut();
290 /// // So if we check what the `as_slice` method returns here, we have "[1, 2, 3]":
291 /// assert_eq!(iter.as_slice(), &[1, 2, 3]);
293 /// // Next, we move to the second element of the slice:
295 /// // Now `as_slice` returns "[2, 3]":
296 /// assert_eq!(iter.as_slice(), &[2, 3]);
299 #[stable(feature = "slice_iter_mut_as_slice", since = "1.53.0")]
300 pub fn as_slice(&self) -> &[T] {
304 /// Views the underlying data as a mutable subslice of the original data.
306 /// To avoid creating `&mut [T]` references that alias, the returned slice
307 /// borrows its lifetime from the iterator the method is applied on.
314 /// #![feature(slice_iter_mut_as_mut_slice)]
316 /// let mut slice: &mut [usize] = &mut [1, 2, 3];
318 /// // First, we get the iterator:
319 /// let mut iter = slice.iter_mut();
320 /// // Then, we get a mutable slice from it:
321 /// let mut_slice = iter.as_mut_slice();
322 /// // So if we check what the `as_mut_slice` method returned, we have "[1, 2, 3]":
323 /// assert_eq!(mut_slice, &mut [1, 2, 3]);
325 /// // We can use it to mutate the slice:
326 /// mut_slice[0] = 4;
327 /// mut_slice[2] = 5;
329 /// // Next, we can move to the second element of the slice, checking that
330 /// // it yields the value we just wrote:
331 /// assert_eq!(iter.next(), Some(&mut 4));
332 /// // Now `as_mut_slice` returns "[2, 5]":
333 /// assert_eq!(iter.as_mut_slice(), &mut [2, 5]);
336 // FIXME: Uncomment the `AsMut<[T]>` impl when this gets stabilized.
337 #[unstable(feature = "slice_iter_mut_as_mut_slice", issue = "93079")]
338 pub fn as_mut_slice(&mut self) -> &mut [T] {
339 // SAFETY: the iterator was created from a mutable slice with pointer
340 // `self.ptr` and length `len!(self)`. This guarantees that all the prerequisites
341 // for `from_raw_parts_mut` are fulfilled.
342 unsafe { from_raw_parts_mut(self.ptr.as_ptr(), len!(self)) }
346 #[stable(feature = "slice_iter_mut_as_slice", since = "1.53.0")]
347 impl<T> AsRef<[T]> for IterMut<'_, T> {
348 fn as_ref(&self) -> &[T] {
353 // #[stable(feature = "slice_iter_mut_as_mut_slice", since = "FIXME")]
354 // impl<T> AsMut<[T]> for IterMut<'_, T> {
355 // fn as_mut(&mut self) -> &mut [T] {
356 // self.as_mut_slice()
360 iterator! {struct IterMut -> *mut T, &'a mut T, mut, {mut}, {}}
362 /// An internal abstraction over the splitting iterators, so that
363 /// splitn, splitn_mut etc can be implemented once.
365 pub(super) trait SplitIter: DoubleEndedIterator {
366 /// Marks the underlying iterator as complete, extracting the remaining
367 /// portion of the slice.
368 fn finish(&mut self) -> Option<Self::Item>;
371 /// An iterator over subslices separated by elements that match a predicate
374 /// This struct is created by the [`split`] method on [slices].
379 /// let slice = [10, 40, 33, 20];
380 /// let mut iter = slice.split(|num| num % 3 == 0);
383 /// [`split`]: slice::split
385 #[stable(feature = "rust1", since = "1.0.0")]
386 #[must_use = "iterators are lazy and do nothing unless consumed"]
387 pub struct Split<'a, T: 'a, P>
389 P: FnMut(&T) -> bool,
391 // Used for `SplitWhitespace` and `SplitAsciiWhitespace` `as_str` methods
392 pub(crate) v: &'a [T],
394 // Used for `SplitAsciiWhitespace` `as_str` method
395 pub(crate) finished: bool,
398 impl<'a, T: 'a, P: FnMut(&T) -> bool> Split<'a, T, P> {
400 pub(super) fn new(slice: &'a [T], pred: P) -> Self {
401 Self { v: slice, pred, finished: false }
403 /// Returns a slice which contains items not yet handled by split.
407 /// #![feature(split_as_slice)]
408 /// let slice = [1,2,3,4,5];
409 /// let mut split = slice.split(|v| v % 2 == 0);
410 /// assert!(split.next().is_some());
411 /// assert_eq!(split.as_slice(), &[3,4,5]);
413 #[unstable(feature = "split_as_slice", issue = "96137")]
414 pub fn as_slice(&self) -> &'a [T] {
415 if self.finished { &[] } else { &self.v }
419 #[stable(feature = "core_impl_debug", since = "1.9.0")]
420 impl<T: fmt::Debug, P> fmt::Debug for Split<'_, T, P>
422 P: FnMut(&T) -> bool,
424 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
425 f.debug_struct("Split").field("v", &self.v).field("finished", &self.finished).finish()
429 // FIXME(#26925) Remove in favor of `#[derive(Clone)]`
430 #[stable(feature = "rust1", since = "1.0.0")]
431 impl<T, P> Clone for Split<'_, T, P>
433 P: Clone + FnMut(&T) -> bool,
435 fn clone(&self) -> Self {
436 Split { v: self.v, pred: self.pred.clone(), finished: self.finished }
440 #[stable(feature = "rust1", since = "1.0.0")]
441 impl<'a, T, P> Iterator for Split<'a, T, P>
443 P: FnMut(&T) -> bool,
448 fn next(&mut self) -> Option<&'a [T]> {
453 match self.v.iter().position(|x| (self.pred)(x)) {
454 None => self.finish(),
456 let ret = Some(&self.v[..idx]);
457 self.v = &self.v[idx + 1..];
464 fn size_hint(&self) -> (usize, Option<usize>) {
468 // If the predicate doesn't match anything, we yield one slice.
469 // If it matches every element, we yield `len() + 1` empty slices.
470 (1, Some(self.v.len() + 1))
475 #[stable(feature = "rust1", since = "1.0.0")]
476 impl<'a, T, P> DoubleEndedIterator for Split<'a, T, P>
478 P: FnMut(&T) -> bool,
481 fn next_back(&mut self) -> Option<&'a [T]> {
486 match self.v.iter().rposition(|x| (self.pred)(x)) {
487 None => self.finish(),
489 let ret = Some(&self.v[idx + 1..]);
490 self.v = &self.v[..idx];
497 impl<'a, T, P> SplitIter for Split<'a, T, P>
499 P: FnMut(&T) -> bool,
502 fn finish(&mut self) -> Option<&'a [T]> {
506 self.finished = true;
512 #[stable(feature = "fused", since = "1.26.0")]
513 impl<T, P> FusedIterator for Split<'_, T, P> where P: FnMut(&T) -> bool {}
515 /// An iterator over subslices separated by elements that match a predicate
516 /// function. Unlike `Split`, it contains the matched part as a terminator
519 /// This struct is created by the [`split_inclusive`] method on [slices].
524 /// let slice = [10, 40, 33, 20];
525 /// let mut iter = slice.split_inclusive(|num| num % 3 == 0);
528 /// [`split_inclusive`]: slice::split_inclusive
530 #[stable(feature = "split_inclusive", since = "1.51.0")]
531 #[must_use = "iterators are lazy and do nothing unless consumed"]
532 pub struct SplitInclusive<'a, T: 'a, P>
534 P: FnMut(&T) -> bool,
541 impl<'a, T: 'a, P: FnMut(&T) -> bool> SplitInclusive<'a, T, P> {
543 pub(super) fn new(slice: &'a [T], pred: P) -> Self {
544 let finished = slice.is_empty();
545 Self { v: slice, pred, finished }
549 #[stable(feature = "split_inclusive", since = "1.51.0")]
550 impl<T: fmt::Debug, P> fmt::Debug for SplitInclusive<'_, T, P>
552 P: FnMut(&T) -> bool,
554 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
555 f.debug_struct("SplitInclusive")
557 .field("finished", &self.finished)
562 // FIXME(#26925) Remove in favor of `#[derive(Clone)]`
563 #[stable(feature = "split_inclusive", since = "1.51.0")]
564 impl<T, P> Clone for SplitInclusive<'_, T, P>
566 P: Clone + FnMut(&T) -> bool,
568 fn clone(&self) -> Self {
569 SplitInclusive { v: self.v, pred: self.pred.clone(), finished: self.finished }
573 #[stable(feature = "split_inclusive", since = "1.51.0")]
574 impl<'a, T, P> Iterator for SplitInclusive<'a, T, P>
576 P: FnMut(&T) -> bool,
581 fn next(&mut self) -> Option<&'a [T]> {
587 self.v.iter().position(|x| (self.pred)(x)).map(|idx| idx + 1).unwrap_or(self.v.len());
588 if idx == self.v.len() {
589 self.finished = true;
591 let ret = Some(&self.v[..idx]);
592 self.v = &self.v[idx..];
597 fn size_hint(&self) -> (usize, Option<usize>) {
601 // If the predicate doesn't match anything, we yield one slice.
602 // If it matches every element, we yield `len()` one-element slices,
603 // or a single empty slice.
604 (1, Some(cmp::max(1, self.v.len())))
609 #[stable(feature = "split_inclusive", since = "1.51.0")]
610 impl<'a, T, P> DoubleEndedIterator for SplitInclusive<'a, T, P>
612 P: FnMut(&T) -> bool,
615 fn next_back(&mut self) -> Option<&'a [T]> {
620 // The last index of self.v is already checked and found to match
621 // by the last iteration, so we start searching a new match
622 // one index to the left.
623 let remainder = if self.v.is_empty() { &[] } else { &self.v[..(self.v.len() - 1)] };
624 let idx = remainder.iter().rposition(|x| (self.pred)(x)).map(|idx| idx + 1).unwrap_or(0);
626 self.finished = true;
628 let ret = Some(&self.v[idx..]);
629 self.v = &self.v[..idx];
634 #[stable(feature = "split_inclusive", since = "1.51.0")]
635 impl<T, P> FusedIterator for SplitInclusive<'_, T, P> where P: FnMut(&T) -> bool {}
637 /// An iterator over the mutable subslices of the vector which are separated
638 /// by elements that match `pred`.
640 /// This struct is created by the [`split_mut`] method on [slices].
645 /// let mut v = [10, 40, 30, 20, 60, 50];
646 /// let iter = v.split_mut(|num| *num % 3 == 0);
649 /// [`split_mut`]: slice::split_mut
651 #[stable(feature = "rust1", since = "1.0.0")]
652 #[must_use = "iterators are lazy and do nothing unless consumed"]
653 pub struct SplitMut<'a, T: 'a, P>
655 P: FnMut(&T) -> bool,
662 impl<'a, T: 'a, P: FnMut(&T) -> bool> SplitMut<'a, T, P> {
664 pub(super) fn new(slice: &'a mut [T], pred: P) -> Self {
665 Self { v: slice, pred, finished: false }
669 #[stable(feature = "core_impl_debug", since = "1.9.0")]
670 impl<T: fmt::Debug, P> fmt::Debug for SplitMut<'_, T, P>
672 P: FnMut(&T) -> bool,
674 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
675 f.debug_struct("SplitMut").field("v", &self.v).field("finished", &self.finished).finish()
679 impl<'a, T, P> SplitIter for SplitMut<'a, T, P>
681 P: FnMut(&T) -> bool,
684 fn finish(&mut self) -> Option<&'a mut [T]> {
688 self.finished = true;
689 Some(mem::replace(&mut self.v, &mut []))
694 #[stable(feature = "rust1", since = "1.0.0")]
695 impl<'a, T, P> Iterator for SplitMut<'a, T, P>
697 P: FnMut(&T) -> bool,
699 type Item = &'a mut [T];
702 fn next(&mut self) -> Option<&'a mut [T]> {
707 match self.v.iter().position(|x| (self.pred)(x)) {
708 None => self.finish(),
710 let tmp = mem::take(&mut self.v);
711 // idx is the index of the element we are splitting on. We want to set self to the
712 // region after idx, and return the subslice before and not including idx.
713 // So first we split after idx
714 let (head, tail) = tmp.split_at_mut(idx + 1);
716 // Then return the subslice up to but not including the found element
717 Some(&mut head[..idx])
723 fn size_hint(&self) -> (usize, Option<usize>) {
727 // If the predicate doesn't match anything, we yield one slice.
728 // If it matches every element, we yield `len() + 1` empty slices.
729 (1, Some(self.v.len() + 1))
734 #[stable(feature = "rust1", since = "1.0.0")]
735 impl<'a, T, P> DoubleEndedIterator for SplitMut<'a, T, P>
737 P: FnMut(&T) -> bool,
740 fn next_back(&mut self) -> Option<&'a mut [T]> {
746 // work around borrowck limitations
747 let pred = &mut self.pred;
748 self.v.iter().rposition(|x| (*pred)(x))
751 None => self.finish(),
753 let tmp = mem::replace(&mut self.v, &mut []);
754 let (head, tail) = tmp.split_at_mut(idx);
762 #[stable(feature = "fused", since = "1.26.0")]
763 impl<T, P> FusedIterator for SplitMut<'_, T, P> where P: FnMut(&T) -> bool {}
765 /// An iterator over the mutable subslices of the vector which are separated
766 /// by elements that match `pred`. Unlike `SplitMut`, it contains the matched
767 /// parts in the ends of the subslices.
769 /// This struct is created by the [`split_inclusive_mut`] method on [slices].
774 /// let mut v = [10, 40, 30, 20, 60, 50];
775 /// let iter = v.split_inclusive_mut(|num| *num % 3 == 0);
778 /// [`split_inclusive_mut`]: slice::split_inclusive_mut
780 #[stable(feature = "split_inclusive", since = "1.51.0")]
781 #[must_use = "iterators are lazy and do nothing unless consumed"]
782 pub struct SplitInclusiveMut<'a, T: 'a, P>
784 P: FnMut(&T) -> bool,
791 impl<'a, T: 'a, P: FnMut(&T) -> bool> SplitInclusiveMut<'a, T, P> {
793 pub(super) fn new(slice: &'a mut [T], pred: P) -> Self {
794 let finished = slice.is_empty();
795 Self { v: slice, pred, finished }
799 #[stable(feature = "split_inclusive", since = "1.51.0")]
800 impl<T: fmt::Debug, P> fmt::Debug for SplitInclusiveMut<'_, T, P>
802 P: FnMut(&T) -> bool,
804 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
805 f.debug_struct("SplitInclusiveMut")
807 .field("finished", &self.finished)
812 #[stable(feature = "split_inclusive", since = "1.51.0")]
813 impl<'a, T, P> Iterator for SplitInclusiveMut<'a, T, P>
815 P: FnMut(&T) -> bool,
817 type Item = &'a mut [T];
820 fn next(&mut self) -> Option<&'a mut [T]> {
826 // work around borrowck limitations
827 let pred = &mut self.pred;
828 self.v.iter().position(|x| (*pred)(x))
830 let idx = idx_opt.map(|idx| idx + 1).unwrap_or(self.v.len());
831 if idx == self.v.len() {
832 self.finished = true;
834 let tmp = mem::replace(&mut self.v, &mut []);
835 let (head, tail) = tmp.split_at_mut(idx);
841 fn size_hint(&self) -> (usize, Option<usize>) {
845 // If the predicate doesn't match anything, we yield one slice.
846 // If it matches every element, we yield `len()` one-element slices,
847 // or a single empty slice.
848 (1, Some(cmp::max(1, self.v.len())))
853 #[stable(feature = "split_inclusive", since = "1.51.0")]
854 impl<'a, T, P> DoubleEndedIterator for SplitInclusiveMut<'a, T, P>
856 P: FnMut(&T) -> bool,
859 fn next_back(&mut self) -> Option<&'a mut [T]> {
864 let idx_opt = if self.v.is_empty() {
867 // work around borrowck limitations
868 let pred = &mut self.pred;
870 // The last index of self.v is already checked and found to match
871 // by the last iteration, so we start searching a new match
872 // one index to the left.
873 let remainder = &self.v[..(self.v.len() - 1)];
874 remainder.iter().rposition(|x| (*pred)(x))
876 let idx = idx_opt.map(|idx| idx + 1).unwrap_or(0);
878 self.finished = true;
880 let tmp = mem::replace(&mut self.v, &mut []);
881 let (head, tail) = tmp.split_at_mut(idx);
887 #[stable(feature = "split_inclusive", since = "1.51.0")]
888 impl<T, P> FusedIterator for SplitInclusiveMut<'_, T, P> where P: FnMut(&T) -> bool {}
890 /// An iterator over subslices separated by elements that match a predicate
891 /// function, starting from the end of the slice.
893 /// This struct is created by the [`rsplit`] method on [slices].
898 /// let slice = [11, 22, 33, 0, 44, 55];
899 /// let iter = slice.rsplit(|num| *num == 0);
902 /// [`rsplit`]: slice::rsplit
904 #[stable(feature = "slice_rsplit", since = "1.27.0")]
905 #[must_use = "iterators are lazy and do nothing unless consumed"]
906 pub struct RSplit<'a, T: 'a, P>
908 P: FnMut(&T) -> bool,
910 inner: Split<'a, T, P>,
913 impl<'a, T: 'a, P: FnMut(&T) -> bool> RSplit<'a, T, P> {
915 pub(super) fn new(slice: &'a [T], pred: P) -> Self {
916 Self { inner: Split::new(slice, pred) }
920 #[stable(feature = "slice_rsplit", since = "1.27.0")]
921 impl<T: fmt::Debug, P> fmt::Debug for RSplit<'_, T, P>
923 P: FnMut(&T) -> bool,
925 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
926 f.debug_struct("RSplit")
927 .field("v", &self.inner.v)
928 .field("finished", &self.inner.finished)
933 // FIXME(#26925) Remove in favor of `#[derive(Clone)]`
934 #[stable(feature = "slice_rsplit", since = "1.27.0")]
935 impl<T, P> Clone for RSplit<'_, T, P>
937 P: Clone + FnMut(&T) -> bool,
939 fn clone(&self) -> Self {
940 RSplit { inner: self.inner.clone() }
944 #[stable(feature = "slice_rsplit", since = "1.27.0")]
945 impl<'a, T, P> Iterator for RSplit<'a, T, P>
947 P: FnMut(&T) -> bool,
952 fn next(&mut self) -> Option<&'a [T]> {
953 self.inner.next_back()
957 fn size_hint(&self) -> (usize, Option<usize>) {
958 self.inner.size_hint()
962 #[stable(feature = "slice_rsplit", since = "1.27.0")]
963 impl<'a, T, P> DoubleEndedIterator for RSplit<'a, T, P>
965 P: FnMut(&T) -> bool,
968 fn next_back(&mut self) -> Option<&'a [T]> {
973 #[stable(feature = "slice_rsplit", since = "1.27.0")]
974 impl<'a, T, P> SplitIter for RSplit<'a, T, P>
976 P: FnMut(&T) -> bool,
979 fn finish(&mut self) -> Option<&'a [T]> {
984 #[stable(feature = "slice_rsplit", since = "1.27.0")]
985 impl<T, P> FusedIterator for RSplit<'_, T, P> where P: FnMut(&T) -> bool {}
987 /// An iterator over the subslices of the vector which are separated
988 /// by elements that match `pred`, starting from the end of the slice.
990 /// This struct is created by the [`rsplit_mut`] method on [slices].
995 /// let mut slice = [11, 22, 33, 0, 44, 55];
996 /// let iter = slice.rsplit_mut(|num| *num == 0);
999 /// [`rsplit_mut`]: slice::rsplit_mut
1001 #[stable(feature = "slice_rsplit", since = "1.27.0")]
1002 #[must_use = "iterators are lazy and do nothing unless consumed"]
1003 pub struct RSplitMut<'a, T: 'a, P>
1005 P: FnMut(&T) -> bool,
1007 inner: SplitMut<'a, T, P>,
1010 impl<'a, T: 'a, P: FnMut(&T) -> bool> RSplitMut<'a, T, P> {
1012 pub(super) fn new(slice: &'a mut [T], pred: P) -> Self {
1013 Self { inner: SplitMut::new(slice, pred) }
1017 #[stable(feature = "slice_rsplit", since = "1.27.0")]
1018 impl<T: fmt::Debug, P> fmt::Debug for RSplitMut<'_, T, P>
1020 P: FnMut(&T) -> bool,
1022 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
1023 f.debug_struct("RSplitMut")
1024 .field("v", &self.inner.v)
1025 .field("finished", &self.inner.finished)
1030 #[stable(feature = "slice_rsplit", since = "1.27.0")]
1031 impl<'a, T, P> SplitIter for RSplitMut<'a, T, P>
1033 P: FnMut(&T) -> bool,
1036 fn finish(&mut self) -> Option<&'a mut [T]> {
1041 #[stable(feature = "slice_rsplit", since = "1.27.0")]
1042 impl<'a, T, P> Iterator for RSplitMut<'a, T, P>
1044 P: FnMut(&T) -> bool,
1046 type Item = &'a mut [T];
1049 fn next(&mut self) -> Option<&'a mut [T]> {
1050 self.inner.next_back()
1054 fn size_hint(&self) -> (usize, Option<usize>) {
1055 self.inner.size_hint()
1059 #[stable(feature = "slice_rsplit", since = "1.27.0")]
1060 impl<'a, T, P> DoubleEndedIterator for RSplitMut<'a, T, P>
1062 P: FnMut(&T) -> bool,
1065 fn next_back(&mut self) -> Option<&'a mut [T]> {
1070 #[stable(feature = "slice_rsplit", since = "1.27.0")]
1071 impl<T, P> FusedIterator for RSplitMut<'_, T, P> where P: FnMut(&T) -> bool {}
1073 /// An private iterator over subslices separated by elements that
1074 /// match a predicate function, splitting at most a fixed number of
1077 struct GenericSplitN<I> {
1082 impl<T, I: SplitIter<Item = T>> Iterator for GenericSplitN<I> {
1086 fn next(&mut self) -> Option<T> {
1101 fn size_hint(&self) -> (usize, Option<usize>) {
1102 let (lower, upper_opt) = self.iter.size_hint();
1104 cmp::min(self.count, lower),
1105 Some(upper_opt.map_or(self.count, |upper| cmp::min(self.count, upper))),
1110 /// An iterator over subslices separated by elements that match a predicate
1111 /// function, limited to a given number of splits.
1113 /// This struct is created by the [`splitn`] method on [slices].
1118 /// let slice = [10, 40, 30, 20, 60, 50];
1119 /// let iter = slice.splitn(2, |num| *num % 3 == 0);
1122 /// [`splitn`]: slice::splitn
1124 #[stable(feature = "rust1", since = "1.0.0")]
1125 #[must_use = "iterators are lazy and do nothing unless consumed"]
1126 pub struct SplitN<'a, T: 'a, P>
1128 P: FnMut(&T) -> bool,
1130 inner: GenericSplitN<Split<'a, T, P>>,
1133 impl<'a, T: 'a, P: FnMut(&T) -> bool> SplitN<'a, T, P> {
1135 pub(super) fn new(s: Split<'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 SplitN<'_, T, P>
1143 P: FnMut(&T) -> bool,
1145 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
1146 f.debug_struct("SplitN").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`] method on [slices].
1159 /// let slice = [10, 40, 30, 20, 60, 50];
1160 /// let iter = slice.rsplitn(2, |num| *num % 3 == 0);
1163 /// [`rsplitn`]: slice::rsplitn
1165 #[stable(feature = "rust1", since = "1.0.0")]
1166 #[must_use = "iterators are lazy and do nothing unless consumed"]
1167 pub struct RSplitN<'a, T: 'a, P>
1169 P: FnMut(&T) -> bool,
1171 inner: GenericSplitN<RSplit<'a, T, P>>,
1174 impl<'a, T: 'a, P: FnMut(&T) -> bool> RSplitN<'a, T, P> {
1176 pub(super) fn new(s: RSplit<'a, T, P>, n: usize) -> Self {
1177 Self { inner: GenericSplitN { iter: s, count: n } }
1181 #[stable(feature = "core_impl_debug", since = "1.9.0")]
1182 impl<T: fmt::Debug, P> fmt::Debug for RSplitN<'_, T, P>
1184 P: FnMut(&T) -> bool,
1186 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
1187 f.debug_struct("RSplitN").field("inner", &self.inner).finish()
1191 /// An iterator over subslices separated by elements that match a predicate
1192 /// function, limited to a given number of splits.
1194 /// This struct is created by the [`splitn_mut`] method on [slices].
1199 /// let mut slice = [10, 40, 30, 20, 60, 50];
1200 /// let iter = slice.splitn_mut(2, |num| *num % 3 == 0);
1203 /// [`splitn_mut`]: slice::splitn_mut
1205 #[stable(feature = "rust1", since = "1.0.0")]
1206 #[must_use = "iterators are lazy and do nothing unless consumed"]
1207 pub struct SplitNMut<'a, T: 'a, P>
1209 P: FnMut(&T) -> bool,
1211 inner: GenericSplitN<SplitMut<'a, T, P>>,
1214 impl<'a, T: 'a, P: FnMut(&T) -> bool> SplitNMut<'a, T, P> {
1216 pub(super) fn new(s: SplitMut<'a, T, P>, n: usize) -> Self {
1217 Self { inner: GenericSplitN { iter: s, count: n } }
1221 #[stable(feature = "core_impl_debug", since = "1.9.0")]
1222 impl<T: fmt::Debug, P> fmt::Debug for SplitNMut<'_, T, P>
1224 P: FnMut(&T) -> bool,
1226 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
1227 f.debug_struct("SplitNMut").field("inner", &self.inner).finish()
1231 /// An iterator over subslices separated by elements that match a
1232 /// predicate function, limited to a given number of splits, starting
1233 /// from the end of the slice.
1235 /// This struct is created by the [`rsplitn_mut`] method on [slices].
1240 /// let mut slice = [10, 40, 30, 20, 60, 50];
1241 /// let iter = slice.rsplitn_mut(2, |num| *num % 3 == 0);
1244 /// [`rsplitn_mut`]: slice::rsplitn_mut
1246 #[stable(feature = "rust1", since = "1.0.0")]
1247 #[must_use = "iterators are lazy and do nothing unless consumed"]
1248 pub struct RSplitNMut<'a, T: 'a, P>
1250 P: FnMut(&T) -> bool,
1252 inner: GenericSplitN<RSplitMut<'a, T, P>>,
1255 impl<'a, T: 'a, P: FnMut(&T) -> bool> RSplitNMut<'a, T, P> {
1257 pub(super) fn new(s: RSplitMut<'a, T, P>, n: usize) -> Self {
1258 Self { inner: GenericSplitN { iter: s, count: n } }
1262 #[stable(feature = "core_impl_debug", since = "1.9.0")]
1263 impl<T: fmt::Debug, P> fmt::Debug for RSplitNMut<'_, T, P>
1265 P: FnMut(&T) -> bool,
1267 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
1268 f.debug_struct("RSplitNMut").field("inner", &self.inner).finish()
1272 forward_iterator! { SplitN: T, &'a [T] }
1273 forward_iterator! { RSplitN: T, &'a [T] }
1274 forward_iterator! { SplitNMut: T, &'a mut [T] }
1275 forward_iterator! { RSplitNMut: T, &'a mut [T] }
1277 /// An iterator over overlapping subslices of length `size`.
1279 /// This struct is created by the [`windows`] method on [slices].
1284 /// let slice = ['r', 'u', 's', 't'];
1285 /// let iter = slice.windows(2);
1288 /// [`windows`]: slice::windows
1291 #[stable(feature = "rust1", since = "1.0.0")]
1292 #[must_use = "iterators are lazy and do nothing unless consumed"]
1293 pub struct Windows<'a, T: 'a> {
1298 impl<'a, T: 'a> Windows<'a, T> {
1300 pub(super) fn new(slice: &'a [T], size: NonZeroUsize) -> Self {
1301 Self { v: slice, size }
1305 // FIXME(#26925) Remove in favor of `#[derive(Clone)]`
1306 #[stable(feature = "rust1", since = "1.0.0")]
1307 impl<T> Clone for Windows<'_, T> {
1308 fn clone(&self) -> Self {
1309 Windows { v: self.v, size: self.size }
1313 #[stable(feature = "rust1", since = "1.0.0")]
1314 impl<'a, T> Iterator for Windows<'a, T> {
1315 type Item = &'a [T];
1318 fn next(&mut self) -> Option<&'a [T]> {
1319 if self.size.get() > self.v.len() {
1322 let ret = Some(&self.v[..self.size.get()]);
1323 self.v = &self.v[1..];
1329 fn size_hint(&self) -> (usize, Option<usize>) {
1330 if self.size.get() > self.v.len() {
1333 let size = self.v.len() - self.size.get() + 1;
1339 fn count(self) -> usize {
1344 fn nth(&mut self, n: usize) -> Option<Self::Item> {
1345 let (end, overflow) = self.size.get().overflowing_add(n);
1346 if end > self.v.len() || overflow {
1350 let nth = &self.v[n..end];
1351 self.v = &self.v[n + 1..];
1357 fn last(self) -> Option<Self::Item> {
1358 if self.size.get() > self.v.len() {
1361 let start = self.v.len() - self.size.get();
1362 Some(&self.v[start..])
1366 unsafe fn __iterator_get_unchecked(&mut self, idx: usize) -> Self::Item {
1367 // SAFETY: since the caller guarantees that `i` is in bounds,
1368 // which means that `i` cannot overflow an `isize`, and the
1369 // slice created by `from_raw_parts` is a subslice of `self.v`
1370 // thus is guaranteed to be valid for the lifetime `'a` of `self.v`.
1371 unsafe { from_raw_parts(self.v.as_ptr().add(idx), self.size.get()) }
1375 #[stable(feature = "rust1", since = "1.0.0")]
1376 impl<'a, T> DoubleEndedIterator for Windows<'a, T> {
1378 fn next_back(&mut self) -> Option<&'a [T]> {
1379 if self.size.get() > self.v.len() {
1382 let ret = Some(&self.v[self.v.len() - self.size.get()..]);
1383 self.v = &self.v[..self.v.len() - 1];
1389 fn nth_back(&mut self, n: usize) -> Option<Self::Item> {
1390 let (end, overflow) = self.v.len().overflowing_sub(n);
1391 if end < self.size.get() || overflow {
1395 let ret = &self.v[end - self.size.get()..end];
1396 self.v = &self.v[..end - 1];
1402 #[stable(feature = "rust1", since = "1.0.0")]
1403 impl<T> ExactSizeIterator for Windows<'_, T> {}
1405 #[unstable(feature = "trusted_len", issue = "37572")]
1406 unsafe impl<T> TrustedLen for Windows<'_, T> {}
1408 #[stable(feature = "fused", since = "1.26.0")]
1409 impl<T> FusedIterator for Windows<'_, T> {}
1412 #[unstable(feature = "trusted_random_access", issue = "none")]
1413 unsafe impl<'a, T> TrustedRandomAccess for Windows<'a, T> {}
1416 #[unstable(feature = "trusted_random_access", issue = "none")]
1417 unsafe impl<'a, T> TrustedRandomAccessNoCoerce for Windows<'a, T> {
1418 const MAY_HAVE_SIDE_EFFECT: bool = false;
1421 /// An iterator over a slice in (non-overlapping) chunks (`chunk_size` elements at a
1422 /// time), starting at the beginning of the slice.
1424 /// When the slice len is not evenly divided by the chunk size, the last slice
1425 /// of the iteration will be the remainder.
1427 /// This struct is created by the [`chunks`] method on [slices].
1432 /// let slice = ['l', 'o', 'r', 'e', 'm'];
1433 /// let iter = slice.chunks(2);
1436 /// [`chunks`]: slice::chunks
1439 #[stable(feature = "rust1", since = "1.0.0")]
1440 #[must_use = "iterators are lazy and do nothing unless consumed"]
1441 pub struct Chunks<'a, T: 'a> {
1446 impl<'a, T: 'a> Chunks<'a, T> {
1448 pub(super) fn new(slice: &'a [T], size: usize) -> Self {
1449 Self { v: slice, chunk_size: size }
1453 // FIXME(#26925) Remove in favor of `#[derive(Clone)]`
1454 #[stable(feature = "rust1", since = "1.0.0")]
1455 impl<T> Clone for Chunks<'_, T> {
1456 fn clone(&self) -> Self {
1457 Chunks { v: self.v, chunk_size: self.chunk_size }
1461 #[stable(feature = "rust1", since = "1.0.0")]
1462 impl<'a, T> Iterator for Chunks<'a, T> {
1463 type Item = &'a [T];
1466 fn next(&mut self) -> Option<&'a [T]> {
1467 if self.v.is_empty() {
1470 let chunksz = cmp::min(self.v.len(), self.chunk_size);
1471 let (fst, snd) = self.v.split_at(chunksz);
1478 fn size_hint(&self) -> (usize, Option<usize>) {
1479 if self.v.is_empty() {
1482 let n = self.v.len() / self.chunk_size;
1483 let rem = self.v.len() % self.chunk_size;
1484 let n = if rem > 0 { n + 1 } else { n };
1490 fn count(self) -> usize {
1495 fn nth(&mut self, n: usize) -> Option<Self::Item> {
1496 let (start, overflow) = n.overflowing_mul(self.chunk_size);
1497 if start >= self.v.len() || overflow {
1501 let end = match start.checked_add(self.chunk_size) {
1502 Some(sum) => cmp::min(self.v.len(), sum),
1503 None => self.v.len(),
1505 let nth = &self.v[start..end];
1506 self.v = &self.v[end..];
1512 fn last(self) -> Option<Self::Item> {
1513 if self.v.is_empty() {
1516 let start = (self.v.len() - 1) / self.chunk_size * self.chunk_size;
1517 Some(&self.v[start..])
1521 unsafe fn __iterator_get_unchecked(&mut self, idx: usize) -> Self::Item {
1522 let start = idx * self.chunk_size;
1523 // SAFETY: the caller guarantees that `i` is in bounds,
1524 // which means that `start` must be in bounds of the
1525 // underlying `self.v` slice, and we made sure that `len`
1526 // is also in bounds of `self.v`. Thus, `start` cannot overflow
1527 // an `isize`, and the slice constructed by `from_raw_parts`
1528 // is a subslice of `self.v` which is guaranteed to be valid
1529 // for the lifetime `'a` of `self.v`.
1531 let len = cmp::min(self.v.len().unchecked_sub(start), self.chunk_size);
1532 from_raw_parts(self.v.as_ptr().add(start), len)
1537 #[stable(feature = "rust1", since = "1.0.0")]
1538 impl<'a, T> DoubleEndedIterator for Chunks<'a, T> {
1540 fn next_back(&mut self) -> Option<&'a [T]> {
1541 if self.v.is_empty() {
1544 let remainder = self.v.len() % self.chunk_size;
1545 let chunksz = if remainder != 0 { remainder } else { self.chunk_size };
1546 // SAFETY: split_at_unchecked requires the argument be less than or
1547 // equal to the length. This is guaranteed, but subtle: `chunksz`
1548 // will always either be `self.v.len() % self.chunk_size`, which
1549 // will always evaluate to strictly less than `self.v.len()` (or
1550 // panic, in the case that `self.chunk_size` is zero), or it can be
1551 // `self.chunk_size`, in the case that the length is exactly
1552 // divisible by the chunk size.
1554 // While it seems like using `self.chunk_size` in this case could
1555 // lead to a value greater than `self.v.len()`, it cannot: if
1556 // `self.chunk_size` were greater than `self.v.len()`, then
1557 // `self.v.len() % self.chunk_size` would return nonzero (note that
1558 // in this branch of the `if`, we already know that `self.v` is
1560 let (fst, snd) = unsafe { self.v.split_at_unchecked(self.v.len() - chunksz) };
1567 fn nth_back(&mut self, n: usize) -> Option<Self::Item> {
1568 let len = self.len();
1573 let start = (len - 1 - n) * self.chunk_size;
1574 let end = match start.checked_add(self.chunk_size) {
1575 Some(res) => cmp::min(self.v.len(), res),
1576 None => self.v.len(),
1578 let nth_back = &self.v[start..end];
1579 self.v = &self.v[..start];
1585 #[stable(feature = "rust1", since = "1.0.0")]
1586 impl<T> ExactSizeIterator for Chunks<'_, T> {}
1588 #[unstable(feature = "trusted_len", issue = "37572")]
1589 unsafe impl<T> TrustedLen for Chunks<'_, T> {}
1591 #[stable(feature = "fused", since = "1.26.0")]
1592 impl<T> FusedIterator for Chunks<'_, T> {}
1595 #[unstable(feature = "trusted_random_access", issue = "none")]
1596 unsafe impl<'a, T> TrustedRandomAccess for Chunks<'a, T> {}
1599 #[unstable(feature = "trusted_random_access", issue = "none")]
1600 unsafe impl<'a, T> TrustedRandomAccessNoCoerce for Chunks<'a, T> {
1601 const MAY_HAVE_SIDE_EFFECT: bool = false;
1604 /// An iterator over a slice in (non-overlapping) mutable chunks (`chunk_size`
1605 /// elements at a time), starting at the beginning of the slice.
1607 /// When the slice len is not evenly divided by the chunk size, the last slice
1608 /// of the iteration will be the remainder.
1610 /// This struct is created by the [`chunks_mut`] method on [slices].
1615 /// let mut slice = ['l', 'o', 'r', 'e', 'm'];
1616 /// let iter = slice.chunks_mut(2);
1619 /// [`chunks_mut`]: slice::chunks_mut
1622 #[stable(feature = "rust1", since = "1.0.0")]
1623 #[must_use = "iterators are lazy and do nothing unless consumed"]
1624 pub struct ChunksMut<'a, T: 'a> {
1626 /// This slice pointer must point at a valid region of `T` with at least length `v.len()`. Normally,
1627 /// those requirements would mean that we could instead use a `&mut [T]` here, but we cannot
1628 /// because `__iterator_get_unchecked` needs to return `&mut [T]`, which guarantees certain aliasing
1629 /// properties that we cannot uphold if we hold on to the full original `&mut [T]`. Wrapping a raw
1630 /// slice instead lets us hand out non-overlapping `&mut [T]` subslices of the slice we wrap.
1633 _marker: PhantomData<&'a mut T>,
1636 impl<'a, T: 'a> ChunksMut<'a, T> {
1638 pub(super) fn new(slice: &'a mut [T], size: usize) -> Self {
1639 Self { v: slice, chunk_size: size, _marker: PhantomData }
1643 #[stable(feature = "rust1", since = "1.0.0")]
1644 impl<'a, T> Iterator for ChunksMut<'a, T> {
1645 type Item = &'a mut [T];
1648 fn next(&mut self) -> Option<&'a mut [T]> {
1649 if self.v.is_empty() {
1652 let sz = cmp::min(self.v.len(), self.chunk_size);
1653 // SAFETY: The self.v contract ensures that any split_at_mut is valid.
1654 let (head, tail) = unsafe { self.v.split_at_mut(sz) };
1656 // SAFETY: Nothing else points to or will point to the contents of this slice.
1657 Some(unsafe { &mut *head })
1662 fn size_hint(&self) -> (usize, Option<usize>) {
1663 if self.v.is_empty() {
1666 let n = self.v.len() / self.chunk_size;
1667 let rem = self.v.len() % self.chunk_size;
1668 let n = if rem > 0 { n + 1 } else { n };
1674 fn count(self) -> usize {
1679 fn nth(&mut self, n: usize) -> Option<&'a mut [T]> {
1680 let (start, overflow) = n.overflowing_mul(self.chunk_size);
1681 if start >= self.v.len() || overflow {
1685 let end = match start.checked_add(self.chunk_size) {
1686 Some(sum) => cmp::min(self.v.len(), sum),
1687 None => self.v.len(),
1689 // SAFETY: The self.v contract ensures that any split_at_mut is valid.
1690 let (head, tail) = unsafe { self.v.split_at_mut(end) };
1691 // SAFETY: The self.v contract ensures that any split_at_mut is valid.
1692 let (_, nth) = unsafe { head.split_at_mut(start) };
1694 // SAFETY: Nothing else points to or will point to the contents of this slice.
1695 Some(unsafe { &mut *nth })
1700 fn last(self) -> Option<Self::Item> {
1701 if self.v.is_empty() {
1704 let start = (self.v.len() - 1) / self.chunk_size * self.chunk_size;
1705 // SAFETY: Nothing else points to or will point to the contents of this slice.
1706 Some(unsafe { &mut *self.v.get_unchecked_mut(start..) })
1710 unsafe fn __iterator_get_unchecked(&mut self, idx: usize) -> Self::Item {
1711 let start = idx * self.chunk_size;
1712 // SAFETY: see comments for `Chunks::__iterator_get_unchecked` and `self.v`.
1714 // Also note that the caller also guarantees that we're never called
1715 // with the same index again, and that no other methods that will
1716 // access this subslice are called, so it is valid for the returned
1717 // slice to be mutable.
1719 let len = cmp::min(self.v.len().unchecked_sub(start), self.chunk_size);
1720 from_raw_parts_mut(self.v.as_mut_ptr().add(start), len)
1725 #[stable(feature = "rust1", since = "1.0.0")]
1726 impl<'a, T> DoubleEndedIterator for ChunksMut<'a, T> {
1728 fn next_back(&mut self) -> Option<&'a mut [T]> {
1729 if self.v.is_empty() {
1732 let remainder = self.v.len() % self.chunk_size;
1733 let sz = if remainder != 0 { remainder } else { self.chunk_size };
1734 let len = self.v.len();
1735 // SAFETY: Similar to `Chunks::next_back`
1736 let (head, tail) = unsafe { self.v.split_at_mut_unchecked(len - sz) };
1738 // SAFETY: Nothing else points to or will point to the contents of this slice.
1739 Some(unsafe { &mut *tail })
1744 fn nth_back(&mut self, n: usize) -> Option<Self::Item> {
1745 let len = self.len();
1750 let start = (len - 1 - n) * self.chunk_size;
1751 let end = match start.checked_add(self.chunk_size) {
1752 Some(res) => cmp::min(self.v.len(), res),
1753 None => self.v.len(),
1755 // SAFETY: The self.v contract ensures that any split_at_mut is valid.
1756 let (temp, _tail) = unsafe { self.v.split_at_mut(end) };
1757 // SAFETY: The self.v contract ensures that any split_at_mut is valid.
1758 let (head, nth_back) = unsafe { temp.split_at_mut(start) };
1760 // SAFETY: Nothing else points to or will point to the contents of this slice.
1761 Some(unsafe { &mut *nth_back })
1766 #[stable(feature = "rust1", since = "1.0.0")]
1767 impl<T> ExactSizeIterator for ChunksMut<'_, T> {}
1769 #[unstable(feature = "trusted_len", issue = "37572")]
1770 unsafe impl<T> TrustedLen for ChunksMut<'_, T> {}
1772 #[stable(feature = "fused", since = "1.26.0")]
1773 impl<T> FusedIterator for ChunksMut<'_, T> {}
1776 #[unstable(feature = "trusted_random_access", issue = "none")]
1777 unsafe impl<'a, T> TrustedRandomAccess for ChunksMut<'a, T> {}
1780 #[unstable(feature = "trusted_random_access", issue = "none")]
1781 unsafe impl<'a, T> TrustedRandomAccessNoCoerce for ChunksMut<'a, T> {
1782 const MAY_HAVE_SIDE_EFFECT: bool = false;
1785 #[stable(feature = "rust1", since = "1.0.0")]
1786 unsafe impl<T> Send for ChunksMut<'_, T> where T: Send {}
1788 #[stable(feature = "rust1", since = "1.0.0")]
1789 unsafe impl<T> Sync for ChunksMut<'_, T> where T: Sync {}
1791 /// An iterator over a slice in (non-overlapping) chunks (`chunk_size` elements at a
1792 /// time), starting at the beginning of the slice.
1794 /// When the slice len is not evenly divided by the chunk size, the last
1795 /// up to `chunk_size-1` elements will be omitted but can be retrieved from
1796 /// the [`remainder`] function from the iterator.
1798 /// This struct is created by the [`chunks_exact`] method on [slices].
1803 /// let slice = ['l', 'o', 'r', 'e', 'm'];
1804 /// let iter = slice.chunks_exact(2);
1807 /// [`chunks_exact`]: slice::chunks_exact
1808 /// [`remainder`]: ChunksExact::remainder
1811 #[stable(feature = "chunks_exact", since = "1.31.0")]
1812 #[must_use = "iterators are lazy and do nothing unless consumed"]
1813 pub struct ChunksExact<'a, T: 'a> {
1819 impl<'a, T> ChunksExact<'a, T> {
1821 pub(super) fn new(slice: &'a [T], chunk_size: usize) -> Self {
1822 let rem = slice.len() % chunk_size;
1823 let fst_len = slice.len() - rem;
1824 // SAFETY: 0 <= fst_len <= slice.len() by construction above
1825 let (fst, snd) = unsafe { slice.split_at_unchecked(fst_len) };
1826 Self { v: fst, rem: snd, chunk_size }
1829 /// Returns the remainder of the original slice that is not going to be
1830 /// returned by the iterator. The returned slice has at most `chunk_size-1`
1833 #[stable(feature = "chunks_exact", since = "1.31.0")]
1834 pub fn remainder(&self) -> &'a [T] {
1839 // FIXME(#26925) Remove in favor of `#[derive(Clone)]`
1840 #[stable(feature = "chunks_exact", since = "1.31.0")]
1841 impl<T> Clone for ChunksExact<'_, T> {
1842 fn clone(&self) -> Self {
1843 ChunksExact { v: self.v, rem: self.rem, chunk_size: self.chunk_size }
1847 #[stable(feature = "chunks_exact", since = "1.31.0")]
1848 impl<'a, T> Iterator for ChunksExact<'a, T> {
1849 type Item = &'a [T];
1852 fn next(&mut self) -> Option<&'a [T]> {
1853 if self.v.len() < self.chunk_size {
1856 let (fst, snd) = self.v.split_at(self.chunk_size);
1863 fn size_hint(&self) -> (usize, Option<usize>) {
1864 let n = self.v.len() / self.chunk_size;
1869 fn count(self) -> usize {
1874 fn nth(&mut self, n: usize) -> Option<Self::Item> {
1875 let (start, overflow) = n.overflowing_mul(self.chunk_size);
1876 if start >= self.v.len() || overflow {
1880 let (_, snd) = self.v.split_at(start);
1887 fn last(mut self) -> Option<Self::Item> {
1891 unsafe fn __iterator_get_unchecked(&mut self, idx: usize) -> Self::Item {
1892 let start = idx * self.chunk_size;
1893 // SAFETY: mostly identical to `Chunks::__iterator_get_unchecked`.
1894 unsafe { from_raw_parts(self.v.as_ptr().add(start), self.chunk_size) }
1898 #[stable(feature = "chunks_exact", since = "1.31.0")]
1899 impl<'a, T> DoubleEndedIterator for ChunksExact<'a, T> {
1901 fn next_back(&mut self) -> Option<&'a [T]> {
1902 if self.v.len() < self.chunk_size {
1905 let (fst, snd) = self.v.split_at(self.v.len() - self.chunk_size);
1912 fn nth_back(&mut self, n: usize) -> Option<Self::Item> {
1913 let len = self.len();
1918 let start = (len - 1 - n) * self.chunk_size;
1919 let end = start + self.chunk_size;
1920 let nth_back = &self.v[start..end];
1921 self.v = &self.v[..start];
1927 #[stable(feature = "chunks_exact", since = "1.31.0")]
1928 impl<T> ExactSizeIterator for ChunksExact<'_, T> {
1929 fn is_empty(&self) -> bool {
1934 #[unstable(feature = "trusted_len", issue = "37572")]
1935 unsafe impl<T> TrustedLen for ChunksExact<'_, T> {}
1937 #[stable(feature = "chunks_exact", since = "1.31.0")]
1938 impl<T> FusedIterator for ChunksExact<'_, T> {}
1941 #[unstable(feature = "trusted_random_access", issue = "none")]
1942 unsafe impl<'a, T> TrustedRandomAccess for ChunksExact<'a, T> {}
1945 #[unstable(feature = "trusted_random_access", issue = "none")]
1946 unsafe impl<'a, T> TrustedRandomAccessNoCoerce for ChunksExact<'a, T> {
1947 const MAY_HAVE_SIDE_EFFECT: bool = false;
1950 /// An iterator over a slice in (non-overlapping) mutable chunks (`chunk_size`
1951 /// elements at a time), starting at the beginning of the slice.
1953 /// When the slice len is not evenly divided by the chunk size, the last up to
1954 /// `chunk_size-1` elements will be omitted but can be retrieved from the
1955 /// [`into_remainder`] function from the iterator.
1957 /// This struct is created by the [`chunks_exact_mut`] method on [slices].
1962 /// let mut slice = ['l', 'o', 'r', 'e', 'm'];
1963 /// let iter = slice.chunks_exact_mut(2);
1966 /// [`chunks_exact_mut`]: slice::chunks_exact_mut
1967 /// [`into_remainder`]: ChunksExactMut::into_remainder
1970 #[stable(feature = "chunks_exact", since = "1.31.0")]
1971 #[must_use = "iterators are lazy and do nothing unless consumed"]
1972 pub struct ChunksExactMut<'a, T: 'a> {
1974 /// This slice pointer must point at a valid region of `T` with at least length `v.len()`. Normally,
1975 /// those requirements would mean that we could instead use a `&mut [T]` here, but we cannot
1976 /// because `__iterator_get_unchecked` needs to return `&mut [T]`, which guarantees certain aliasing
1977 /// properties that we cannot uphold if we hold on to the full original `&mut [T]`. Wrapping a raw
1978 /// slice instead lets us hand out non-overlapping `&mut [T]` subslices of the slice we wrap.
1980 rem: &'a mut [T], // The iterator never yields from here, so this can be unique
1982 _marker: PhantomData<&'a mut T>,
1985 impl<'a, T> ChunksExactMut<'a, T> {
1987 pub(super) fn new(slice: &'a mut [T], chunk_size: usize) -> Self {
1988 let rem = slice.len() % chunk_size;
1989 let fst_len = slice.len() - rem;
1990 // SAFETY: 0 <= fst_len <= slice.len() by construction above
1991 let (fst, snd) = unsafe { slice.split_at_mut_unchecked(fst_len) };
1992 Self { v: fst, rem: snd, chunk_size, _marker: PhantomData }
1995 /// Returns the remainder of the original slice that is not going to be
1996 /// returned by the iterator. The returned slice has at most `chunk_size-1`
1998 #[must_use = "`self` will be dropped if the result is not used"]
1999 #[stable(feature = "chunks_exact", since = "1.31.0")]
2000 pub fn into_remainder(self) -> &'a mut [T] {
2005 #[stable(feature = "chunks_exact", since = "1.31.0")]
2006 impl<'a, T> Iterator for ChunksExactMut<'a, T> {
2007 type Item = &'a mut [T];
2010 fn next(&mut self) -> Option<&'a mut [T]> {
2011 if self.v.len() < self.chunk_size {
2014 // SAFETY: self.chunk_size is inbounds because we compared above against self.v.len()
2015 let (head, tail) = unsafe { self.v.split_at_mut(self.chunk_size) };
2017 // SAFETY: Nothing else points to or will point to the contents of this slice.
2018 Some(unsafe { &mut *head })
2023 fn size_hint(&self) -> (usize, Option<usize>) {
2024 let n = self.v.len() / self.chunk_size;
2029 fn count(self) -> usize {
2034 fn nth(&mut self, n: usize) -> Option<&'a mut [T]> {
2035 let (start, overflow) = n.overflowing_mul(self.chunk_size);
2036 if start >= self.v.len() || overflow {
2040 // SAFETY: The self.v contract ensures that any split_at_mut is valid.
2041 let (_, snd) = unsafe { self.v.split_at_mut(start) };
2048 fn last(mut self) -> Option<Self::Item> {
2052 unsafe fn __iterator_get_unchecked(&mut self, idx: usize) -> Self::Item {
2053 let start = idx * self.chunk_size;
2054 // SAFETY: see comments for `Chunks::__iterator_get_unchecked` and `self.v`.
2055 unsafe { from_raw_parts_mut(self.v.as_mut_ptr().add(start), self.chunk_size) }
2059 #[stable(feature = "chunks_exact", since = "1.31.0")]
2060 impl<'a, T> DoubleEndedIterator for ChunksExactMut<'a, T> {
2062 fn next_back(&mut self) -> Option<&'a mut [T]> {
2063 if self.v.len() < self.chunk_size {
2066 // SAFETY: This subtraction is inbounds because of the check above
2067 let (head, tail) = unsafe { self.v.split_at_mut(self.v.len() - self.chunk_size) };
2069 // SAFETY: Nothing else points to or will point to the contents of this slice.
2070 Some(unsafe { &mut *tail })
2075 fn nth_back(&mut self, n: usize) -> Option<Self::Item> {
2076 let len = self.len();
2081 let start = (len - 1 - n) * self.chunk_size;
2082 let end = start + self.chunk_size;
2083 // SAFETY: The self.v contract ensures that any split_at_mut is valid.
2084 let (temp, _tail) = unsafe { mem::replace(&mut self.v, &mut []).split_at_mut(end) };
2085 // SAFETY: The self.v contract ensures that any split_at_mut is valid.
2086 let (head, nth_back) = unsafe { temp.split_at_mut(start) };
2088 // SAFETY: Nothing else points to or will point to the contents of this slice.
2089 Some(unsafe { &mut *nth_back })
2094 #[stable(feature = "chunks_exact", since = "1.31.0")]
2095 impl<T> ExactSizeIterator for ChunksExactMut<'_, T> {
2096 fn is_empty(&self) -> bool {
2101 #[unstable(feature = "trusted_len", issue = "37572")]
2102 unsafe impl<T> TrustedLen for ChunksExactMut<'_, T> {}
2104 #[stable(feature = "chunks_exact", since = "1.31.0")]
2105 impl<T> FusedIterator for ChunksExactMut<'_, T> {}
2108 #[unstable(feature = "trusted_random_access", issue = "none")]
2109 unsafe impl<'a, T> TrustedRandomAccess for ChunksExactMut<'a, T> {}
2112 #[unstable(feature = "trusted_random_access", issue = "none")]
2113 unsafe impl<'a, T> TrustedRandomAccessNoCoerce for ChunksExactMut<'a, T> {
2114 const MAY_HAVE_SIDE_EFFECT: bool = false;
2117 #[stable(feature = "chunks_exact", since = "1.31.0")]
2118 unsafe impl<T> Send for ChunksExactMut<'_, T> where T: Send {}
2120 #[stable(feature = "chunks_exact", since = "1.31.0")]
2121 unsafe impl<T> Sync for ChunksExactMut<'_, T> where T: Sync {}
2123 /// A windowed iterator over a slice in overlapping chunks (`N` elements at a
2124 /// time), starting at the beginning of the slice
2126 /// This struct is created by the [`array_windows`] method on [slices].
2131 /// #![feature(array_windows)]
2133 /// let slice = [0, 1, 2, 3];
2134 /// let iter = slice.array_windows::<2>();
2137 /// [`array_windows`]: slice::array_windows
2139 #[derive(Debug, Clone, Copy)]
2140 #[unstable(feature = "array_windows", issue = "75027")]
2141 #[must_use = "iterators are lazy and do nothing unless consumed"]
2142 pub struct ArrayWindows<'a, T: 'a, const N: usize> {
2143 slice_head: *const T,
2145 marker: PhantomData<&'a [T; N]>,
2148 impl<'a, T: 'a, const N: usize> ArrayWindows<'a, T, N> {
2150 pub(super) fn new(slice: &'a [T]) -> Self {
2151 let num_windows = slice.len().saturating_sub(N - 1);
2152 Self { slice_head: slice.as_ptr(), num: num_windows, marker: PhantomData }
2156 #[unstable(feature = "array_windows", issue = "75027")]
2157 impl<'a, T, const N: usize> Iterator for ArrayWindows<'a, T, N> {
2158 type Item = &'a [T; N];
2161 fn next(&mut self) -> Option<Self::Item> {
2166 // This is safe because it's indexing into a slice guaranteed to be length > N.
2167 let ret = unsafe { &*self.slice_head.cast::<[T; N]>() };
2168 // SAFETY: Guaranteed that there are at least 1 item remaining otherwise
2169 // earlier branch would've been hit
2170 self.slice_head = unsafe { self.slice_head.add(1) };
2177 fn size_hint(&self) -> (usize, Option<usize>) {
2178 (self.num, Some(self.num))
2182 fn count(self) -> usize {
2187 fn nth(&mut self, n: usize) -> Option<Self::Item> {
2193 // This is safe because it's indexing into a slice guaranteed to be length > N.
2194 let ret = unsafe { &*self.slice_head.add(n).cast::<[T; N]>() };
2195 // SAFETY: Guaranteed that there are at least n items remaining
2196 self.slice_head = unsafe { self.slice_head.add(n + 1) };
2203 fn last(mut self) -> Option<Self::Item> {
2204 self.nth(self.num.checked_sub(1)?)
2208 #[unstable(feature = "array_windows", issue = "75027")]
2209 impl<'a, T, const N: usize> DoubleEndedIterator for ArrayWindows<'a, T, N> {
2211 fn next_back(&mut self) -> Option<&'a [T; N]> {
2215 // SAFETY: Guaranteed that there are n items remaining, n-1 for 0-indexing.
2216 let ret = unsafe { &*self.slice_head.add(self.num - 1).cast::<[T; N]>() };
2222 fn nth_back(&mut self, n: usize) -> Option<&'a [T; N]> {
2227 // SAFETY: Guaranteed that there are n items remaining, n-1 for 0-indexing.
2228 let ret = unsafe { &*self.slice_head.add(self.num - (n + 1)).cast::<[T; N]>() };
2234 #[unstable(feature = "array_windows", issue = "75027")]
2235 impl<T, const N: usize> ExactSizeIterator for ArrayWindows<'_, T, N> {
2236 fn is_empty(&self) -> bool {
2241 /// An iterator over a slice in (non-overlapping) chunks (`N` elements at a
2242 /// time), starting at the beginning of the slice.
2244 /// When the slice len is not evenly divided by the chunk size, the last
2245 /// up to `N-1` elements will be omitted but can be retrieved from
2246 /// the [`remainder`] function from the iterator.
2248 /// This struct is created by the [`array_chunks`] method on [slices].
2253 /// #![feature(array_chunks)]
2255 /// let slice = ['l', 'o', 'r', 'e', 'm'];
2256 /// let iter = slice.array_chunks::<2>();
2259 /// [`array_chunks`]: slice::array_chunks
2260 /// [`remainder`]: ArrayChunks::remainder
2263 #[unstable(feature = "array_chunks", issue = "74985")]
2264 #[must_use = "iterators are lazy and do nothing unless consumed"]
2265 pub struct ArrayChunks<'a, T: 'a, const N: usize> {
2266 iter: Iter<'a, [T; N]>,
2270 impl<'a, T, const N: usize> ArrayChunks<'a, T, N> {
2272 pub(super) fn new(slice: &'a [T]) -> Self {
2273 let (array_slice, rem) = slice.as_chunks();
2274 Self { iter: array_slice.iter(), rem }
2277 /// Returns the remainder of the original slice that is not going to be
2278 /// returned by the iterator. The returned slice has at most `N-1`
2281 #[unstable(feature = "array_chunks", issue = "74985")]
2282 pub fn remainder(&self) -> &'a [T] {
2287 // FIXME(#26925) Remove in favor of `#[derive(Clone)]`
2288 #[unstable(feature = "array_chunks", issue = "74985")]
2289 impl<T, const N: usize> Clone for ArrayChunks<'_, T, N> {
2290 fn clone(&self) -> Self {
2291 ArrayChunks { iter: self.iter.clone(), rem: self.rem }
2295 #[unstable(feature = "array_chunks", issue = "74985")]
2296 impl<'a, T, const N: usize> Iterator for ArrayChunks<'a, T, N> {
2297 type Item = &'a [T; N];
2300 fn next(&mut self) -> Option<&'a [T; N]> {
2305 fn size_hint(&self) -> (usize, Option<usize>) {
2306 self.iter.size_hint()
2310 fn count(self) -> usize {
2315 fn nth(&mut self, n: usize) -> Option<Self::Item> {
2320 fn last(self) -> Option<Self::Item> {
2324 unsafe fn __iterator_get_unchecked(&mut self, i: usize) -> &'a [T; N] {
2325 // SAFETY: The safety guarantees of `__iterator_get_unchecked` are
2326 // transferred to the caller.
2327 unsafe { self.iter.__iterator_get_unchecked(i) }
2331 #[unstable(feature = "array_chunks", issue = "74985")]
2332 impl<'a, T, const N: usize> DoubleEndedIterator for ArrayChunks<'a, T, N> {
2334 fn next_back(&mut self) -> Option<&'a [T; N]> {
2335 self.iter.next_back()
2339 fn nth_back(&mut self, n: usize) -> Option<Self::Item> {
2340 self.iter.nth_back(n)
2344 #[unstable(feature = "array_chunks", issue = "74985")]
2345 impl<T, const N: usize> ExactSizeIterator for ArrayChunks<'_, T, N> {
2346 fn is_empty(&self) -> bool {
2347 self.iter.is_empty()
2351 #[unstable(feature = "trusted_len", issue = "37572")]
2352 unsafe impl<T, const N: usize> TrustedLen for ArrayChunks<'_, T, N> {}
2354 #[unstable(feature = "array_chunks", issue = "74985")]
2355 impl<T, const N: usize> FusedIterator for ArrayChunks<'_, T, N> {}
2358 #[unstable(feature = "array_chunks", issue = "74985")]
2359 unsafe impl<'a, T, const N: usize> TrustedRandomAccess for ArrayChunks<'a, T, N> {}
2362 #[unstable(feature = "array_chunks", issue = "74985")]
2363 unsafe impl<'a, T, const N: usize> TrustedRandomAccessNoCoerce for ArrayChunks<'a, T, N> {
2364 const MAY_HAVE_SIDE_EFFECT: bool = false;
2367 /// An iterator over a slice in (non-overlapping) mutable chunks (`N` elements
2368 /// at a time), starting at the beginning of the slice.
2370 /// When the slice len is not evenly divided by the chunk size, the last
2371 /// up to `N-1` elements will be omitted but can be retrieved from
2372 /// the [`into_remainder`] function from the iterator.
2374 /// This struct is created by the [`array_chunks_mut`] method on [slices].
2379 /// #![feature(array_chunks)]
2381 /// let mut slice = ['l', 'o', 'r', 'e', 'm'];
2382 /// let iter = slice.array_chunks_mut::<2>();
2385 /// [`array_chunks_mut`]: slice::array_chunks_mut
2386 /// [`into_remainder`]: ../../std/slice/struct.ArrayChunksMut.html#method.into_remainder
2389 #[unstable(feature = "array_chunks", issue = "74985")]
2390 #[must_use = "iterators are lazy and do nothing unless consumed"]
2391 pub struct ArrayChunksMut<'a, T: 'a, const N: usize> {
2392 iter: IterMut<'a, [T; N]>,
2396 impl<'a, T, const N: usize> ArrayChunksMut<'a, T, N> {
2398 pub(super) fn new(slice: &'a mut [T]) -> Self {
2399 let (array_slice, rem) = slice.as_chunks_mut();
2400 Self { iter: array_slice.iter_mut(), rem }
2403 /// Returns the remainder of the original slice that is not going to be
2404 /// returned by the iterator. The returned slice has at most `N-1`
2406 #[must_use = "`self` will be dropped if the result is not used"]
2407 #[unstable(feature = "array_chunks", issue = "74985")]
2408 pub fn into_remainder(self) -> &'a mut [T] {
2413 #[unstable(feature = "array_chunks", issue = "74985")]
2414 impl<'a, T, const N: usize> Iterator for ArrayChunksMut<'a, T, N> {
2415 type Item = &'a mut [T; N];
2418 fn next(&mut self) -> Option<&'a mut [T; N]> {
2423 fn size_hint(&self) -> (usize, Option<usize>) {
2424 self.iter.size_hint()
2428 fn count(self) -> usize {
2433 fn nth(&mut self, n: usize) -> Option<Self::Item> {
2438 fn last(self) -> Option<Self::Item> {
2442 unsafe fn __iterator_get_unchecked(&mut self, i: usize) -> &'a mut [T; N] {
2443 // SAFETY: The safety guarantees of `__iterator_get_unchecked` are transferred to
2445 unsafe { self.iter.__iterator_get_unchecked(i) }
2449 #[unstable(feature = "array_chunks", issue = "74985")]
2450 impl<'a, T, const N: usize> DoubleEndedIterator for ArrayChunksMut<'a, T, N> {
2452 fn next_back(&mut self) -> Option<&'a mut [T; N]> {
2453 self.iter.next_back()
2457 fn nth_back(&mut self, n: usize) -> Option<Self::Item> {
2458 self.iter.nth_back(n)
2462 #[unstable(feature = "array_chunks", issue = "74985")]
2463 impl<T, const N: usize> ExactSizeIterator for ArrayChunksMut<'_, T, N> {
2464 fn is_empty(&self) -> bool {
2465 self.iter.is_empty()
2469 #[unstable(feature = "trusted_len", issue = "37572")]
2470 unsafe impl<T, const N: usize> TrustedLen for ArrayChunksMut<'_, T, N> {}
2472 #[unstable(feature = "array_chunks", issue = "74985")]
2473 impl<T, const N: usize> FusedIterator for ArrayChunksMut<'_, T, N> {}
2476 #[unstable(feature = "array_chunks", issue = "74985")]
2477 unsafe impl<'a, T, const N: usize> TrustedRandomAccess for ArrayChunksMut<'a, T, N> {}
2480 #[unstable(feature = "array_chunks", issue = "74985")]
2481 unsafe impl<'a, T, const N: usize> TrustedRandomAccessNoCoerce for ArrayChunksMut<'a, T, N> {
2482 const MAY_HAVE_SIDE_EFFECT: bool = false;
2485 /// An iterator over a slice in (non-overlapping) chunks (`chunk_size` elements at a
2486 /// time), starting at the end of the slice.
2488 /// When the slice len is not evenly divided by the chunk size, the last slice
2489 /// of the iteration will be the remainder.
2491 /// This struct is created by the [`rchunks`] method on [slices].
2496 /// let slice = ['l', 'o', 'r', 'e', 'm'];
2497 /// let iter = slice.rchunks(2);
2500 /// [`rchunks`]: slice::rchunks
2503 #[stable(feature = "rchunks", since = "1.31.0")]
2504 #[must_use = "iterators are lazy and do nothing unless consumed"]
2505 pub struct RChunks<'a, T: 'a> {
2510 impl<'a, T: 'a> RChunks<'a, T> {
2512 pub(super) fn new(slice: &'a [T], size: usize) -> Self {
2513 Self { v: slice, chunk_size: size }
2517 // FIXME(#26925) Remove in favor of `#[derive(Clone)]`
2518 #[stable(feature = "rchunks", since = "1.31.0")]
2519 impl<T> Clone for RChunks<'_, T> {
2520 fn clone(&self) -> Self {
2521 RChunks { v: self.v, chunk_size: self.chunk_size }
2525 #[stable(feature = "rchunks", since = "1.31.0")]
2526 impl<'a, T> Iterator for RChunks<'a, T> {
2527 type Item = &'a [T];
2530 fn next(&mut self) -> Option<&'a [T]> {
2531 if self.v.is_empty() {
2534 let len = self.v.len();
2535 let chunksz = cmp::min(len, self.chunk_size);
2536 // SAFETY: split_at_unchecked just requires the argument be less
2537 // than the length. This could only happen if the expression `len -
2538 // chunksz` overflows. This could only happen if `chunksz > len`,
2539 // which is impossible as we initialize it as the `min` of `len` and
2540 // `self.chunk_size`.
2541 let (fst, snd) = unsafe { self.v.split_at_unchecked(len - chunksz) };
2548 fn size_hint(&self) -> (usize, Option<usize>) {
2549 if self.v.is_empty() {
2552 let n = self.v.len() / self.chunk_size;
2553 let rem = self.v.len() % self.chunk_size;
2554 let n = if rem > 0 { n + 1 } else { n };
2560 fn count(self) -> usize {
2565 fn nth(&mut self, n: usize) -> Option<Self::Item> {
2566 let (end, overflow) = n.overflowing_mul(self.chunk_size);
2567 if end >= self.v.len() || overflow {
2571 // Can't underflow because of the check above
2572 let end = self.v.len() - end;
2573 let start = match end.checked_sub(self.chunk_size) {
2577 let nth = &self.v[start..end];
2578 self.v = &self.v[0..start];
2584 fn last(self) -> Option<Self::Item> {
2585 if self.v.is_empty() {
2588 let rem = self.v.len() % self.chunk_size;
2589 let end = if rem == 0 { self.chunk_size } else { rem };
2590 Some(&self.v[0..end])
2594 unsafe fn __iterator_get_unchecked(&mut self, idx: usize) -> Self::Item {
2595 let end = self.v.len() - idx * self.chunk_size;
2596 let start = match end.checked_sub(self.chunk_size) {
2598 Some(start) => start,
2600 // SAFETY: mostly identical to `Chunks::__iterator_get_unchecked`.
2601 unsafe { from_raw_parts(self.v.as_ptr().add(start), end - start) }
2605 #[stable(feature = "rchunks", since = "1.31.0")]
2606 impl<'a, T> DoubleEndedIterator for RChunks<'a, T> {
2608 fn next_back(&mut self) -> Option<&'a [T]> {
2609 if self.v.is_empty() {
2612 let remainder = self.v.len() % self.chunk_size;
2613 let chunksz = if remainder != 0 { remainder } else { self.chunk_size };
2614 // SAFETY: similar to Chunks::next_back
2615 let (fst, snd) = unsafe { self.v.split_at_unchecked(chunksz) };
2622 fn nth_back(&mut self, n: usize) -> Option<Self::Item> {
2623 let len = self.len();
2628 // can't underflow because `n < len`
2629 let offset_from_end = (len - 1 - n) * self.chunk_size;
2630 let end = self.v.len() - offset_from_end;
2631 let start = end.saturating_sub(self.chunk_size);
2632 let nth_back = &self.v[start..end];
2633 self.v = &self.v[end..];
2639 #[stable(feature = "rchunks", since = "1.31.0")]
2640 impl<T> ExactSizeIterator for RChunks<'_, T> {}
2642 #[unstable(feature = "trusted_len", issue = "37572")]
2643 unsafe impl<T> TrustedLen for RChunks<'_, T> {}
2645 #[stable(feature = "rchunks", since = "1.31.0")]
2646 impl<T> FusedIterator for RChunks<'_, T> {}
2649 #[unstable(feature = "trusted_random_access", issue = "none")]
2650 unsafe impl<'a, T> TrustedRandomAccess for RChunks<'a, T> {}
2653 #[unstable(feature = "trusted_random_access", issue = "none")]
2654 unsafe impl<'a, T> TrustedRandomAccessNoCoerce for RChunks<'a, T> {
2655 const MAY_HAVE_SIDE_EFFECT: bool = false;
2658 /// An iterator over a slice in (non-overlapping) mutable chunks (`chunk_size`
2659 /// elements at a time), starting at the end of the slice.
2661 /// When the slice len is not evenly divided by the chunk size, the last slice
2662 /// of the iteration will be the remainder.
2664 /// This struct is created by the [`rchunks_mut`] method on [slices].
2669 /// let mut slice = ['l', 'o', 'r', 'e', 'm'];
2670 /// let iter = slice.rchunks_mut(2);
2673 /// [`rchunks_mut`]: slice::rchunks_mut
2676 #[stable(feature = "rchunks", since = "1.31.0")]
2677 #[must_use = "iterators are lazy and do nothing unless consumed"]
2678 pub struct RChunksMut<'a, T: 'a> {
2680 /// This slice pointer must point at a valid region of `T` with at least length `v.len()`. Normally,
2681 /// those requirements would mean that we could instead use a `&mut [T]` here, but we cannot
2682 /// because `__iterator_get_unchecked` needs to return `&mut [T]`, which guarantees certain aliasing
2683 /// properties that we cannot uphold if we hold on to the full original `&mut [T]`. Wrapping a raw
2684 /// slice instead lets us hand out non-overlapping `&mut [T]` subslices of the slice we wrap.
2687 _marker: PhantomData<&'a mut T>,
2690 impl<'a, T: 'a> RChunksMut<'a, T> {
2692 pub(super) fn new(slice: &'a mut [T], size: usize) -> Self {
2693 Self { v: slice, chunk_size: size, _marker: PhantomData }
2697 #[stable(feature = "rchunks", since = "1.31.0")]
2698 impl<'a, T> Iterator for RChunksMut<'a, T> {
2699 type Item = &'a mut [T];
2702 fn next(&mut self) -> Option<&'a mut [T]> {
2703 if self.v.is_empty() {
2706 let sz = cmp::min(self.v.len(), self.chunk_size);
2707 let len = self.v.len();
2708 // SAFETY: split_at_mut_unchecked just requires the argument be less
2709 // than the length. This could only happen if the expression
2710 // `len - sz` overflows. This could only happen if `sz >
2711 // len`, which is impossible as we initialize it as the `min` of
2712 // `self.v.len()` (e.g. `len`) and `self.chunk_size`.
2713 let (head, tail) = unsafe { self.v.split_at_mut_unchecked(len - sz) };
2715 // SAFETY: Nothing else points to or will point to the contents of this slice.
2716 Some(unsafe { &mut *tail })
2721 fn size_hint(&self) -> (usize, Option<usize>) {
2722 if self.v.is_empty() {
2725 let n = self.v.len() / self.chunk_size;
2726 let rem = self.v.len() % self.chunk_size;
2727 let n = if rem > 0 { n + 1 } else { n };
2733 fn count(self) -> usize {
2738 fn nth(&mut self, n: usize) -> Option<&'a mut [T]> {
2739 let (end, overflow) = n.overflowing_mul(self.chunk_size);
2740 if end >= self.v.len() || overflow {
2744 // Can't underflow because of the check above
2745 let end = self.v.len() - end;
2746 let start = match end.checked_sub(self.chunk_size) {
2750 // SAFETY: This type ensures that self.v is a valid pointer with a correct len.
2751 // Therefore the bounds check in split_at_mut guarantees the split point is inbounds.
2752 let (head, tail) = unsafe { self.v.split_at_mut(start) };
2753 // SAFETY: This type ensures that self.v is a valid pointer with a correct len.
2754 // Therefore the bounds check in split_at_mut guarantees the split point is inbounds.
2755 let (nth, _) = unsafe { tail.split_at_mut(end - start) };
2757 // SAFETY: Nothing else points to or will point to the contents of this slice.
2758 Some(unsafe { &mut *nth })
2763 fn last(self) -> Option<Self::Item> {
2764 if self.v.is_empty() {
2767 let rem = self.v.len() % self.chunk_size;
2768 let end = if rem == 0 { self.chunk_size } else { rem };
2769 // SAFETY: Nothing else points to or will point to the contents of this slice.
2770 Some(unsafe { &mut *self.v.get_unchecked_mut(0..end) })
2774 unsafe fn __iterator_get_unchecked(&mut self, idx: usize) -> Self::Item {
2775 let end = self.v.len() - idx * self.chunk_size;
2776 let start = match end.checked_sub(self.chunk_size) {
2778 Some(start) => start,
2780 // SAFETY: see comments for `RChunks::__iterator_get_unchecked` and
2781 // `ChunksMut::__iterator_get_unchecked`, `self.v`.
2782 unsafe { from_raw_parts_mut(self.v.as_mut_ptr().add(start), end - start) }
2786 #[stable(feature = "rchunks", since = "1.31.0")]
2787 impl<'a, T> DoubleEndedIterator for RChunksMut<'a, T> {
2789 fn next_back(&mut self) -> Option<&'a mut [T]> {
2790 if self.v.is_empty() {
2793 let remainder = self.v.len() % self.chunk_size;
2794 let sz = if remainder != 0 { remainder } else { self.chunk_size };
2795 // SAFETY: Similar to `Chunks::next_back`
2796 let (head, tail) = unsafe { self.v.split_at_mut_unchecked(sz) };
2798 // SAFETY: Nothing else points to or will point to the contents of this slice.
2799 Some(unsafe { &mut *head })
2804 fn nth_back(&mut self, n: usize) -> Option<Self::Item> {
2805 let len = self.len();
2810 // can't underflow because `n < len`
2811 let offset_from_end = (len - 1 - n) * self.chunk_size;
2812 let end = self.v.len() - offset_from_end;
2813 let start = end.saturating_sub(self.chunk_size);
2814 // SAFETY: The self.v contract ensures that any split_at_mut is valid.
2815 let (tmp, tail) = unsafe { self.v.split_at_mut(end) };
2816 // SAFETY: The self.v contract ensures that any split_at_mut is valid.
2817 let (_, nth_back) = unsafe { tmp.split_at_mut(start) };
2819 // SAFETY: Nothing else points to or will point to the contents of this slice.
2820 Some(unsafe { &mut *nth_back })
2825 #[stable(feature = "rchunks", since = "1.31.0")]
2826 impl<T> ExactSizeIterator for RChunksMut<'_, T> {}
2828 #[unstable(feature = "trusted_len", issue = "37572")]
2829 unsafe impl<T> TrustedLen for RChunksMut<'_, T> {}
2831 #[stable(feature = "rchunks", since = "1.31.0")]
2832 impl<T> FusedIterator for RChunksMut<'_, T> {}
2835 #[unstable(feature = "trusted_random_access", issue = "none")]
2836 unsafe impl<'a, T> TrustedRandomAccess for RChunksMut<'a, T> {}
2839 #[unstable(feature = "trusted_random_access", issue = "none")]
2840 unsafe impl<'a, T> TrustedRandomAccessNoCoerce for RChunksMut<'a, T> {
2841 const MAY_HAVE_SIDE_EFFECT: bool = false;
2844 #[stable(feature = "rchunks", since = "1.31.0")]
2845 unsafe impl<T> Send for RChunksMut<'_, T> where T: Send {}
2847 #[stable(feature = "rchunks", since = "1.31.0")]
2848 unsafe impl<T> Sync for RChunksMut<'_, T> where T: Sync {}
2850 /// An iterator over a slice in (non-overlapping) chunks (`chunk_size` elements at a
2851 /// time), starting at the end of the slice.
2853 /// When the slice len is not evenly divided by the chunk size, the last
2854 /// up to `chunk_size-1` elements will be omitted but can be retrieved from
2855 /// the [`remainder`] function from the iterator.
2857 /// This struct is created by the [`rchunks_exact`] method on [slices].
2862 /// let slice = ['l', 'o', 'r', 'e', 'm'];
2863 /// let iter = slice.rchunks_exact(2);
2866 /// [`rchunks_exact`]: slice::rchunks_exact
2867 /// [`remainder`]: ChunksExact::remainder
2870 #[stable(feature = "rchunks", since = "1.31.0")]
2871 #[must_use = "iterators are lazy and do nothing unless consumed"]
2872 pub struct RChunksExact<'a, T: 'a> {
2878 impl<'a, T> RChunksExact<'a, T> {
2880 pub(super) fn new(slice: &'a [T], chunk_size: usize) -> Self {
2881 let rem = slice.len() % chunk_size;
2882 // SAFETY: 0 <= rem <= slice.len() by construction above
2883 let (fst, snd) = unsafe { slice.split_at_unchecked(rem) };
2884 Self { v: snd, rem: fst, chunk_size }
2887 /// Returns the remainder of the original slice that is not going to be
2888 /// returned by the iterator. The returned slice has at most `chunk_size-1`
2891 #[stable(feature = "rchunks", since = "1.31.0")]
2892 pub fn remainder(&self) -> &'a [T] {
2897 // FIXME(#26925) Remove in favor of `#[derive(Clone)]`
2898 #[stable(feature = "rchunks", since = "1.31.0")]
2899 impl<'a, T> Clone for RChunksExact<'a, T> {
2900 fn clone(&self) -> RChunksExact<'a, T> {
2901 RChunksExact { v: self.v, rem: self.rem, chunk_size: self.chunk_size }
2905 #[stable(feature = "rchunks", since = "1.31.0")]
2906 impl<'a, T> Iterator for RChunksExact<'a, T> {
2907 type Item = &'a [T];
2910 fn next(&mut self) -> Option<&'a [T]> {
2911 if self.v.len() < self.chunk_size {
2914 let (fst, snd) = self.v.split_at(self.v.len() - self.chunk_size);
2921 fn size_hint(&self) -> (usize, Option<usize>) {
2922 let n = self.v.len() / self.chunk_size;
2927 fn count(self) -> usize {
2932 fn nth(&mut self, n: usize) -> Option<Self::Item> {
2933 let (end, overflow) = n.overflowing_mul(self.chunk_size);
2934 if end >= self.v.len() || overflow {
2938 let (fst, _) = self.v.split_at(self.v.len() - end);
2945 fn last(mut self) -> Option<Self::Item> {
2949 unsafe fn __iterator_get_unchecked(&mut self, idx: usize) -> Self::Item {
2950 let end = self.v.len() - idx * self.chunk_size;
2951 let start = end - self.chunk_size;
2952 // SAFETY: mostly identical to `Chunks::__iterator_get_unchecked`.
2953 unsafe { from_raw_parts(self.v.as_ptr().add(start), self.chunk_size) }
2957 #[stable(feature = "rchunks", since = "1.31.0")]
2958 impl<'a, T> DoubleEndedIterator for RChunksExact<'a, T> {
2960 fn next_back(&mut self) -> Option<&'a [T]> {
2961 if self.v.len() < self.chunk_size {
2964 let (fst, snd) = self.v.split_at(self.chunk_size);
2971 fn nth_back(&mut self, n: usize) -> Option<Self::Item> {
2972 let len = self.len();
2977 // now that we know that `n` corresponds to a chunk,
2978 // none of these operations can underflow/overflow
2979 let offset = (len - n) * self.chunk_size;
2980 let start = self.v.len() - offset;
2981 let end = start + self.chunk_size;
2982 let nth_back = &self.v[start..end];
2983 self.v = &self.v[end..];
2989 #[stable(feature = "rchunks", since = "1.31.0")]
2990 impl<'a, T> ExactSizeIterator for RChunksExact<'a, T> {
2991 fn is_empty(&self) -> bool {
2996 #[unstable(feature = "trusted_len", issue = "37572")]
2997 unsafe impl<T> TrustedLen for RChunksExact<'_, T> {}
2999 #[stable(feature = "rchunks", since = "1.31.0")]
3000 impl<T> FusedIterator for RChunksExact<'_, T> {}
3003 #[unstable(feature = "trusted_random_access", issue = "none")]
3004 unsafe impl<'a, T> TrustedRandomAccess for RChunksExact<'a, T> {}
3007 #[unstable(feature = "trusted_random_access", issue = "none")]
3008 unsafe impl<'a, T> TrustedRandomAccessNoCoerce for RChunksExact<'a, T> {
3009 const MAY_HAVE_SIDE_EFFECT: bool = false;
3012 /// An iterator over a slice in (non-overlapping) mutable chunks (`chunk_size`
3013 /// elements at a time), starting at the end of the slice.
3015 /// When the slice len is not evenly divided by the chunk size, the last up to
3016 /// `chunk_size-1` elements will be omitted but can be retrieved from the
3017 /// [`into_remainder`] function from the iterator.
3019 /// This struct is created by the [`rchunks_exact_mut`] method on [slices].
3024 /// let mut slice = ['l', 'o', 'r', 'e', 'm'];
3025 /// let iter = slice.rchunks_exact_mut(2);
3028 /// [`rchunks_exact_mut`]: slice::rchunks_exact_mut
3029 /// [`into_remainder`]: ChunksExactMut::into_remainder
3032 #[stable(feature = "rchunks", since = "1.31.0")]
3033 #[must_use = "iterators are lazy and do nothing unless consumed"]
3034 pub struct RChunksExactMut<'a, T: 'a> {
3036 /// This slice pointer must point at a valid region of `T` with at least length `v.len()`. Normally,
3037 /// those requirements would mean that we could instead use a `&mut [T]` here, but we cannot
3038 /// because `__iterator_get_unchecked` needs to return `&mut [T]`, which guarantees certain aliasing
3039 /// properties that we cannot uphold if we hold on to the full original `&mut [T]`. Wrapping a raw
3040 /// slice instead lets us hand out non-overlapping `&mut [T]` subslices of the slice we wrap.
3046 impl<'a, T> RChunksExactMut<'a, T> {
3048 pub(super) fn new(slice: &'a mut [T], chunk_size: usize) -> Self {
3049 let rem = slice.len() % chunk_size;
3050 // SAFETY: 0 <= rem <= slice.len() by construction above
3051 let (fst, snd) = unsafe { slice.split_at_mut_unchecked(rem) };
3052 Self { v: snd, rem: fst, chunk_size }
3055 /// Returns the remainder of the original slice that is not going to be
3056 /// returned by the iterator. The returned slice has at most `chunk_size-1`
3058 #[must_use = "`self` will be dropped if the result is not used"]
3059 #[stable(feature = "rchunks", since = "1.31.0")]
3060 pub fn into_remainder(self) -> &'a mut [T] {
3065 #[stable(feature = "rchunks", since = "1.31.0")]
3066 impl<'a, T> Iterator for RChunksExactMut<'a, T> {
3067 type Item = &'a mut [T];
3070 fn next(&mut self) -> Option<&'a mut [T]> {
3071 if self.v.len() < self.chunk_size {
3074 let len = self.v.len();
3075 // SAFETY: The self.v contract ensures that any split_at_mut is valid.
3076 let (head, tail) = unsafe { self.v.split_at_mut(len - self.chunk_size) };
3078 // SAFETY: Nothing else points to or will point to the contents of this slice.
3079 Some(unsafe { &mut *tail })
3084 fn size_hint(&self) -> (usize, Option<usize>) {
3085 let n = self.v.len() / self.chunk_size;
3090 fn count(self) -> usize {
3095 fn nth(&mut self, n: usize) -> Option<&'a mut [T]> {
3096 let (end, overflow) = n.overflowing_mul(self.chunk_size);
3097 if end >= self.v.len() || overflow {
3101 let len = self.v.len();
3102 // SAFETY: The self.v contract ensures that any split_at_mut is valid.
3103 let (fst, _) = unsafe { self.v.split_at_mut(len - end) };
3110 fn last(mut self) -> Option<Self::Item> {
3114 unsafe fn __iterator_get_unchecked(&mut self, idx: usize) -> Self::Item {
3115 let end = self.v.len() - idx * self.chunk_size;
3116 let start = end - self.chunk_size;
3117 // SAFETY: see comments for `RChunksMut::__iterator_get_unchecked` and `self.v`.
3118 unsafe { from_raw_parts_mut(self.v.as_mut_ptr().add(start), self.chunk_size) }
3122 #[stable(feature = "rchunks", since = "1.31.0")]
3123 impl<'a, T> DoubleEndedIterator for RChunksExactMut<'a, T> {
3125 fn next_back(&mut self) -> Option<&'a mut [T]> {
3126 if self.v.len() < self.chunk_size {
3129 // SAFETY: The self.v contract ensures that any split_at_mut is valid.
3130 let (head, tail) = unsafe { self.v.split_at_mut(self.chunk_size) };
3132 // SAFETY: Nothing else points to or will point to the contents of this slice.
3133 Some(unsafe { &mut *head })
3138 fn nth_back(&mut self, n: usize) -> Option<Self::Item> {
3139 let len = self.len();
3144 // now that we know that `n` corresponds to a chunk,
3145 // none of these operations can underflow/overflow
3146 let offset = (len - n) * self.chunk_size;
3147 let start = self.v.len() - offset;
3148 let end = start + self.chunk_size;
3149 // SAFETY: The self.v contract ensures that any split_at_mut is valid.
3150 let (tmp, tail) = unsafe { self.v.split_at_mut(end) };
3151 // SAFETY: The self.v contract ensures that any split_at_mut is valid.
3152 let (_, nth_back) = unsafe { tmp.split_at_mut(start) };
3154 // SAFETY: Nothing else points to or will point to the contents of this slice.
3155 Some(unsafe { &mut *nth_back })
3160 #[stable(feature = "rchunks", since = "1.31.0")]
3161 impl<T> ExactSizeIterator for RChunksExactMut<'_, T> {
3162 fn is_empty(&self) -> bool {
3167 #[unstable(feature = "trusted_len", issue = "37572")]
3168 unsafe impl<T> TrustedLen for RChunksExactMut<'_, T> {}
3170 #[stable(feature = "rchunks", since = "1.31.0")]
3171 impl<T> FusedIterator for RChunksExactMut<'_, T> {}
3174 #[unstable(feature = "trusted_random_access", issue = "none")]
3175 unsafe impl<'a, T> TrustedRandomAccess for RChunksExactMut<'a, T> {}
3178 #[unstable(feature = "trusted_random_access", issue = "none")]
3179 unsafe impl<'a, T> TrustedRandomAccessNoCoerce for RChunksExactMut<'a, T> {
3180 const MAY_HAVE_SIDE_EFFECT: bool = false;
3183 #[stable(feature = "rchunks", since = "1.31.0")]
3184 unsafe impl<T> Send for RChunksExactMut<'_, T> where T: Send {}
3186 #[stable(feature = "rchunks", since = "1.31.0")]
3187 unsafe impl<T> Sync for RChunksExactMut<'_, T> where T: Sync {}
3190 #[unstable(feature = "trusted_random_access", issue = "none")]
3191 unsafe impl<'a, T> TrustedRandomAccess for Iter<'a, T> {}
3194 #[unstable(feature = "trusted_random_access", issue = "none")]
3195 unsafe impl<'a, T> TrustedRandomAccessNoCoerce for Iter<'a, T> {
3196 const MAY_HAVE_SIDE_EFFECT: bool = false;
3200 #[unstable(feature = "trusted_random_access", issue = "none")]
3201 unsafe impl<'a, T> TrustedRandomAccess for IterMut<'a, T> {}
3204 #[unstable(feature = "trusted_random_access", issue = "none")]
3205 unsafe impl<'a, T> TrustedRandomAccessNoCoerce for IterMut<'a, T> {
3206 const MAY_HAVE_SIDE_EFFECT: bool = false;
3209 /// An iterator over slice in (non-overlapping) chunks separated by a predicate.
3211 /// This struct is created by the [`group_by`] method on [slices].
3213 /// [`group_by`]: slice::group_by
3215 #[unstable(feature = "slice_group_by", issue = "80552")]
3216 #[must_use = "iterators are lazy and do nothing unless consumed"]
3217 pub struct GroupBy<'a, T: 'a, P> {
3222 #[unstable(feature = "slice_group_by", issue = "80552")]
3223 impl<'a, T: 'a, P> GroupBy<'a, T, P> {
3224 pub(super) fn new(slice: &'a [T], predicate: P) -> Self {
3225 GroupBy { slice, predicate }
3229 #[unstable(feature = "slice_group_by", issue = "80552")]
3230 impl<'a, T: 'a, P> Iterator for GroupBy<'a, T, P>
3232 P: FnMut(&T, &T) -> bool,
3234 type Item = &'a [T];
3237 fn next(&mut self) -> Option<Self::Item> {
3238 if self.slice.is_empty() {
3242 let mut iter = self.slice.windows(2);
3243 while let Some([l, r]) = iter.next() {
3244 if (self.predicate)(l, r) { len += 1 } else { break }
3246 let (head, tail) = self.slice.split_at(len);
3253 fn size_hint(&self) -> (usize, Option<usize>) {
3254 if self.slice.is_empty() { (0, Some(0)) } else { (1, Some(self.slice.len())) }
3258 fn last(mut self) -> Option<Self::Item> {
3263 #[unstable(feature = "slice_group_by", issue = "80552")]
3264 impl<'a, T: 'a, P> DoubleEndedIterator for GroupBy<'a, T, P>
3266 P: FnMut(&T, &T) -> bool,
3269 fn next_back(&mut self) -> Option<Self::Item> {
3270 if self.slice.is_empty() {
3274 let mut iter = self.slice.windows(2);
3275 while let Some([l, r]) = iter.next_back() {
3276 if (self.predicate)(l, r) { len += 1 } else { break }
3278 let (head, tail) = self.slice.split_at(self.slice.len() - len);
3285 #[unstable(feature = "slice_group_by", issue = "80552")]
3286 impl<'a, T: 'a, P> FusedIterator for GroupBy<'a, T, P> where P: FnMut(&T, &T) -> bool {}
3288 #[unstable(feature = "slice_group_by", issue = "80552")]
3289 impl<'a, T: 'a + fmt::Debug, P> fmt::Debug for GroupBy<'a, T, P> {
3290 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
3291 f.debug_struct("GroupBy").field("slice", &self.slice).finish()
3295 /// An iterator over slice in (non-overlapping) mutable chunks separated
3298 /// This struct is created by the [`group_by_mut`] method on [slices].
3300 /// [`group_by_mut`]: slice::group_by_mut
3302 #[unstable(feature = "slice_group_by", issue = "80552")]
3303 #[must_use = "iterators are lazy and do nothing unless consumed"]
3304 pub struct GroupByMut<'a, T: 'a, P> {
3309 #[unstable(feature = "slice_group_by", issue = "80552")]
3310 impl<'a, T: 'a, P> GroupByMut<'a, T, P> {
3311 pub(super) fn new(slice: &'a mut [T], predicate: P) -> Self {
3312 GroupByMut { slice, predicate }
3316 #[unstable(feature = "slice_group_by", issue = "80552")]
3317 impl<'a, T: 'a, P> Iterator for GroupByMut<'a, T, P>
3319 P: FnMut(&T, &T) -> bool,
3321 type Item = &'a mut [T];
3324 fn next(&mut self) -> Option<Self::Item> {
3325 if self.slice.is_empty() {
3329 let mut iter = self.slice.windows(2);
3330 while let Some([l, r]) = iter.next() {
3331 if (self.predicate)(l, r) { len += 1 } else { break }
3333 let slice = mem::take(&mut self.slice);
3334 let (head, tail) = slice.split_at_mut(len);
3341 fn size_hint(&self) -> (usize, Option<usize>) {
3342 if self.slice.is_empty() { (0, Some(0)) } else { (1, Some(self.slice.len())) }
3346 fn last(mut self) -> Option<Self::Item> {
3351 #[unstable(feature = "slice_group_by", issue = "80552")]
3352 impl<'a, T: 'a, P> DoubleEndedIterator for GroupByMut<'a, T, P>
3354 P: FnMut(&T, &T) -> bool,
3357 fn next_back(&mut self) -> Option<Self::Item> {
3358 if self.slice.is_empty() {
3362 let mut iter = self.slice.windows(2);
3363 while let Some([l, r]) = iter.next_back() {
3364 if (self.predicate)(l, r) { len += 1 } else { break }
3366 let slice = mem::take(&mut self.slice);
3367 let (head, tail) = slice.split_at_mut(slice.len() - len);
3374 #[unstable(feature = "slice_group_by", issue = "80552")]
3375 impl<'a, T: 'a, P> FusedIterator for GroupByMut<'a, T, P> where P: FnMut(&T, &T) -> bool {}
3377 #[unstable(feature = "slice_group_by", issue = "80552")]
3378 impl<'a, T: 'a + fmt::Debug, P> fmt::Debug for GroupByMut<'a, T, P> {
3379 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
3380 f.debug_struct("GroupByMut").field("slice", &self.slice).finish()