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};
11 use crate::marker::{self, Send, Sized, Sync};
13 use crate::ptr::NonNull;
15 use super::{from_raw_parts, from_raw_parts_mut};
17 #[stable(feature = "rust1", since = "1.0.0")]
18 impl<'a, T> IntoIterator for &'a [T] {
20 type IntoIter = Iter<'a, T>;
22 fn into_iter(self) -> Iter<'a, T> {
27 #[stable(feature = "rust1", since = "1.0.0")]
28 impl<'a, T> IntoIterator for &'a mut [T] {
29 type Item = &'a mut T;
30 type IntoIter = IterMut<'a, T>;
32 fn into_iter(self) -> IterMut<'a, T> {
37 // Macro helper functions
39 fn size_from_ptr<T>(_: *const T) -> usize {
43 /// Immutable slice iterator
45 /// This struct is created by the [`iter`] method on [slices].
52 /// // First, we declare a type which has `iter` method to get the `Iter` struct (&[usize here]):
53 /// let slice = &[1, 2, 3];
55 /// // Then, we iterate over it:
56 /// for element in slice.iter() {
57 /// println!("{}", element);
61 /// [`iter`]: ../../std/primitive.slice.html#method.iter
62 /// [slices]: ../../std/primitive.slice.html
63 #[stable(feature = "rust1", since = "1.0.0")]
64 pub struct Iter<'a, T: 'a> {
65 pub(super) ptr: NonNull<T>,
66 pub(super) end: *const T, // If T is a ZST, this is actually ptr+len. This encoding is picked so that
67 // ptr == end is a quick test for the Iterator being empty, that works
68 // for both ZST and non-ZST.
69 pub(super) _marker: marker::PhantomData<&'a T>,
72 #[stable(feature = "core_impl_debug", since = "1.9.0")]
73 impl<T: fmt::Debug> fmt::Debug for Iter<'_, T> {
74 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
75 f.debug_tuple("Iter").field(&self.as_slice()).finish()
79 #[stable(feature = "rust1", since = "1.0.0")]
80 unsafe impl<T: Sync> Sync for Iter<'_, T> {}
81 #[stable(feature = "rust1", since = "1.0.0")]
82 unsafe impl<T: Sync> Send for Iter<'_, T> {}
84 impl<'a, T> Iter<'a, T> {
85 /// Views the underlying data as a subslice of the original data.
87 /// This has the same lifetime as the original slice, and so the
88 /// iterator can continue to be used while this exists.
95 /// // First, we declare a type which has the `iter` method to get the `Iter`
96 /// // struct (&[usize here]):
97 /// let slice = &[1, 2, 3];
99 /// // Then, we get the iterator:
100 /// let mut iter = slice.iter();
101 /// // So if we print what `as_slice` method returns here, we have "[1, 2, 3]":
102 /// println!("{:?}", iter.as_slice());
104 /// // Next, we move to the second element of the slice:
106 /// // Now `as_slice` returns "[2, 3]":
107 /// println!("{:?}", iter.as_slice());
109 #[stable(feature = "iter_to_slice", since = "1.4.0")]
110 pub fn as_slice(&self) -> &'a [T] {
115 iterator! {struct Iter -> *const T, &'a T, const, {/* no mut */}, {
116 fn is_sorted_by<F>(self, mut compare: F) -> bool
119 F: FnMut(&Self::Item, &Self::Item) -> Option<Ordering>,
121 self.as_slice().windows(2).all(|w| {
122 compare(&&w[0], &&w[1]).map(|o| o != Ordering::Greater).unwrap_or(false)
127 #[stable(feature = "rust1", since = "1.0.0")]
128 impl<T> Clone for Iter<'_, T> {
129 fn clone(&self) -> Self {
130 Iter { ptr: self.ptr, end: self.end, _marker: self._marker }
134 #[stable(feature = "slice_iter_as_ref", since = "1.13.0")]
135 impl<T> AsRef<[T]> for Iter<'_, T> {
136 fn as_ref(&self) -> &[T] {
141 /// Mutable slice iterator.
143 /// This struct is created by the [`iter_mut`] method on [slices].
150 /// // First, we declare a type which has `iter_mut` method to get the `IterMut`
151 /// // struct (&[usize here]):
152 /// let mut slice = &mut [1, 2, 3];
154 /// // Then, we iterate over it and increment each element value:
155 /// for element in slice.iter_mut() {
159 /// // We now have "[2, 3, 4]":
160 /// println!("{:?}", slice);
163 /// [`iter_mut`]: ../../std/primitive.slice.html#method.iter_mut
164 /// [slices]: ../../std/primitive.slice.html
165 #[stable(feature = "rust1", since = "1.0.0")]
166 pub struct IterMut<'a, T: 'a> {
167 pub(super) ptr: NonNull<T>,
168 pub(super) end: *mut T, // If T is a ZST, this is actually ptr+len. This encoding is picked so that
169 // ptr == end is a quick test for the Iterator being empty, that works
170 // for both ZST and non-ZST.
171 pub(super) _marker: marker::PhantomData<&'a mut T>,
174 #[stable(feature = "core_impl_debug", since = "1.9.0")]
175 impl<T: fmt::Debug> fmt::Debug for IterMut<'_, T> {
176 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
177 f.debug_tuple("IterMut").field(&self.make_slice()).finish()
181 #[stable(feature = "rust1", since = "1.0.0")]
182 unsafe impl<T: Sync> Sync for IterMut<'_, T> {}
183 #[stable(feature = "rust1", since = "1.0.0")]
184 unsafe impl<T: Send> Send for IterMut<'_, T> {}
186 impl<'a, T> IterMut<'a, T> {
187 /// Views the underlying data as a subslice of the original data.
189 /// To avoid creating `&mut` references that alias, this is forced
190 /// to consume the iterator.
197 /// // First, we declare a type which has `iter_mut` method to get the `IterMut`
198 /// // struct (&[usize here]):
199 /// let mut slice = &mut [1, 2, 3];
202 /// // Then, we get the iterator:
203 /// let mut iter = slice.iter_mut();
204 /// // We move to next element:
206 /// // So if we print what `into_slice` method returns here, we have "[2, 3]":
207 /// println!("{:?}", iter.into_slice());
210 /// // Now let's modify a value of the slice:
212 /// // First we get back the iterator:
213 /// let mut iter = slice.iter_mut();
214 /// // We change the value of the first element of the slice returned by the `next` method:
215 /// *iter.next().unwrap() += 1;
217 /// // Now slice is "[2, 2, 3]":
218 /// println!("{:?}", slice);
220 #[stable(feature = "iter_to_slice", since = "1.4.0")]
221 pub fn into_slice(self) -> &'a mut [T] {
222 // SAFETY: the iterator was created from a mutable slice with pointer
223 // `self.ptr` and length `len!(self)`. This guarantees that all the prerequisites
224 // for `from_raw_parts_mut` are fulfilled.
225 unsafe { from_raw_parts_mut(self.ptr.as_ptr(), len!(self)) }
228 /// Views the underlying data as a subslice of the original data.
230 /// To avoid creating `&mut [T]` references that alias, the returned slice
231 /// borrows its lifetime from the iterator the method is applied on.
238 /// # #![feature(slice_iter_mut_as_slice)]
239 /// let mut slice: &mut [usize] = &mut [1, 2, 3];
241 /// // First, we get the iterator:
242 /// let mut iter = slice.iter_mut();
243 /// // So if we check what the `as_slice` method returns here, we have "[1, 2, 3]":
244 /// assert_eq!(iter.as_slice(), &[1, 2, 3]);
246 /// // Next, we move to the second element of the slice:
248 /// // Now `as_slice` returns "[2, 3]":
249 /// assert_eq!(iter.as_slice(), &[2, 3]);
251 #[unstable(feature = "slice_iter_mut_as_slice", reason = "recently added", issue = "58957")]
252 pub fn as_slice(&self) -> &[T] {
257 iterator! {struct IterMut -> *mut T, &'a mut T, mut, {mut}, {}}
259 /// An internal abstraction over the splitting iterators, so that
260 /// splitn, splitn_mut etc can be implemented once.
262 pub(super) trait SplitIter: DoubleEndedIterator {
263 /// Marks the underlying iterator as complete, extracting the remaining
264 /// portion of the slice.
265 fn finish(&mut self) -> Option<Self::Item>;
268 /// An iterator over subslices separated by elements that match a predicate
271 /// This struct is created by the [`split`] method on [slices].
273 /// [`split`]: ../../std/primitive.slice.html#method.split
274 /// [slices]: ../../std/primitive.slice.html
275 #[stable(feature = "rust1", since = "1.0.0")]
276 pub struct Split<'a, T: 'a, P>
278 P: FnMut(&T) -> bool,
280 pub(super) v: &'a [T],
282 pub(super) finished: bool,
285 #[stable(feature = "core_impl_debug", since = "1.9.0")]
286 impl<T: fmt::Debug, P> fmt::Debug for Split<'_, T, P>
288 P: FnMut(&T) -> bool,
290 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
291 f.debug_struct("Split").field("v", &self.v).field("finished", &self.finished).finish()
295 // FIXME(#26925) Remove in favor of `#[derive(Clone)]`
296 #[stable(feature = "rust1", since = "1.0.0")]
297 impl<T, P> Clone for Split<'_, T, P>
299 P: Clone + FnMut(&T) -> bool,
301 fn clone(&self) -> Self {
302 Split { v: self.v, pred: self.pred.clone(), finished: self.finished }
306 #[stable(feature = "rust1", since = "1.0.0")]
307 impl<'a, T, P> Iterator for Split<'a, T, P>
309 P: FnMut(&T) -> bool,
314 fn next(&mut self) -> Option<&'a [T]> {
319 match self.v.iter().position(|x| (self.pred)(x)) {
320 None => self.finish(),
322 let ret = Some(&self.v[..idx]);
323 self.v = &self.v[idx + 1..];
330 fn size_hint(&self) -> (usize, Option<usize>) {
331 if self.finished { (0, Some(0)) } else { (1, Some(self.v.len() + 1)) }
335 #[stable(feature = "rust1", since = "1.0.0")]
336 impl<'a, T, P> DoubleEndedIterator for Split<'a, T, P>
338 P: FnMut(&T) -> bool,
341 fn next_back(&mut self) -> Option<&'a [T]> {
346 match self.v.iter().rposition(|x| (self.pred)(x)) {
347 None => self.finish(),
349 let ret = Some(&self.v[idx + 1..]);
350 self.v = &self.v[..idx];
357 impl<'a, T, P> SplitIter for Split<'a, T, P>
359 P: FnMut(&T) -> bool,
362 fn finish(&mut self) -> Option<&'a [T]> {
366 self.finished = true;
372 #[stable(feature = "fused", since = "1.26.0")]
373 impl<T, P> FusedIterator for Split<'_, T, P> where P: FnMut(&T) -> bool {}
375 /// An iterator over subslices separated by elements that match a predicate
376 /// function. Unlike `Split`, it contains the matched part as a terminator
379 /// This struct is created by the [`split_inclusive`] method on [slices].
381 /// [`split_inclusive`]: ../../std/primitive.slice.html#method.split_inclusive
382 /// [slices]: ../../std/primitive.slice.html
383 #[unstable(feature = "split_inclusive", issue = "72360")]
384 pub struct SplitInclusive<'a, T: 'a, P>
386 P: FnMut(&T) -> bool,
388 pub(super) v: &'a [T],
390 pub(super) finished: bool,
393 #[unstable(feature = "split_inclusive", issue = "72360")]
394 impl<T: fmt::Debug, P> fmt::Debug for SplitInclusive<'_, T, P>
396 P: FnMut(&T) -> bool,
398 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
399 f.debug_struct("SplitInclusive")
401 .field("finished", &self.finished)
406 // FIXME(#26925) Remove in favor of `#[derive(Clone)]`
407 #[unstable(feature = "split_inclusive", issue = "72360")]
408 impl<T, P> Clone for SplitInclusive<'_, T, P>
410 P: Clone + FnMut(&T) -> bool,
412 fn clone(&self) -> Self {
413 SplitInclusive { v: self.v, pred: self.pred.clone(), finished: self.finished }
417 #[unstable(feature = "split_inclusive", issue = "72360")]
418 impl<'a, T, P> Iterator for SplitInclusive<'a, T, P>
420 P: FnMut(&T) -> bool,
425 fn next(&mut self) -> Option<&'a [T]> {
431 self.v.iter().position(|x| (self.pred)(x)).map(|idx| idx + 1).unwrap_or(self.v.len());
432 if idx == self.v.len() {
433 self.finished = true;
435 let ret = Some(&self.v[..idx]);
436 self.v = &self.v[idx..];
441 fn size_hint(&self) -> (usize, Option<usize>) {
442 if self.finished { (0, Some(0)) } else { (1, Some(self.v.len() + 1)) }
446 #[unstable(feature = "split_inclusive", issue = "72360")]
447 impl<'a, T, P> DoubleEndedIterator for SplitInclusive<'a, T, P>
449 P: FnMut(&T) -> bool,
452 fn next_back(&mut self) -> Option<&'a [T]> {
457 // The last index of self.v is already checked and found to match
458 // by the last iteration, so we start searching a new match
459 // one index to the left.
460 let remainder = if self.v.is_empty() { &[] } else { &self.v[..(self.v.len() - 1)] };
461 let idx = remainder.iter().rposition(|x| (self.pred)(x)).map(|idx| idx + 1).unwrap_or(0);
463 self.finished = true;
465 let ret = Some(&self.v[idx..]);
466 self.v = &self.v[..idx];
471 #[unstable(feature = "split_inclusive", issue = "72360")]
472 impl<T, P> FusedIterator for SplitInclusive<'_, T, P> where P: FnMut(&T) -> bool {}
474 /// An iterator over the mutable subslices of the vector which are separated
475 /// by elements that match `pred`.
477 /// This struct is created by the [`split_mut`] method on [slices].
479 /// [`split_mut`]: ../../std/primitive.slice.html#method.split_mut
480 /// [slices]: ../../std/primitive.slice.html
481 #[stable(feature = "rust1", since = "1.0.0")]
482 pub struct SplitMut<'a, T: 'a, P>
484 P: FnMut(&T) -> bool,
486 pub(super) v: &'a mut [T],
488 pub(super) finished: bool,
491 #[stable(feature = "core_impl_debug", since = "1.9.0")]
492 impl<T: fmt::Debug, P> fmt::Debug for SplitMut<'_, T, P>
494 P: FnMut(&T) -> bool,
496 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
497 f.debug_struct("SplitMut").field("v", &self.v).field("finished", &self.finished).finish()
501 impl<'a, T, P> SplitIter for SplitMut<'a, T, P>
503 P: FnMut(&T) -> bool,
506 fn finish(&mut self) -> Option<&'a mut [T]> {
510 self.finished = true;
511 Some(mem::replace(&mut self.v, &mut []))
516 #[stable(feature = "rust1", since = "1.0.0")]
517 impl<'a, T, P> Iterator for SplitMut<'a, T, P>
519 P: FnMut(&T) -> bool,
521 type Item = &'a mut [T];
524 fn next(&mut self) -> Option<&'a mut [T]> {
530 // work around borrowck limitations
531 let pred = &mut self.pred;
532 self.v.iter().position(|x| (*pred)(x))
535 None => self.finish(),
537 let tmp = mem::replace(&mut self.v, &mut []);
538 let (head, tail) = tmp.split_at_mut(idx);
539 self.v = &mut tail[1..];
546 fn size_hint(&self) -> (usize, Option<usize>) {
550 // if the predicate doesn't match anything, we yield one slice
551 // if it matches every element, we yield len+1 empty slices.
552 (1, Some(self.v.len() + 1))
557 #[stable(feature = "rust1", since = "1.0.0")]
558 impl<'a, T, P> DoubleEndedIterator for SplitMut<'a, T, P>
560 P: FnMut(&T) -> bool,
563 fn next_back(&mut self) -> Option<&'a mut [T]> {
569 // work around borrowck limitations
570 let pred = &mut self.pred;
571 self.v.iter().rposition(|x| (*pred)(x))
574 None => self.finish(),
576 let tmp = mem::replace(&mut self.v, &mut []);
577 let (head, tail) = tmp.split_at_mut(idx);
585 #[stable(feature = "fused", since = "1.26.0")]
586 impl<T, P> FusedIterator for SplitMut<'_, T, P> where P: FnMut(&T) -> bool {}
588 /// An iterator over the mutable subslices of the vector which are separated
589 /// by elements that match `pred`. Unlike `SplitMut`, it contains the matched
590 /// parts in the ends of the subslices.
592 /// This struct is created by the [`split_inclusive_mut`] method on [slices].
594 /// [`split_inclusive_mut`]: ../../std/primitive.slice.html#method.split_inclusive_mut
595 /// [slices]: ../../std/primitive.slice.html
596 #[unstable(feature = "split_inclusive", issue = "72360")]
597 pub struct SplitInclusiveMut<'a, T: 'a, P>
599 P: FnMut(&T) -> bool,
601 pub(super) v: &'a mut [T],
603 pub(super) finished: bool,
606 #[unstable(feature = "split_inclusive", issue = "72360")]
607 impl<T: fmt::Debug, P> fmt::Debug for SplitInclusiveMut<'_, T, P>
609 P: FnMut(&T) -> bool,
611 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
612 f.debug_struct("SplitInclusiveMut")
614 .field("finished", &self.finished)
619 #[unstable(feature = "split_inclusive", issue = "72360")]
620 impl<'a, T, P> Iterator for SplitInclusiveMut<'a, T, P>
622 P: FnMut(&T) -> bool,
624 type Item = &'a mut [T];
627 fn next(&mut self) -> Option<&'a mut [T]> {
633 // work around borrowck limitations
634 let pred = &mut self.pred;
635 self.v.iter().position(|x| (*pred)(x))
637 let idx = idx_opt.map(|idx| idx + 1).unwrap_or(self.v.len());
638 if idx == self.v.len() {
639 self.finished = true;
641 let tmp = mem::replace(&mut self.v, &mut []);
642 let (head, tail) = tmp.split_at_mut(idx);
648 fn size_hint(&self) -> (usize, Option<usize>) {
652 // if the predicate doesn't match anything, we yield one slice
653 // if it matches every element, we yield len+1 empty slices.
654 (1, Some(self.v.len() + 1))
659 #[unstable(feature = "split_inclusive", issue = "72360")]
660 impl<'a, T, P> DoubleEndedIterator for SplitInclusiveMut<'a, T, P>
662 P: FnMut(&T) -> bool,
665 fn next_back(&mut self) -> Option<&'a mut [T]> {
670 let idx_opt = if self.v.is_empty() {
673 // work around borrowck limitations
674 let pred = &mut self.pred;
676 // The last index of self.v is already checked and found to match
677 // by the last iteration, so we start searching a new match
678 // one index to the left.
679 let remainder = &self.v[..(self.v.len() - 1)];
680 remainder.iter().rposition(|x| (*pred)(x))
682 let idx = idx_opt.map(|idx| idx + 1).unwrap_or(0);
684 self.finished = true;
686 let tmp = mem::replace(&mut self.v, &mut []);
687 let (head, tail) = tmp.split_at_mut(idx);
693 #[unstable(feature = "split_inclusive", issue = "72360")]
694 impl<T, P> FusedIterator for SplitInclusiveMut<'_, T, P> where P: FnMut(&T) -> bool {}
696 /// An iterator over subslices separated by elements that match a predicate
697 /// function, starting from the end of the slice.
699 /// This struct is created by the [`rsplit`] method on [slices].
701 /// [`rsplit`]: ../../std/primitive.slice.html#method.rsplit
702 /// [slices]: ../../std/primitive.slice.html
703 #[stable(feature = "slice_rsplit", since = "1.27.0")]
704 #[derive(Clone)] // Is this correct, or does it incorrectly require `T: Clone`?
705 pub struct RSplit<'a, T: 'a, P>
707 P: FnMut(&T) -> bool,
709 pub(super) inner: Split<'a, T, P>,
712 #[stable(feature = "slice_rsplit", since = "1.27.0")]
713 impl<T: fmt::Debug, P> fmt::Debug for RSplit<'_, T, P>
715 P: FnMut(&T) -> bool,
717 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
718 f.debug_struct("RSplit")
719 .field("v", &self.inner.v)
720 .field("finished", &self.inner.finished)
725 #[stable(feature = "slice_rsplit", since = "1.27.0")]
726 impl<'a, T, P> Iterator for RSplit<'a, T, P>
728 P: FnMut(&T) -> bool,
733 fn next(&mut self) -> Option<&'a [T]> {
734 self.inner.next_back()
738 fn size_hint(&self) -> (usize, Option<usize>) {
739 self.inner.size_hint()
743 #[stable(feature = "slice_rsplit", since = "1.27.0")]
744 impl<'a, T, P> DoubleEndedIterator for RSplit<'a, T, P>
746 P: FnMut(&T) -> bool,
749 fn next_back(&mut self) -> Option<&'a [T]> {
754 #[stable(feature = "slice_rsplit", since = "1.27.0")]
755 impl<'a, T, P> SplitIter for RSplit<'a, T, P>
757 P: FnMut(&T) -> bool,
760 fn finish(&mut self) -> Option<&'a [T]> {
765 #[stable(feature = "slice_rsplit", since = "1.27.0")]
766 impl<T, P> FusedIterator for RSplit<'_, T, P> where P: FnMut(&T) -> bool {}
768 /// An iterator over the subslices of the vector which are separated
769 /// by elements that match `pred`, starting from the end of the slice.
771 /// This struct is created by the [`rsplit_mut`] method on [slices].
773 /// [`rsplit_mut`]: ../../std/primitive.slice.html#method.rsplit_mut
774 /// [slices]: ../../std/primitive.slice.html
775 #[stable(feature = "slice_rsplit", since = "1.27.0")]
776 pub struct RSplitMut<'a, T: 'a, P>
778 P: FnMut(&T) -> bool,
780 pub(super) inner: SplitMut<'a, T, P>,
783 #[stable(feature = "slice_rsplit", since = "1.27.0")]
784 impl<T: fmt::Debug, P> fmt::Debug for RSplitMut<'_, T, P>
786 P: FnMut(&T) -> bool,
788 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
789 f.debug_struct("RSplitMut")
790 .field("v", &self.inner.v)
791 .field("finished", &self.inner.finished)
796 #[stable(feature = "slice_rsplit", since = "1.27.0")]
797 impl<'a, T, P> SplitIter for RSplitMut<'a, T, P>
799 P: FnMut(&T) -> bool,
802 fn finish(&mut self) -> Option<&'a mut [T]> {
807 #[stable(feature = "slice_rsplit", since = "1.27.0")]
808 impl<'a, T, P> Iterator for RSplitMut<'a, T, P>
810 P: FnMut(&T) -> bool,
812 type Item = &'a mut [T];
815 fn next(&mut self) -> Option<&'a mut [T]> {
816 self.inner.next_back()
820 fn size_hint(&self) -> (usize, Option<usize>) {
821 self.inner.size_hint()
825 #[stable(feature = "slice_rsplit", since = "1.27.0")]
826 impl<'a, T, P> DoubleEndedIterator for RSplitMut<'a, T, P>
828 P: FnMut(&T) -> bool,
831 fn next_back(&mut self) -> Option<&'a mut [T]> {
836 #[stable(feature = "slice_rsplit", since = "1.27.0")]
837 impl<T, P> FusedIterator for RSplitMut<'_, T, P> where P: FnMut(&T) -> bool {}
839 /// An private iterator over subslices separated by elements that
840 /// match a predicate function, splitting at most a fixed number of
843 pub(super) struct GenericSplitN<I> {
845 pub(super) count: usize,
848 impl<T, I: SplitIter<Item = T>> Iterator for GenericSplitN<I> {
852 fn next(&mut self) -> Option<T> {
867 fn size_hint(&self) -> (usize, Option<usize>) {
868 let (lower, upper_opt) = self.iter.size_hint();
869 (lower, upper_opt.map(|upper| cmp::min(self.count, upper)))
873 /// An iterator over subslices separated by elements that match a predicate
874 /// function, limited to a given number of splits.
876 /// This struct is created by the [`splitn`] method on [slices].
878 /// [`splitn`]: ../../std/primitive.slice.html#method.splitn
879 /// [slices]: ../../std/primitive.slice.html
880 #[stable(feature = "rust1", since = "1.0.0")]
881 pub struct SplitN<'a, T: 'a, P>
883 P: FnMut(&T) -> bool,
885 pub(super) inner: GenericSplitN<Split<'a, T, P>>,
888 #[stable(feature = "core_impl_debug", since = "1.9.0")]
889 impl<T: fmt::Debug, P> fmt::Debug for SplitN<'_, T, P>
891 P: FnMut(&T) -> bool,
893 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
894 f.debug_struct("SplitN").field("inner", &self.inner).finish()
898 /// An iterator over subslices separated by elements that match a
899 /// predicate function, limited to a given number of splits, starting
900 /// from the end of the slice.
902 /// This struct is created by the [`rsplitn`] method on [slices].
904 /// [`rsplitn`]: ../../std/primitive.slice.html#method.rsplitn
905 /// [slices]: ../../std/primitive.slice.html
906 #[stable(feature = "rust1", since = "1.0.0")]
907 pub struct RSplitN<'a, T: 'a, P>
909 P: FnMut(&T) -> bool,
911 pub(super) inner: GenericSplitN<RSplit<'a, T, P>>,
914 #[stable(feature = "core_impl_debug", since = "1.9.0")]
915 impl<T: fmt::Debug, P> fmt::Debug for RSplitN<'_, T, P>
917 P: FnMut(&T) -> bool,
919 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
920 f.debug_struct("RSplitN").field("inner", &self.inner).finish()
924 /// An iterator over subslices separated by elements that match a predicate
925 /// function, limited to a given number of splits.
927 /// This struct is created by the [`splitn_mut`] method on [slices].
929 /// [`splitn_mut`]: ../../std/primitive.slice.html#method.splitn_mut
930 /// [slices]: ../../std/primitive.slice.html
931 #[stable(feature = "rust1", since = "1.0.0")]
932 pub struct SplitNMut<'a, T: 'a, P>
934 P: FnMut(&T) -> bool,
936 pub(super) inner: GenericSplitN<SplitMut<'a, T, P>>,
939 #[stable(feature = "core_impl_debug", since = "1.9.0")]
940 impl<T: fmt::Debug, P> fmt::Debug for SplitNMut<'_, T, P>
942 P: FnMut(&T) -> bool,
944 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
945 f.debug_struct("SplitNMut").field("inner", &self.inner).finish()
949 /// An iterator over subslices separated by elements that match a
950 /// predicate function, limited to a given number of splits, starting
951 /// from the end of the slice.
953 /// This struct is created by the [`rsplitn_mut`] method on [slices].
955 /// [`rsplitn_mut`]: ../../std/primitive.slice.html#method.rsplitn_mut
956 /// [slices]: ../../std/primitive.slice.html
957 #[stable(feature = "rust1", since = "1.0.0")]
958 pub struct RSplitNMut<'a, T: 'a, P>
960 P: FnMut(&T) -> bool,
962 pub(super) inner: GenericSplitN<RSplitMut<'a, T, P>>,
965 #[stable(feature = "core_impl_debug", since = "1.9.0")]
966 impl<T: fmt::Debug, P> fmt::Debug for RSplitNMut<'_, T, P>
968 P: FnMut(&T) -> bool,
970 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
971 f.debug_struct("RSplitNMut").field("inner", &self.inner).finish()
975 forward_iterator! { SplitN: T, &'a [T] }
976 forward_iterator! { RSplitN: T, &'a [T] }
977 forward_iterator! { SplitNMut: T, &'a mut [T] }
978 forward_iterator! { RSplitNMut: T, &'a mut [T] }
980 /// An iterator over overlapping subslices of length `size`.
982 /// This struct is created by the [`windows`] method on [slices].
984 /// [`windows`]: ../../std/primitive.slice.html#method.windows
985 /// [slices]: ../../std/primitive.slice.html
987 #[stable(feature = "rust1", since = "1.0.0")]
988 pub struct Windows<'a, T: 'a> {
989 pub(super) v: &'a [T],
990 pub(super) size: usize,
993 // FIXME(#26925) Remove in favor of `#[derive(Clone)]`
994 #[stable(feature = "rust1", since = "1.0.0")]
995 impl<T> Clone for Windows<'_, T> {
996 fn clone(&self) -> Self {
997 Windows { v: self.v, size: self.size }
1001 #[stable(feature = "rust1", since = "1.0.0")]
1002 impl<'a, T> Iterator for Windows<'a, T> {
1003 type Item = &'a [T];
1006 fn next(&mut self) -> Option<&'a [T]> {
1007 if self.size > self.v.len() {
1010 let ret = Some(&self.v[..self.size]);
1011 self.v = &self.v[1..];
1017 fn size_hint(&self) -> (usize, Option<usize>) {
1018 if self.size > self.v.len() {
1021 let size = self.v.len() - self.size + 1;
1027 fn count(self) -> usize {
1032 fn nth(&mut self, n: usize) -> Option<Self::Item> {
1033 let (end, overflow) = self.size.overflowing_add(n);
1034 if end > self.v.len() || overflow {
1038 let nth = &self.v[n..end];
1039 self.v = &self.v[n + 1..];
1045 fn last(self) -> Option<Self::Item> {
1046 if self.size > self.v.len() {
1049 let start = self.v.len() - self.size;
1050 Some(&self.v[start..])
1055 unsafe fn get_unchecked(&mut self, idx: usize) -> Self::Item {
1056 // SAFETY: since the caller guarantees that `i` is in bounds,
1057 // which means that `i` cannot overflow an `isize`, and the
1058 // slice created by `from_raw_parts` is a subslice of `self.v`
1059 // thus is guaranteed to be valid for the lifetime `'a` of `self.v`.
1060 unsafe { from_raw_parts(self.v.as_ptr().add(idx), self.size) }
1064 #[stable(feature = "rust1", since = "1.0.0")]
1065 impl<'a, T> DoubleEndedIterator for Windows<'a, T> {
1067 fn next_back(&mut self) -> Option<&'a [T]> {
1068 if self.size > self.v.len() {
1071 let ret = Some(&self.v[self.v.len() - self.size..]);
1072 self.v = &self.v[..self.v.len() - 1];
1078 fn nth_back(&mut self, n: usize) -> Option<Self::Item> {
1079 let (end, overflow) = self.v.len().overflowing_sub(n);
1080 if end < self.size || overflow {
1084 let ret = &self.v[end - self.size..end];
1085 self.v = &self.v[..end - 1];
1091 #[stable(feature = "rust1", since = "1.0.0")]
1092 impl<T> ExactSizeIterator for Windows<'_, T> {}
1094 #[unstable(feature = "trusted_len", issue = "37572")]
1095 unsafe impl<T> TrustedLen for Windows<'_, T> {}
1097 #[stable(feature = "fused", since = "1.26.0")]
1098 impl<T> FusedIterator for Windows<'_, T> {}
1101 #[unstable(feature = "trusted_random_access", issue = "none")]
1102 unsafe impl<'a, T> TrustedRandomAccess for Windows<'a, T> {
1103 fn may_have_side_effect() -> bool {
1108 /// An iterator over a slice in (non-overlapping) chunks (`chunk_size` elements at a
1109 /// time), starting at the beginning of the slice.
1111 /// When the slice len is not evenly divided by the chunk size, the last slice
1112 /// of the iteration will be the remainder.
1114 /// This struct is created by the [`chunks`] method on [slices].
1116 /// [`chunks`]: ../../std/primitive.slice.html#method.chunks
1117 /// [slices]: ../../std/primitive.slice.html
1119 #[stable(feature = "rust1", since = "1.0.0")]
1120 pub struct Chunks<'a, T: 'a> {
1121 pub(super) v: &'a [T],
1122 pub(super) chunk_size: usize,
1125 // FIXME(#26925) Remove in favor of `#[derive(Clone)]`
1126 #[stable(feature = "rust1", since = "1.0.0")]
1127 impl<T> Clone for Chunks<'_, T> {
1128 fn clone(&self) -> Self {
1129 Chunks { v: self.v, chunk_size: self.chunk_size }
1133 #[stable(feature = "rust1", since = "1.0.0")]
1134 impl<'a, T> Iterator for Chunks<'a, T> {
1135 type Item = &'a [T];
1138 fn next(&mut self) -> Option<&'a [T]> {
1139 if self.v.is_empty() {
1142 let chunksz = cmp::min(self.v.len(), self.chunk_size);
1143 let (fst, snd) = self.v.split_at(chunksz);
1150 fn size_hint(&self) -> (usize, Option<usize>) {
1151 if self.v.is_empty() {
1154 let n = self.v.len() / self.chunk_size;
1155 let rem = self.v.len() % self.chunk_size;
1156 let n = if rem > 0 { n + 1 } else { n };
1162 fn count(self) -> usize {
1167 fn nth(&mut self, n: usize) -> Option<Self::Item> {
1168 let (start, overflow) = n.overflowing_mul(self.chunk_size);
1169 if start >= self.v.len() || overflow {
1173 let end = match start.checked_add(self.chunk_size) {
1174 Some(sum) => cmp::min(self.v.len(), sum),
1175 None => self.v.len(),
1177 let nth = &self.v[start..end];
1178 self.v = &self.v[end..];
1184 fn last(self) -> Option<Self::Item> {
1185 if self.v.is_empty() {
1188 let start = (self.v.len() - 1) / self.chunk_size * self.chunk_size;
1189 Some(&self.v[start..])
1194 unsafe fn get_unchecked(&mut self, idx: usize) -> Self::Item {
1195 let start = idx * self.chunk_size;
1196 let end = match start.checked_add(self.chunk_size) {
1197 None => self.v.len(),
1198 Some(end) => cmp::min(end, self.v.len()),
1200 // SAFETY: the caller guarantees that `i` is in bounds,
1201 // which means that `start` must be in bounds of the
1202 // underlying `self.v` slice, and we made sure that `end`
1203 // is also in bounds of `self.v`. Thus, `start` cannot overflow
1204 // an `isize`, and the slice constructed by `from_raw_parts`
1205 // is a subslice of `self.v` which is guaranteed to be valid
1206 // for the lifetime `'a` of `self.v`.
1207 unsafe { from_raw_parts(self.v.as_ptr().add(start), end - start) }
1211 #[stable(feature = "rust1", since = "1.0.0")]
1212 impl<'a, T> DoubleEndedIterator for Chunks<'a, T> {
1214 fn next_back(&mut self) -> Option<&'a [T]> {
1215 if self.v.is_empty() {
1218 let remainder = self.v.len() % self.chunk_size;
1219 let chunksz = if remainder != 0 { remainder } else { self.chunk_size };
1220 let (fst, snd) = self.v.split_at(self.v.len() - chunksz);
1227 fn nth_back(&mut self, n: usize) -> Option<Self::Item> {
1228 let len = self.len();
1233 let start = (len - 1 - n) * self.chunk_size;
1234 let end = match start.checked_add(self.chunk_size) {
1235 Some(res) => cmp::min(res, self.v.len()),
1236 None => self.v.len(),
1238 let nth_back = &self.v[start..end];
1239 self.v = &self.v[..start];
1245 #[stable(feature = "rust1", since = "1.0.0")]
1246 impl<T> ExactSizeIterator for Chunks<'_, T> {}
1248 #[unstable(feature = "trusted_len", issue = "37572")]
1249 unsafe impl<T> TrustedLen for Chunks<'_, T> {}
1251 #[stable(feature = "fused", since = "1.26.0")]
1252 impl<T> FusedIterator for Chunks<'_, T> {}
1255 #[unstable(feature = "trusted_random_access", issue = "none")]
1256 unsafe impl<'a, T> TrustedRandomAccess for Chunks<'a, T> {
1257 fn may_have_side_effect() -> bool {
1262 /// An iterator over a slice in (non-overlapping) mutable chunks (`chunk_size`
1263 /// elements at a time), starting at the beginning of the slice.
1265 /// When the slice len is not evenly divided by the chunk size, the last slice
1266 /// of the iteration will be the remainder.
1268 /// This struct is created by the [`chunks_mut`] method on [slices].
1270 /// [`chunks_mut`]: ../../std/primitive.slice.html#method.chunks_mut
1271 /// [slices]: ../../std/primitive.slice.html
1273 #[stable(feature = "rust1", since = "1.0.0")]
1274 pub struct ChunksMut<'a, T: 'a> {
1275 pub(super) v: &'a mut [T],
1276 pub(super) chunk_size: usize,
1279 #[stable(feature = "rust1", since = "1.0.0")]
1280 impl<'a, T> Iterator for ChunksMut<'a, T> {
1281 type Item = &'a mut [T];
1284 fn next(&mut self) -> Option<&'a mut [T]> {
1285 if self.v.is_empty() {
1288 let sz = cmp::min(self.v.len(), self.chunk_size);
1289 let tmp = mem::replace(&mut self.v, &mut []);
1290 let (head, tail) = tmp.split_at_mut(sz);
1297 fn size_hint(&self) -> (usize, Option<usize>) {
1298 if self.v.is_empty() {
1301 let n = self.v.len() / self.chunk_size;
1302 let rem = self.v.len() % self.chunk_size;
1303 let n = if rem > 0 { n + 1 } else { n };
1309 fn count(self) -> usize {
1314 fn nth(&mut self, n: usize) -> Option<&'a mut [T]> {
1315 let (start, overflow) = n.overflowing_mul(self.chunk_size);
1316 if start >= self.v.len() || overflow {
1320 let end = match start.checked_add(self.chunk_size) {
1321 Some(sum) => cmp::min(self.v.len(), sum),
1322 None => self.v.len(),
1324 let tmp = mem::replace(&mut self.v, &mut []);
1325 let (head, tail) = tmp.split_at_mut(end);
1326 let (_, nth) = head.split_at_mut(start);
1333 fn last(self) -> Option<Self::Item> {
1334 if self.v.is_empty() {
1337 let start = (self.v.len() - 1) / self.chunk_size * self.chunk_size;
1338 Some(&mut self.v[start..])
1343 unsafe fn get_unchecked(&mut self, idx: usize) -> Self::Item {
1344 let start = idx * self.chunk_size;
1345 let end = match start.checked_add(self.chunk_size) {
1346 None => self.v.len(),
1347 Some(end) => cmp::min(end, self.v.len()),
1349 // SAFETY: see comments for `Chunks::get_unchecked`.
1351 // Also note that the caller also guarantees that we're never called
1352 // with the same index again, and that no other methods that will
1353 // access this subslice are called, so it is valid for the returned
1354 // slice to be mutable.
1355 unsafe { from_raw_parts_mut(self.v.as_mut_ptr().add(start), end - start) }
1359 #[stable(feature = "rust1", since = "1.0.0")]
1360 impl<'a, T> DoubleEndedIterator for ChunksMut<'a, T> {
1362 fn next_back(&mut self) -> Option<&'a mut [T]> {
1363 if self.v.is_empty() {
1366 let remainder = self.v.len() % self.chunk_size;
1367 let sz = if remainder != 0 { remainder } else { self.chunk_size };
1368 let tmp = mem::replace(&mut self.v, &mut []);
1369 let tmp_len = tmp.len();
1370 let (head, tail) = tmp.split_at_mut(tmp_len - sz);
1377 fn nth_back(&mut self, n: usize) -> Option<Self::Item> {
1378 let len = self.len();
1383 let start = (len - 1 - n) * self.chunk_size;
1384 let end = match start.checked_add(self.chunk_size) {
1385 Some(res) => cmp::min(res, self.v.len()),
1386 None => self.v.len(),
1388 let (temp, _tail) = mem::replace(&mut self.v, &mut []).split_at_mut(end);
1389 let (head, nth_back) = temp.split_at_mut(start);
1396 #[stable(feature = "rust1", since = "1.0.0")]
1397 impl<T> ExactSizeIterator for ChunksMut<'_, T> {}
1399 #[unstable(feature = "trusted_len", issue = "37572")]
1400 unsafe impl<T> TrustedLen for ChunksMut<'_, T> {}
1402 #[stable(feature = "fused", since = "1.26.0")]
1403 impl<T> FusedIterator for ChunksMut<'_, T> {}
1406 #[unstable(feature = "trusted_random_access", issue = "none")]
1407 unsafe impl<'a, T> TrustedRandomAccess for ChunksMut<'a, T> {
1408 fn may_have_side_effect() -> bool {
1413 /// An iterator over a slice in (non-overlapping) chunks (`chunk_size` elements at a
1414 /// time), starting at the beginning of the slice.
1416 /// When the slice len is not evenly divided by the chunk size, the last
1417 /// up to `chunk_size-1` elements will be omitted but can be retrieved from
1418 /// the [`remainder`] function from the iterator.
1420 /// This struct is created by the [`chunks_exact`] method on [slices].
1422 /// [`chunks_exact`]: ../../std/primitive.slice.html#method.chunks_exact
1423 /// [`remainder`]: ChunksExact::remainder
1424 /// [slices]: ../../std/primitive.slice.html
1426 #[stable(feature = "chunks_exact", since = "1.31.0")]
1427 pub struct ChunksExact<'a, T: 'a> {
1428 pub(super) v: &'a [T],
1429 pub(super) rem: &'a [T],
1430 pub(super) chunk_size: usize,
1433 impl<'a, T> ChunksExact<'a, T> {
1434 /// Returns the remainder of the original slice that is not going to be
1435 /// returned by the iterator. The returned slice has at most `chunk_size-1`
1437 #[stable(feature = "chunks_exact", since = "1.31.0")]
1438 pub fn remainder(&self) -> &'a [T] {
1443 // FIXME(#26925) Remove in favor of `#[derive(Clone)]`
1444 #[stable(feature = "chunks_exact", since = "1.31.0")]
1445 impl<T> Clone for ChunksExact<'_, T> {
1446 fn clone(&self) -> Self {
1447 ChunksExact { v: self.v, rem: self.rem, chunk_size: self.chunk_size }
1451 #[stable(feature = "chunks_exact", since = "1.31.0")]
1452 impl<'a, T> Iterator for ChunksExact<'a, T> {
1453 type Item = &'a [T];
1456 fn next(&mut self) -> Option<&'a [T]> {
1457 if self.v.len() < self.chunk_size {
1460 let (fst, snd) = self.v.split_at(self.chunk_size);
1467 fn size_hint(&self) -> (usize, Option<usize>) {
1468 let n = self.v.len() / self.chunk_size;
1473 fn count(self) -> usize {
1478 fn nth(&mut self, n: usize) -> Option<Self::Item> {
1479 let (start, overflow) = n.overflowing_mul(self.chunk_size);
1480 if start >= self.v.len() || overflow {
1484 let (_, snd) = self.v.split_at(start);
1491 fn last(mut self) -> Option<Self::Item> {
1496 unsafe fn get_unchecked(&mut self, idx: usize) -> Self::Item {
1497 let start = idx * self.chunk_size;
1498 // SAFETY: mostly identical to `Chunks::get_unchecked`.
1499 unsafe { from_raw_parts(self.v.as_ptr().add(start), self.chunk_size) }
1503 #[stable(feature = "chunks_exact", since = "1.31.0")]
1504 impl<'a, T> DoubleEndedIterator for ChunksExact<'a, T> {
1506 fn next_back(&mut self) -> Option<&'a [T]> {
1507 if self.v.len() < self.chunk_size {
1510 let (fst, snd) = self.v.split_at(self.v.len() - self.chunk_size);
1517 fn nth_back(&mut self, n: usize) -> Option<Self::Item> {
1518 let len = self.len();
1523 let start = (len - 1 - n) * self.chunk_size;
1524 let end = start + self.chunk_size;
1525 let nth_back = &self.v[start..end];
1526 self.v = &self.v[..start];
1532 #[stable(feature = "chunks_exact", since = "1.31.0")]
1533 impl<T> ExactSizeIterator for ChunksExact<'_, T> {
1534 fn is_empty(&self) -> bool {
1539 #[unstable(feature = "trusted_len", issue = "37572")]
1540 unsafe impl<T> TrustedLen for ChunksExact<'_, T> {}
1542 #[stable(feature = "chunks_exact", since = "1.31.0")]
1543 impl<T> FusedIterator for ChunksExact<'_, T> {}
1546 #[unstable(feature = "trusted_random_access", issue = "none")]
1547 unsafe impl<'a, T> TrustedRandomAccess for ChunksExact<'a, T> {
1548 fn may_have_side_effect() -> bool {
1553 /// An iterator over a slice in (non-overlapping) mutable chunks (`chunk_size`
1554 /// elements at a time), starting at the beginning of the slice.
1556 /// When the slice len is not evenly divided by the chunk size, the last up to
1557 /// `chunk_size-1` elements will be omitted but can be retrieved from the
1558 /// [`into_remainder`] function from the iterator.
1560 /// This struct is created by the [`chunks_exact_mut`] method on [slices].
1562 /// [`chunks_exact_mut`]: ../../std/primitive.slice.html#method.chunks_exact_mut
1563 /// [`into_remainder`]: ChunksExactMut::into_remainder
1564 /// [slices]: ../../std/primitive.slice.html
1566 #[stable(feature = "chunks_exact", since = "1.31.0")]
1567 pub struct ChunksExactMut<'a, T: 'a> {
1568 pub(super) v: &'a mut [T],
1569 pub(super) rem: &'a mut [T],
1570 pub(super) chunk_size: usize,
1573 impl<'a, T> ChunksExactMut<'a, T> {
1574 /// Returns the remainder of the original slice that is not going to be
1575 /// returned by the iterator. The returned slice has at most `chunk_size-1`
1577 #[stable(feature = "chunks_exact", since = "1.31.0")]
1578 pub fn into_remainder(self) -> &'a mut [T] {
1583 #[stable(feature = "chunks_exact", since = "1.31.0")]
1584 impl<'a, T> Iterator for ChunksExactMut<'a, T> {
1585 type Item = &'a mut [T];
1588 fn next(&mut self) -> Option<&'a mut [T]> {
1589 if self.v.len() < self.chunk_size {
1592 let tmp = mem::replace(&mut self.v, &mut []);
1593 let (head, tail) = tmp.split_at_mut(self.chunk_size);
1600 fn size_hint(&self) -> (usize, Option<usize>) {
1601 let n = self.v.len() / self.chunk_size;
1606 fn count(self) -> usize {
1611 fn nth(&mut self, n: usize) -> Option<&'a mut [T]> {
1612 let (start, overflow) = n.overflowing_mul(self.chunk_size);
1613 if start >= self.v.len() || overflow {
1617 let tmp = mem::replace(&mut self.v, &mut []);
1618 let (_, snd) = tmp.split_at_mut(start);
1625 fn last(mut self) -> Option<Self::Item> {
1630 unsafe fn get_unchecked(&mut self, idx: usize) -> Self::Item {
1631 let start = idx * self.chunk_size;
1632 // SAFETY: see comments for `ChunksMut::get_unchecked`.
1633 unsafe { from_raw_parts_mut(self.v.as_mut_ptr().add(start), self.chunk_size) }
1637 #[stable(feature = "chunks_exact", since = "1.31.0")]
1638 impl<'a, T> DoubleEndedIterator for ChunksExactMut<'a, T> {
1640 fn next_back(&mut self) -> Option<&'a mut [T]> {
1641 if self.v.len() < self.chunk_size {
1644 let tmp = mem::replace(&mut self.v, &mut []);
1645 let tmp_len = tmp.len();
1646 let (head, tail) = tmp.split_at_mut(tmp_len - self.chunk_size);
1653 fn nth_back(&mut self, n: usize) -> Option<Self::Item> {
1654 let len = self.len();
1659 let start = (len - 1 - n) * self.chunk_size;
1660 let end = start + self.chunk_size;
1661 let (temp, _tail) = mem::replace(&mut self.v, &mut []).split_at_mut(end);
1662 let (head, nth_back) = temp.split_at_mut(start);
1669 #[stable(feature = "chunks_exact", since = "1.31.0")]
1670 impl<T> ExactSizeIterator for ChunksExactMut<'_, T> {
1671 fn is_empty(&self) -> bool {
1676 #[unstable(feature = "trusted_len", issue = "37572")]
1677 unsafe impl<T> TrustedLen for ChunksExactMut<'_, T> {}
1679 #[stable(feature = "chunks_exact", since = "1.31.0")]
1680 impl<T> FusedIterator for ChunksExactMut<'_, T> {}
1683 #[unstable(feature = "trusted_random_access", issue = "none")]
1684 unsafe impl<'a, T> TrustedRandomAccess for ChunksExactMut<'a, T> {
1685 fn may_have_side_effect() -> bool {
1690 /// A windowed iterator over a slice in overlapping chunks (`N` elements at a
1691 /// time), starting at the beginning of the slice
1693 /// This struct is created by the [`array_windows`] method on [slices].
1695 /// [`array_windows`]: ../../std/primitive.slice.html#method.array_windows
1696 /// [slices]: ../../std/primitive.slice.html
1697 #[derive(Debug, Clone, Copy)]
1698 #[unstable(feature = "array_windows", issue = "75027")]
1699 pub struct ArrayWindows<'a, T: 'a, const N: usize> {
1700 pub(crate) slice_head: *const T,
1701 pub(crate) num: usize,
1702 pub(crate) marker: marker::PhantomData<&'a [T; N]>,
1705 #[unstable(feature = "array_windows", issue = "75027")]
1706 impl<'a, T, const N: usize> Iterator for ArrayWindows<'a, T, N> {
1707 type Item = &'a [T; N];
1710 fn next(&mut self) -> Option<Self::Item> {
1715 // This is safe because it's indexing into a slice guaranteed to be length > N.
1716 let ret = unsafe { &*self.slice_head.cast::<[T; N]>() };
1717 // SAFETY: Guaranteed that there are at least 1 item remaining otherwise
1718 // earlier branch would've been hit
1719 self.slice_head = unsafe { self.slice_head.add(1) };
1726 fn size_hint(&self) -> (usize, Option<usize>) {
1727 (self.num, Some(self.num))
1731 fn count(self) -> usize {
1736 fn nth(&mut self, n: usize) -> Option<Self::Item> {
1742 // This is safe because it's indexing into a slice guaranteed to be length > N.
1743 let ret = unsafe { &*self.slice_head.add(n).cast::<[T; N]>() };
1744 // SAFETY: Guaranteed that there are at least n items remaining
1745 self.slice_head = unsafe { self.slice_head.add(n + 1) };
1752 fn last(mut self) -> Option<Self::Item> {
1753 self.nth(self.num.checked_sub(1)?)
1757 #[unstable(feature = "array_windows", issue = "75027")]
1758 impl<'a, T, const N: usize> DoubleEndedIterator for ArrayWindows<'a, T, N> {
1760 fn next_back(&mut self) -> Option<&'a [T; N]> {
1764 // SAFETY: Guaranteed that there are n items remaining, n-1 for 0-indexing.
1765 let ret = unsafe { &*self.slice_head.add(self.num - 1).cast::<[T; N]>() };
1771 fn nth_back(&mut self, n: usize) -> Option<&'a [T; N]> {
1776 // SAFETY: Guaranteed that there are n items remaining, n-1 for 0-indexing.
1777 let ret = unsafe { &*self.slice_head.add(self.num - (n + 1)).cast::<[T; N]>() };
1783 #[unstable(feature = "array_windows", issue = "75027")]
1784 impl<T, const N: usize> ExactSizeIterator for ArrayWindows<'_, T, N> {
1785 fn is_empty(&self) -> bool {
1790 /// An iterator over a slice in (non-overlapping) chunks (`N` elements at a
1791 /// time), starting at the beginning of the slice.
1793 /// When the slice len is not evenly divided by the chunk size, the last
1794 /// up to `N-1` elements will be omitted but can be retrieved from
1795 /// the [`remainder`] function from the iterator.
1797 /// This struct is created by the [`array_chunks`] method on [slices].
1799 /// [`array_chunks`]: ../../std/primitive.slice.html#method.array_chunks
1800 /// [`remainder`]: ArrayChunks::remainder
1801 /// [slices]: ../../std/primitive.slice.html
1803 #[unstable(feature = "array_chunks", issue = "74985")]
1804 pub struct ArrayChunks<'a, T: 'a, const N: usize> {
1805 pub(super) iter: Iter<'a, [T; N]>,
1806 pub(super) rem: &'a [T],
1809 impl<'a, T, const N: usize> ArrayChunks<'a, T, N> {
1810 /// Returns the remainder of the original slice that is not going to be
1811 /// returned by the iterator. The returned slice has at most `N-1`
1813 #[unstable(feature = "array_chunks", issue = "74985")]
1814 pub fn remainder(&self) -> &'a [T] {
1819 // FIXME(#26925) Remove in favor of `#[derive(Clone)]`
1820 #[unstable(feature = "array_chunks", issue = "74985")]
1821 impl<T, const N: usize> Clone for ArrayChunks<'_, T, N> {
1822 fn clone(&self) -> Self {
1823 ArrayChunks { iter: self.iter.clone(), rem: self.rem }
1827 #[unstable(feature = "array_chunks", issue = "74985")]
1828 impl<'a, T, const N: usize> Iterator for ArrayChunks<'a, T, N> {
1829 type Item = &'a [T; N];
1832 fn next(&mut self) -> Option<&'a [T; N]> {
1837 fn size_hint(&self) -> (usize, Option<usize>) {
1838 self.iter.size_hint()
1842 fn count(self) -> usize {
1847 fn nth(&mut self, n: usize) -> Option<Self::Item> {
1852 fn last(self) -> Option<Self::Item> {
1856 unsafe fn get_unchecked(&mut self, i: usize) -> &'a [T; N] {
1857 // SAFETY: The safety guarantees of `get_unchecked` are transferred to
1859 unsafe { self.iter.get_unchecked(i) }
1863 #[unstable(feature = "array_chunks", issue = "74985")]
1864 impl<'a, T, const N: usize> DoubleEndedIterator for ArrayChunks<'a, T, N> {
1866 fn next_back(&mut self) -> Option<&'a [T; N]> {
1867 self.iter.next_back()
1871 fn nth_back(&mut self, n: usize) -> Option<Self::Item> {
1872 self.iter.nth_back(n)
1876 #[unstable(feature = "array_chunks", issue = "74985")]
1877 impl<T, const N: usize> ExactSizeIterator for ArrayChunks<'_, T, N> {
1878 fn is_empty(&self) -> bool {
1879 self.iter.is_empty()
1883 #[unstable(feature = "trusted_len", issue = "37572")]
1884 unsafe impl<T, const N: usize> TrustedLen for ArrayChunks<'_, T, N> {}
1886 #[unstable(feature = "array_chunks", issue = "74985")]
1887 impl<T, const N: usize> FusedIterator for ArrayChunks<'_, T, N> {}
1890 #[unstable(feature = "array_chunks", issue = "74985")]
1891 unsafe impl<'a, T, const N: usize> TrustedRandomAccess for ArrayChunks<'a, T, N> {
1892 fn may_have_side_effect() -> bool {
1897 /// An iterator over a slice in (non-overlapping) mutable chunks (`N` elements
1898 /// at a time), starting at the beginning of the slice.
1900 /// When the slice len is not evenly divided by the chunk size, the last
1901 /// up to `N-1` elements will be omitted but can be retrieved from
1902 /// the [`into_remainder`] function from the iterator.
1904 /// This struct is created by the [`array_chunks_mut`] method on [slices].
1906 /// [`array_chunks_mut`]: ../../std/primitive.slice.html#method.array_chunks_mut
1907 /// [`into_remainder`]: ../../std/slice/struct.ArrayChunksMut.html#method.into_remainder
1908 /// [slices]: ../../std/primitive.slice.html
1910 #[unstable(feature = "array_chunks", issue = "74985")]
1911 pub struct ArrayChunksMut<'a, T: 'a, const N: usize> {
1912 pub(super) iter: IterMut<'a, [T; N]>,
1913 pub(super) rem: &'a mut [T],
1916 impl<'a, T, const N: usize> ArrayChunksMut<'a, T, N> {
1917 /// Returns the remainder of the original slice that is not going to be
1918 /// returned by the iterator. The returned slice has at most `N-1`
1920 #[unstable(feature = "array_chunks", issue = "74985")]
1921 pub fn into_remainder(self) -> &'a mut [T] {
1926 #[unstable(feature = "array_chunks", issue = "74985")]
1927 impl<'a, T, const N: usize> Iterator for ArrayChunksMut<'a, T, N> {
1928 type Item = &'a mut [T; N];
1931 fn next(&mut self) -> Option<&'a mut [T; N]> {
1936 fn size_hint(&self) -> (usize, Option<usize>) {
1937 self.iter.size_hint()
1941 fn count(self) -> usize {
1946 fn nth(&mut self, n: usize) -> Option<Self::Item> {
1951 fn last(self) -> Option<Self::Item> {
1955 unsafe fn get_unchecked(&mut self, i: usize) -> &'a mut [T; N] {
1956 // SAFETY: The safety guarantees of `get_unchecked` are transferred to
1958 unsafe { self.iter.get_unchecked(i) }
1962 #[unstable(feature = "array_chunks", issue = "74985")]
1963 impl<'a, T, const N: usize> DoubleEndedIterator for ArrayChunksMut<'a, T, N> {
1965 fn next_back(&mut self) -> Option<&'a mut [T; N]> {
1966 self.iter.next_back()
1970 fn nth_back(&mut self, n: usize) -> Option<Self::Item> {
1971 self.iter.nth_back(n)
1975 #[unstable(feature = "array_chunks", issue = "74985")]
1976 impl<T, const N: usize> ExactSizeIterator for ArrayChunksMut<'_, T, N> {
1977 fn is_empty(&self) -> bool {
1978 self.iter.is_empty()
1982 #[unstable(feature = "trusted_len", issue = "37572")]
1983 unsafe impl<T, const N: usize> TrustedLen for ArrayChunksMut<'_, T, N> {}
1985 #[unstable(feature = "array_chunks", issue = "74985")]
1986 impl<T, const N: usize> FusedIterator for ArrayChunksMut<'_, T, N> {}
1989 #[unstable(feature = "array_chunks", issue = "74985")]
1990 unsafe impl<'a, T, const N: usize> TrustedRandomAccess for ArrayChunksMut<'a, T, N> {
1991 fn may_have_side_effect() -> bool {
1996 /// An iterator over a slice in (non-overlapping) chunks (`chunk_size` elements at a
1997 /// time), starting at the end of the slice.
1999 /// When the slice len is not evenly divided by the chunk size, the last slice
2000 /// of the iteration will be the remainder.
2002 /// This struct is created by the [`rchunks`] method on [slices].
2004 /// [`rchunks`]: ../../std/primitive.slice.html#method.rchunks
2005 /// [slices]: ../../std/primitive.slice.html
2007 #[stable(feature = "rchunks", since = "1.31.0")]
2008 pub struct RChunks<'a, T: 'a> {
2009 pub(super) v: &'a [T],
2010 pub(super) chunk_size: usize,
2013 // FIXME(#26925) Remove in favor of `#[derive(Clone)]`
2014 #[stable(feature = "rchunks", since = "1.31.0")]
2015 impl<T> Clone for RChunks<'_, T> {
2016 fn clone(&self) -> Self {
2017 RChunks { v: self.v, chunk_size: self.chunk_size }
2021 #[stable(feature = "rchunks", since = "1.31.0")]
2022 impl<'a, T> Iterator for RChunks<'a, T> {
2023 type Item = &'a [T];
2026 fn next(&mut self) -> Option<&'a [T]> {
2027 if self.v.is_empty() {
2030 let chunksz = cmp::min(self.v.len(), self.chunk_size);
2031 let (fst, snd) = self.v.split_at(self.v.len() - chunksz);
2038 fn size_hint(&self) -> (usize, Option<usize>) {
2039 if self.v.is_empty() {
2042 let n = self.v.len() / self.chunk_size;
2043 let rem = self.v.len() % self.chunk_size;
2044 let n = if rem > 0 { n + 1 } else { n };
2050 fn count(self) -> usize {
2055 fn nth(&mut self, n: usize) -> Option<Self::Item> {
2056 let (end, overflow) = n.overflowing_mul(self.chunk_size);
2057 if end >= self.v.len() || overflow {
2061 // Can't underflow because of the check above
2062 let end = self.v.len() - end;
2063 let start = match end.checked_sub(self.chunk_size) {
2067 let nth = &self.v[start..end];
2068 self.v = &self.v[0..start];
2074 fn last(self) -> Option<Self::Item> {
2075 if self.v.is_empty() {
2078 let rem = self.v.len() % self.chunk_size;
2079 let end = if rem == 0 { self.chunk_size } else { rem };
2080 Some(&self.v[0..end])
2085 unsafe fn get_unchecked(&mut self, idx: usize) -> Self::Item {
2086 let end = self.v.len() - idx * self.chunk_size;
2087 let start = match end.checked_sub(self.chunk_size) {
2089 Some(start) => start,
2091 // SAFETY: mostly identical to `Chunks::get_unchecked`.
2092 unsafe { from_raw_parts(self.v.as_ptr().add(start), end - start) }
2096 #[stable(feature = "rchunks", since = "1.31.0")]
2097 impl<'a, T> DoubleEndedIterator for RChunks<'a, T> {
2099 fn next_back(&mut self) -> Option<&'a [T]> {
2100 if self.v.is_empty() {
2103 let remainder = self.v.len() % self.chunk_size;
2104 let chunksz = if remainder != 0 { remainder } else { self.chunk_size };
2105 let (fst, snd) = self.v.split_at(chunksz);
2112 fn nth_back(&mut self, n: usize) -> Option<Self::Item> {
2113 let len = self.len();
2118 // can't underflow because `n < len`
2119 let offset_from_end = (len - 1 - n) * self.chunk_size;
2120 let end = self.v.len() - offset_from_end;
2121 let start = end.saturating_sub(self.chunk_size);
2122 let nth_back = &self.v[start..end];
2123 self.v = &self.v[end..];
2129 #[stable(feature = "rchunks", since = "1.31.0")]
2130 impl<T> ExactSizeIterator for RChunks<'_, T> {}
2132 #[unstable(feature = "trusted_len", issue = "37572")]
2133 unsafe impl<T> TrustedLen for RChunks<'_, T> {}
2135 #[stable(feature = "rchunks", since = "1.31.0")]
2136 impl<T> FusedIterator for RChunks<'_, T> {}
2139 #[unstable(feature = "trusted_random_access", issue = "none")]
2140 unsafe impl<'a, T> TrustedRandomAccess for RChunks<'a, T> {
2141 fn may_have_side_effect() -> bool {
2146 /// An iterator over a slice in (non-overlapping) mutable chunks (`chunk_size`
2147 /// elements at a time), starting at the end of the slice.
2149 /// When the slice len is not evenly divided by the chunk size, the last slice
2150 /// of the iteration will be the remainder.
2152 /// This struct is created by the [`rchunks_mut`] method on [slices].
2154 /// [`rchunks_mut`]: ../../std/primitive.slice.html#method.rchunks_mut
2155 /// [slices]: ../../std/primitive.slice.html
2157 #[stable(feature = "rchunks", since = "1.31.0")]
2158 pub struct RChunksMut<'a, T: 'a> {
2159 pub(super) v: &'a mut [T],
2160 pub(super) chunk_size: usize,
2163 #[stable(feature = "rchunks", since = "1.31.0")]
2164 impl<'a, T> Iterator for RChunksMut<'a, T> {
2165 type Item = &'a mut [T];
2168 fn next(&mut self) -> Option<&'a mut [T]> {
2169 if self.v.is_empty() {
2172 let sz = cmp::min(self.v.len(), self.chunk_size);
2173 let tmp = mem::replace(&mut self.v, &mut []);
2174 let tmp_len = tmp.len();
2175 let (head, tail) = tmp.split_at_mut(tmp_len - sz);
2182 fn size_hint(&self) -> (usize, Option<usize>) {
2183 if self.v.is_empty() {
2186 let n = self.v.len() / self.chunk_size;
2187 let rem = self.v.len() % self.chunk_size;
2188 let n = if rem > 0 { n + 1 } else { n };
2194 fn count(self) -> usize {
2199 fn nth(&mut self, n: usize) -> Option<&'a mut [T]> {
2200 let (end, overflow) = n.overflowing_mul(self.chunk_size);
2201 if end >= self.v.len() || overflow {
2205 // Can't underflow because of the check above
2206 let end = self.v.len() - end;
2207 let start = match end.checked_sub(self.chunk_size) {
2211 let tmp = mem::replace(&mut self.v, &mut []);
2212 let (head, tail) = tmp.split_at_mut(start);
2213 let (nth, _) = tail.split_at_mut(end - start);
2220 fn last(self) -> Option<Self::Item> {
2221 if self.v.is_empty() {
2224 let rem = self.v.len() % self.chunk_size;
2225 let end = if rem == 0 { self.chunk_size } else { rem };
2226 Some(&mut self.v[0..end])
2231 unsafe fn get_unchecked(&mut self, idx: usize) -> Self::Item {
2232 let end = self.v.len() - idx * self.chunk_size;
2233 let start = match end.checked_sub(self.chunk_size) {
2235 Some(start) => start,
2237 // SAFETY: see comments for `RChunks::get_unchecked` and `ChunksMut::get_unchecked`
2238 unsafe { from_raw_parts_mut(self.v.as_mut_ptr().add(start), end - start) }
2242 #[stable(feature = "rchunks", since = "1.31.0")]
2243 impl<'a, T> DoubleEndedIterator for RChunksMut<'a, T> {
2245 fn next_back(&mut self) -> Option<&'a mut [T]> {
2246 if self.v.is_empty() {
2249 let remainder = self.v.len() % self.chunk_size;
2250 let sz = if remainder != 0 { remainder } else { self.chunk_size };
2251 let tmp = mem::replace(&mut self.v, &mut []);
2252 let (head, tail) = tmp.split_at_mut(sz);
2259 fn nth_back(&mut self, n: usize) -> Option<Self::Item> {
2260 let len = self.len();
2265 // can't underflow because `n < len`
2266 let offset_from_end = (len - 1 - n) * self.chunk_size;
2267 let end = self.v.len() - offset_from_end;
2268 let start = end.saturating_sub(self.chunk_size);
2269 let (tmp, tail) = mem::replace(&mut self.v, &mut []).split_at_mut(end);
2270 let (_, nth_back) = tmp.split_at_mut(start);
2277 #[stable(feature = "rchunks", since = "1.31.0")]
2278 impl<T> ExactSizeIterator for RChunksMut<'_, T> {}
2280 #[unstable(feature = "trusted_len", issue = "37572")]
2281 unsafe impl<T> TrustedLen for RChunksMut<'_, T> {}
2283 #[stable(feature = "rchunks", since = "1.31.0")]
2284 impl<T> FusedIterator for RChunksMut<'_, T> {}
2287 #[unstable(feature = "trusted_random_access", issue = "none")]
2288 unsafe impl<'a, T> TrustedRandomAccess for RChunksMut<'a, T> {
2289 fn may_have_side_effect() -> bool {
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
2298 /// up to `chunk_size-1` elements will be omitted but can be retrieved from
2299 /// the [`remainder`] function from the iterator.
2301 /// This struct is created by the [`rchunks_exact`] method on [slices].
2303 /// [`rchunks_exact`]: ../../std/primitive.slice.html#method.rchunks_exact
2304 /// [`remainder`]: ChunksExact::remainder
2305 /// [slices]: ../../std/primitive.slice.html
2307 #[stable(feature = "rchunks", since = "1.31.0")]
2308 pub struct RChunksExact<'a, T: 'a> {
2309 pub(super) v: &'a [T],
2310 pub(super) rem: &'a [T],
2311 pub(super) chunk_size: usize,
2314 impl<'a, T> RChunksExact<'a, T> {
2315 /// Returns the remainder of the original slice that is not going to be
2316 /// returned by the iterator. The returned slice has at most `chunk_size-1`
2318 #[stable(feature = "rchunks", since = "1.31.0")]
2319 pub fn remainder(&self) -> &'a [T] {
2324 // FIXME(#26925) Remove in favor of `#[derive(Clone)]`
2325 #[stable(feature = "rchunks", since = "1.31.0")]
2326 impl<'a, T> Clone for RChunksExact<'a, T> {
2327 fn clone(&self) -> RChunksExact<'a, T> {
2328 RChunksExact { v: self.v, rem: self.rem, chunk_size: self.chunk_size }
2332 #[stable(feature = "rchunks", since = "1.31.0")]
2333 impl<'a, T> Iterator for RChunksExact<'a, T> {
2334 type Item = &'a [T];
2337 fn next(&mut self) -> Option<&'a [T]> {
2338 if self.v.len() < self.chunk_size {
2341 let (fst, snd) = self.v.split_at(self.v.len() - self.chunk_size);
2348 fn size_hint(&self) -> (usize, Option<usize>) {
2349 let n = self.v.len() / self.chunk_size;
2354 fn count(self) -> usize {
2359 fn nth(&mut self, n: usize) -> Option<Self::Item> {
2360 let (end, overflow) = n.overflowing_mul(self.chunk_size);
2361 if end >= self.v.len() || overflow {
2365 let (fst, _) = self.v.split_at(self.v.len() - end);
2372 fn last(mut self) -> Option<Self::Item> {
2377 unsafe fn get_unchecked(&mut self, idx: usize) -> Self::Item {
2378 let end = self.v.len() - idx * self.chunk_size;
2379 let start = end - self.chunk_size;
2381 // SAFETY: mostmy identical to `Chunks::get_unchecked`.
2382 unsafe { from_raw_parts(self.v.as_ptr().add(start), self.chunk_size) }
2386 #[stable(feature = "rchunks", since = "1.31.0")]
2387 impl<'a, T> DoubleEndedIterator for RChunksExact<'a, T> {
2389 fn next_back(&mut self) -> Option<&'a [T]> {
2390 if self.v.len() < self.chunk_size {
2393 let (fst, snd) = self.v.split_at(self.chunk_size);
2400 fn nth_back(&mut self, n: usize) -> Option<Self::Item> {
2401 let len = self.len();
2406 // now that we know that `n` corresponds to a chunk,
2407 // none of these operations can underflow/overflow
2408 let offset = (len - n) * self.chunk_size;
2409 let start = self.v.len() - offset;
2410 let end = start + self.chunk_size;
2411 let nth_back = &self.v[start..end];
2412 self.v = &self.v[end..];
2418 #[stable(feature = "rchunks", since = "1.31.0")]
2419 impl<'a, T> ExactSizeIterator for RChunksExact<'a, T> {
2420 fn is_empty(&self) -> bool {
2425 #[unstable(feature = "trusted_len", issue = "37572")]
2426 unsafe impl<T> TrustedLen for RChunksExact<'_, T> {}
2428 #[stable(feature = "rchunks", since = "1.31.0")]
2429 impl<T> FusedIterator for RChunksExact<'_, T> {}
2432 #[unstable(feature = "trusted_random_access", issue = "none")]
2433 unsafe impl<'a, T> TrustedRandomAccess for RChunksExact<'a, T> {
2434 fn may_have_side_effect() -> bool {
2439 /// An iterator over a slice in (non-overlapping) mutable chunks (`chunk_size`
2440 /// elements at a time), starting at the end of the slice.
2442 /// When the slice len is not evenly divided by the chunk size, the last up to
2443 /// `chunk_size-1` elements will be omitted but can be retrieved from the
2444 /// [`into_remainder`] function from the iterator.
2446 /// This struct is created by the [`rchunks_exact_mut`] method on [slices].
2448 /// [`rchunks_exact_mut`]: ../../std/primitive.slice.html#method.rchunks_exact_mut
2449 /// [`into_remainder`]: ChunksExactMut::into_remainder
2450 /// [slices]: ../../std/primitive.slice.html
2452 #[stable(feature = "rchunks", since = "1.31.0")]
2453 pub struct RChunksExactMut<'a, T: 'a> {
2454 pub(super) v: &'a mut [T],
2455 pub(super) rem: &'a mut [T],
2456 pub(super) chunk_size: usize,
2459 impl<'a, T> RChunksExactMut<'a, T> {
2460 /// Returns the remainder of the original slice that is not going to be
2461 /// returned by the iterator. The returned slice has at most `chunk_size-1`
2463 #[stable(feature = "rchunks", since = "1.31.0")]
2464 pub fn into_remainder(self) -> &'a mut [T] {
2469 #[stable(feature = "rchunks", since = "1.31.0")]
2470 impl<'a, T> Iterator for RChunksExactMut<'a, T> {
2471 type Item = &'a mut [T];
2474 fn next(&mut self) -> Option<&'a mut [T]> {
2475 if self.v.len() < self.chunk_size {
2478 let tmp = mem::replace(&mut self.v, &mut []);
2479 let tmp_len = tmp.len();
2480 let (head, tail) = tmp.split_at_mut(tmp_len - self.chunk_size);
2487 fn size_hint(&self) -> (usize, Option<usize>) {
2488 let n = self.v.len() / self.chunk_size;
2493 fn count(self) -> usize {
2498 fn nth(&mut self, n: usize) -> Option<&'a mut [T]> {
2499 let (end, overflow) = n.overflowing_mul(self.chunk_size);
2500 if end >= self.v.len() || overflow {
2504 let tmp = mem::replace(&mut self.v, &mut []);
2505 let tmp_len = tmp.len();
2506 let (fst, _) = tmp.split_at_mut(tmp_len - end);
2513 fn last(mut self) -> Option<Self::Item> {
2518 unsafe fn get_unchecked(&mut self, idx: usize) -> Self::Item {
2519 let end = self.v.len() - idx * self.chunk_size;
2520 let start = end - self.chunk_size;
2521 // SAFETY: see comments for `RChunksMut::get_unchecked`.
2522 unsafe { from_raw_parts_mut(self.v.as_mut_ptr().add(start), self.chunk_size) }
2526 #[stable(feature = "rchunks", since = "1.31.0")]
2527 impl<'a, T> DoubleEndedIterator for RChunksExactMut<'a, T> {
2529 fn next_back(&mut self) -> Option<&'a mut [T]> {
2530 if self.v.len() < self.chunk_size {
2533 let tmp = mem::replace(&mut self.v, &mut []);
2534 let (head, tail) = tmp.split_at_mut(self.chunk_size);
2541 fn nth_back(&mut self, n: usize) -> Option<Self::Item> {
2542 let len = self.len();
2547 // now that we know that `n` corresponds to a chunk,
2548 // none of these operations can underflow/overflow
2549 let offset = (len - n) * self.chunk_size;
2550 let start = self.v.len() - offset;
2551 let end = start + self.chunk_size;
2552 let (tmp, tail) = mem::replace(&mut self.v, &mut []).split_at_mut(end);
2553 let (_, nth_back) = tmp.split_at_mut(start);
2560 #[stable(feature = "rchunks", since = "1.31.0")]
2561 impl<T> ExactSizeIterator for RChunksExactMut<'_, T> {
2562 fn is_empty(&self) -> bool {
2567 #[unstable(feature = "trusted_len", issue = "37572")]
2568 unsafe impl<T> TrustedLen for RChunksExactMut<'_, T> {}
2570 #[stable(feature = "rchunks", since = "1.31.0")]
2571 impl<T> FusedIterator for RChunksExactMut<'_, T> {}
2574 #[unstable(feature = "trusted_random_access", issue = "none")]
2575 unsafe impl<'a, T> TrustedRandomAccess for RChunksExactMut<'a, T> {
2576 fn may_have_side_effect() -> bool {
2582 #[unstable(feature = "trusted_random_access", issue = "none")]
2583 unsafe impl<'a, T> TrustedRandomAccess for Iter<'a, T> {
2584 fn may_have_side_effect() -> bool {
2590 #[unstable(feature = "trusted_random_access", issue = "none")]
2591 unsafe impl<'a, T> TrustedRandomAccess for IterMut<'a, T> {
2592 fn may_have_side_effect() -> bool {