1 // ignore-tidy-filelength
2 //! Definitions of a bunch of iterators for `[T]`.
4 #[macro_use] // import iterator! and forward_iterator!
8 use crate::cmp
::Ordering
;
10 use crate::intrinsics
::{assume, exact_div, unchecked_sub}
;
11 use crate::iter
::{FusedIterator, TrustedLen, TrustedRandomAccess}
;
12 use crate::marker
::{PhantomData, Send, Sized, Sync}
;
14 use crate::num
::NonZeroUsize
;
15 use crate::ptr
::NonNull
;
17 use super::{from_raw_parts, from_raw_parts_mut}
;
19 #[stable(feature = "rust1", since = "1.0.0")]
20 impl<'a
, T
> IntoIterator
for &'a
[T
] {
22 type IntoIter
= Iter
<'a
, T
>;
24 fn into_iter(self) -> Iter
<'a
, T
> {
29 #[stable(feature = "rust1", since = "1.0.0")]
30 impl<'a
, T
> IntoIterator
for &'a
mut [T
] {
31 type Item
= &'a
mut T
;
32 type IntoIter
= IterMut
<'a
, T
>;
34 fn into_iter(self) -> IterMut
<'a
, T
> {
39 // Macro helper functions
41 fn size_from_ptr
<T
>(_
: *const T
) -> usize {
45 /// Immutable slice iterator
47 /// This struct is created by the [`iter`] method on [slices].
54 /// // First, we declare a type which has `iter` method to get the `Iter` struct (`&[usize]` here):
55 /// let slice = &[1, 2, 3];
57 /// // Then, we iterate over it:
58 /// for element in slice.iter() {
59 /// println!("{}", element);
63 /// [`iter`]: slice::iter
65 #[stable(feature = "rust1", since = "1.0.0")]
66 pub struct Iter
<'a
, T
: 'a
> {
68 end
: *const T
, // If T is a ZST, this is actually ptr+len. This encoding is picked so that
69 // ptr == end is a quick test for the Iterator being empty, that works
70 // for both ZST and non-ZST.
71 _marker
: PhantomData
<&'a T
>,
74 #[stable(feature = "core_impl_debug", since = "1.9.0")]
75 impl<T
: fmt
::Debug
> fmt
::Debug
for Iter
<'_
, T
> {
76 fn fmt(&self, f
: &mut fmt
::Formatter
<'_
>) -> fmt
::Result
{
77 f
.debug_tuple("Iter").field(&self.as_slice()).finish()
81 #[stable(feature = "rust1", since = "1.0.0")]
82 unsafe impl<T
: Sync
> Sync
for Iter
<'_
, T
> {}
83 #[stable(feature = "rust1", since = "1.0.0")]
84 unsafe impl<T
: Sync
> Send
for Iter
<'_
, T
> {}
86 impl<'a
, T
> Iter
<'a
, T
> {
88 pub(super) fn new(slice
: &'a
[T
]) -> Self {
89 let ptr
= slice
.as_ptr();
90 // SAFETY: Similar to `IterMut::new`.
92 assume(!ptr
.is_null());
94 let end
= if mem
::size_of
::<T
>() == 0 {
95 (ptr
as *const u8).wrapping_add(slice
.len()) as *const T
100 Self { ptr: NonNull::new_unchecked(ptr as *mut T), end, _marker: PhantomData }
104 /// Views the underlying data as a subslice of the original data.
106 /// This has the same lifetime as the original slice, and so the
107 /// iterator can continue to be used while this exists.
114 /// // First, we declare a type which has the `iter` method to get the `Iter`
115 /// // struct (`&[usize]` here):
116 /// let slice = &[1, 2, 3];
118 /// // Then, we get the iterator:
119 /// let mut iter = slice.iter();
120 /// // So if we print what `as_slice` method returns here, we have "[1, 2, 3]":
121 /// println!("{:?}", iter.as_slice());
123 /// // Next, we move to the second element of the slice:
125 /// // Now `as_slice` returns "[2, 3]":
126 /// println!("{:?}", iter.as_slice());
128 #[stable(feature = "iter_to_slice", since = "1.4.0")]
129 pub fn as_slice(&self) -> &'a
[T
] {
134 iterator
! {struct Iter -> *const T, &'a T, const, {/* no mut */}
, {
135 fn is_sorted_by
<F
>(self, mut compare
: F
) -> bool
138 F
: FnMut(&Self::Item
, &Self::Item
) -> Option
<Ordering
>,
140 self.as_slice().windows(2).all(|w
| {
141 compare(&&w
[0], &&w
[1]).map(|o
| o
!= Ordering
::Greater
).unwrap_or(false)
146 #[stable(feature = "rust1", since = "1.0.0")]
147 impl<T
> Clone
for Iter
<'_
, T
> {
148 fn clone(&self) -> Self {
149 Iter { ptr: self.ptr, end: self.end, _marker: self._marker }
153 #[stable(feature = "slice_iter_as_ref", since = "1.13.0")]
154 impl<T
> AsRef
<[T
]> for Iter
<'_
, T
> {
155 fn as_ref(&self) -> &[T
] {
160 /// Mutable slice iterator.
162 /// This struct is created by the [`iter_mut`] method on [slices].
169 /// // First, we declare a type which has `iter_mut` method to get the `IterMut`
170 /// // struct (`&[usize]` here):
171 /// let mut slice = &mut [1, 2, 3];
173 /// // Then, we iterate over it and increment each element value:
174 /// for element in slice.iter_mut() {
178 /// // We now have "[2, 3, 4]":
179 /// println!("{:?}", slice);
182 /// [`iter_mut`]: slice::iter_mut
184 #[stable(feature = "rust1", since = "1.0.0")]
185 pub struct IterMut
<'a
, T
: 'a
> {
187 end
: *mut T
, // If T is a ZST, this is actually ptr+len. This encoding is picked so that
188 // ptr == end is a quick test for the Iterator being empty, that works
189 // for both ZST and non-ZST.
190 _marker
: PhantomData
<&'a
mut T
>,
193 #[stable(feature = "core_impl_debug", since = "1.9.0")]
194 impl<T
: fmt
::Debug
> fmt
::Debug
for IterMut
<'_
, T
> {
195 fn fmt(&self, f
: &mut fmt
::Formatter
<'_
>) -> fmt
::Result
{
196 f
.debug_tuple("IterMut").field(&self.make_slice()).finish()
200 #[stable(feature = "rust1", since = "1.0.0")]
201 unsafe impl<T
: Sync
> Sync
for IterMut
<'_
, T
> {}
202 #[stable(feature = "rust1", since = "1.0.0")]
203 unsafe impl<T
: Send
> Send
for IterMut
<'_
, T
> {}
205 impl<'a
, T
> IterMut
<'a
, T
> {
207 pub(super) fn new(slice
: &'a
mut [T
]) -> Self {
208 let ptr
= slice
.as_mut_ptr();
209 // SAFETY: There are several things here:
211 // `ptr` has been obtained by `slice.as_ptr()` where `slice` is a valid
212 // reference thus it is non-NUL and safe to use and pass to
213 // `NonNull::new_unchecked` .
215 // Adding `slice.len()` to the starting pointer gives a pointer
216 // at the end of `slice`. `end` will never be dereferenced, only checked
217 // for direct pointer equality with `ptr` to check if the iterator is
220 // In the case of a ZST, the end pointer is just the start pointer plus
221 // the length, to also allows for the fast `ptr == end` check.
223 // See the `next_unchecked!` and `is_empty!` macros as well as the
224 // `post_inc_start` method for more informations.
226 assume(!ptr
.is_null());
228 let end
= if mem
::size_of
::<T
>() == 0 {
229 (ptr
as *mut u8).wrapping_add(slice
.len()) as *mut T
234 Self { ptr: NonNull::new_unchecked(ptr), end, _marker: PhantomData }
238 /// Views the underlying data as a subslice of the original data.
240 /// To avoid creating `&mut` references that alias, this is forced
241 /// to consume the iterator.
248 /// // First, we declare a type which has `iter_mut` method to get the `IterMut`
249 /// // struct (`&[usize]` here):
250 /// let mut slice = &mut [1, 2, 3];
253 /// // Then, we get the iterator:
254 /// let mut iter = slice.iter_mut();
255 /// // We move to next element:
257 /// // So if we print what `into_slice` method returns here, we have "[2, 3]":
258 /// println!("{:?}", iter.into_slice());
261 /// // Now let's modify a value of the slice:
263 /// // First we get back the iterator:
264 /// let mut iter = slice.iter_mut();
265 /// // We change the value of the first element of the slice returned by the `next` method:
266 /// *iter.next().unwrap() += 1;
268 /// // Now slice is "[2, 2, 3]":
269 /// println!("{:?}", slice);
271 #[stable(feature = "iter_to_slice", since = "1.4.0")]
272 pub fn into_slice(self) -> &'a
mut [T
] {
273 // SAFETY: the iterator was created from a mutable slice with pointer
274 // `self.ptr` and length `len!(self)`. This guarantees that all the prerequisites
275 // for `from_raw_parts_mut` are fulfilled.
276 unsafe { from_raw_parts_mut(self.ptr.as_ptr(), len!(self)) }
279 /// Views the underlying data as a subslice of the original data.
281 /// To avoid creating `&mut [T]` references that alias, the returned slice
282 /// borrows its lifetime from the iterator the method is applied on.
289 /// let mut slice: &mut [usize] = &mut [1, 2, 3];
291 /// // First, we get the iterator:
292 /// let mut iter = slice.iter_mut();
293 /// // So if we check what the `as_slice` method returns here, we have "[1, 2, 3]":
294 /// assert_eq!(iter.as_slice(), &[1, 2, 3]);
296 /// // Next, we move to the second element of the slice:
298 /// // Now `as_slice` returns "[2, 3]":
299 /// assert_eq!(iter.as_slice(), &[2, 3]);
301 #[stable(feature = "slice_iter_mut_as_slice", since = "1.53.0")]
302 pub fn as_slice(&self) -> &[T
] {
307 #[stable(feature = "slice_iter_mut_as_slice", since = "1.53.0")]
308 impl<T
> AsRef
<[T
]> for IterMut
<'_
, T
> {
309 fn as_ref(&self) -> &[T
] {
314 iterator
! {struct IterMut -> *mut T, &'a mut T, mut, {mut}
, {}
}
316 /// An internal abstraction over the splitting iterators, so that
317 /// splitn, splitn_mut etc can be implemented once.
319 pub(super) trait SplitIter
: DoubleEndedIterator
{
320 /// Marks the underlying iterator as complete, extracting the remaining
321 /// portion of the slice.
322 fn finish(&mut self) -> Option
<Self::Item
>;
325 /// An iterator over subslices separated by elements that match a predicate
328 /// This struct is created by the [`split`] method on [slices].
333 /// let slice = [10, 40, 33, 20];
334 /// let mut iter = slice.split(|num| num % 3 == 0);
337 /// [`split`]: slice::split
339 #[stable(feature = "rust1", since = "1.0.0")]
340 pub struct Split
<'a
, T
: 'a
, P
>
342 P
: FnMut(&T
) -> bool
,
344 // Used for `SplitWhitespace` and `SplitAsciiWhitespace` `as_str` methods
345 pub(crate) v
: &'a
[T
],
347 // Used for `SplitAsciiWhitespace` `as_str` method
348 pub(crate) finished
: bool
,
351 impl<'a
, T
: 'a
, P
: FnMut(&T
) -> bool
> Split
<'a
, T
, P
> {
353 pub(super) fn new(slice
: &'a
[T
], pred
: P
) -> Self {
354 Self { v: slice, pred, finished: false }
358 #[stable(feature = "core_impl_debug", since = "1.9.0")]
359 impl<T
: fmt
::Debug
, P
> fmt
::Debug
for Split
<'_
, T
, P
>
361 P
: FnMut(&T
) -> bool
,
363 fn fmt(&self, f
: &mut fmt
::Formatter
<'_
>) -> fmt
::Result
{
364 f
.debug_struct("Split").field("v", &self.v
).field("finished", &self.finished
).finish()
368 // FIXME(#26925) Remove in favor of `#[derive(Clone)]`
369 #[stable(feature = "rust1", since = "1.0.0")]
370 impl<T
, P
> Clone
for Split
<'_
, T
, P
>
372 P
: Clone
+ FnMut(&T
) -> bool
,
374 fn clone(&self) -> Self {
375 Split { v: self.v, pred: self.pred.clone(), finished: self.finished }
379 #[stable(feature = "rust1", since = "1.0.0")]
380 impl<'a
, T
, P
> Iterator
for Split
<'a
, T
, P
>
382 P
: FnMut(&T
) -> bool
,
387 fn next(&mut self) -> Option
<&'a
[T
]> {
392 match self.v
.iter().position(|x
| (self.pred
)(x
)) {
393 None
=> self.finish(),
395 let ret
= Some(&self.v
[..idx
]);
396 self.v
= &self.v
[idx
+ 1..];
403 fn size_hint(&self) -> (usize, Option
<usize>) {
404 if self.finished { (0, Some(0)) }
else { (1, Some(self.v.len() + 1)) }
408 #[stable(feature = "rust1", since = "1.0.0")]
409 impl<'a
, T
, P
> DoubleEndedIterator
for Split
<'a
, T
, P
>
411 P
: FnMut(&T
) -> bool
,
414 fn next_back(&mut self) -> Option
<&'a
[T
]> {
419 match self.v
.iter().rposition(|x
| (self.pred
)(x
)) {
420 None
=> self.finish(),
422 let ret
= Some(&self.v
[idx
+ 1..]);
423 self.v
= &self.v
[..idx
];
430 impl<'a
, T
, P
> SplitIter
for Split
<'a
, T
, P
>
432 P
: FnMut(&T
) -> bool
,
435 fn finish(&mut self) -> Option
<&'a
[T
]> {
439 self.finished
= true;
445 #[stable(feature = "fused", since = "1.26.0")]
446 impl<T
, P
> FusedIterator
for Split
<'_
, T
, P
> where P
: FnMut(&T
) -> bool {}
448 /// An iterator over subslices separated by elements that match a predicate
449 /// function. Unlike `Split`, it contains the matched part as a terminator
452 /// This struct is created by the [`split_inclusive`] method on [slices].
457 /// let slice = [10, 40, 33, 20];
458 /// let mut iter = slice.split_inclusive(|num| num % 3 == 0);
461 /// [`split_inclusive`]: slice::split_inclusive
463 #[stable(feature = "split_inclusive", since = "1.51.0")]
464 pub struct SplitInclusive
<'a
, T
: 'a
, P
>
466 P
: FnMut(&T
) -> bool
,
473 impl<'a
, T
: 'a
, P
: FnMut(&T
) -> bool
> SplitInclusive
<'a
, T
, P
> {
475 pub(super) fn new(slice
: &'a
[T
], pred
: P
) -> Self {
476 Self { v: slice, pred, finished: false }
480 #[stable(feature = "split_inclusive", since = "1.51.0")]
481 impl<T
: fmt
::Debug
, P
> fmt
::Debug
for SplitInclusive
<'_
, T
, P
>
483 P
: FnMut(&T
) -> bool
,
485 fn fmt(&self, f
: &mut fmt
::Formatter
<'_
>) -> fmt
::Result
{
486 f
.debug_struct("SplitInclusive")
488 .field("finished", &self.finished
)
493 // FIXME(#26925) Remove in favor of `#[derive(Clone)]`
494 #[stable(feature = "split_inclusive", since = "1.51.0")]
495 impl<T
, P
> Clone
for SplitInclusive
<'_
, T
, P
>
497 P
: Clone
+ FnMut(&T
) -> bool
,
499 fn clone(&self) -> Self {
500 SplitInclusive { v: self.v, pred: self.pred.clone(), finished: self.finished }
504 #[stable(feature = "split_inclusive", since = "1.51.0")]
505 impl<'a
, T
, P
> Iterator
for SplitInclusive
<'a
, T
, P
>
507 P
: FnMut(&T
) -> bool
,
512 fn next(&mut self) -> Option
<&'a
[T
]> {
518 self.v
.iter().position(|x
| (self.pred
)(x
)).map(|idx
| idx
+ 1).unwrap_or(self.v
.len());
519 if idx
== self.v
.len() {
520 self.finished
= true;
522 let ret
= Some(&self.v
[..idx
]);
523 self.v
= &self.v
[idx
..];
528 fn size_hint(&self) -> (usize, Option
<usize>) {
529 if self.finished { (0, Some(0)) }
else { (1, Some(self.v.len() + 1)) }
533 #[stable(feature = "split_inclusive", since = "1.51.0")]
534 impl<'a
, T
, P
> DoubleEndedIterator
for SplitInclusive
<'a
, T
, P
>
536 P
: FnMut(&T
) -> bool
,
539 fn next_back(&mut self) -> Option
<&'a
[T
]> {
544 // The last index of self.v is already checked and found to match
545 // by the last iteration, so we start searching a new match
546 // one index to the left.
547 let remainder
= if self.v
.is_empty() { &[] }
else { &self.v[..(self.v.len() - 1)] }
;
548 let idx
= remainder
.iter().rposition(|x
| (self.pred
)(x
)).map(|idx
| idx
+ 1).unwrap_or(0);
550 self.finished
= true;
552 let ret
= Some(&self.v
[idx
..]);
553 self.v
= &self.v
[..idx
];
558 #[stable(feature = "split_inclusive", since = "1.51.0")]
559 impl<T
, P
> FusedIterator
for SplitInclusive
<'_
, T
, P
> where P
: FnMut(&T
) -> bool {}
561 /// An iterator over the mutable subslices of the vector which are separated
562 /// by elements that match `pred`.
564 /// This struct is created by the [`split_mut`] method on [slices].
569 /// let mut v = [10, 40, 30, 20, 60, 50];
570 /// let iter = v.split_mut(|num| *num % 3 == 0);
573 /// [`split_mut`]: slice::split_mut
575 #[stable(feature = "rust1", since = "1.0.0")]
576 pub struct SplitMut
<'a
, T
: 'a
, P
>
578 P
: FnMut(&T
) -> bool
,
585 impl<'a
, T
: 'a
, P
: FnMut(&T
) -> bool
> SplitMut
<'a
, T
, P
> {
587 pub(super) fn new(slice
: &'a
mut [T
], pred
: P
) -> Self {
588 Self { v: slice, pred, finished: false }
592 #[stable(feature = "core_impl_debug", since = "1.9.0")]
593 impl<T
: fmt
::Debug
, P
> fmt
::Debug
for SplitMut
<'_
, T
, P
>
595 P
: FnMut(&T
) -> bool
,
597 fn fmt(&self, f
: &mut fmt
::Formatter
<'_
>) -> fmt
::Result
{
598 f
.debug_struct("SplitMut").field("v", &self.v
).field("finished", &self.finished
).finish()
602 impl<'a
, T
, P
> SplitIter
for SplitMut
<'a
, T
, P
>
604 P
: FnMut(&T
) -> bool
,
607 fn finish(&mut self) -> Option
<&'a
mut [T
]> {
611 self.finished
= true;
612 Some(mem
::replace(&mut self.v
, &mut []))
617 #[stable(feature = "rust1", since = "1.0.0")]
618 impl<'a
, T
, P
> Iterator
for SplitMut
<'a
, T
, P
>
620 P
: FnMut(&T
) -> bool
,
622 type Item
= &'a
mut [T
];
625 fn next(&mut self) -> Option
<&'a
mut [T
]> {
631 // work around borrowck limitations
632 let pred
= &mut self.pred
;
633 self.v
.iter().position(|x
| (*pred
)(x
))
636 None
=> self.finish(),
638 let tmp
= mem
::replace(&mut self.v
, &mut []);
639 let (head
, tail
) = tmp
.split_at_mut(idx
);
640 self.v
= &mut tail
[1..];
647 fn size_hint(&self) -> (usize, Option
<usize>) {
651 // if the predicate doesn't match anything, we yield one slice
652 // if it matches every element, we yield len+1 empty slices.
653 (1, Some(self.v
.len() + 1))
658 #[stable(feature = "rust1", since = "1.0.0")]
659 impl<'a
, T
, P
> DoubleEndedIterator
for SplitMut
<'a
, T
, P
>
661 P
: FnMut(&T
) -> bool
,
664 fn next_back(&mut self) -> Option
<&'a
mut [T
]> {
670 // work around borrowck limitations
671 let pred
= &mut self.pred
;
672 self.v
.iter().rposition(|x
| (*pred
)(x
))
675 None
=> self.finish(),
677 let tmp
= mem
::replace(&mut self.v
, &mut []);
678 let (head
, tail
) = tmp
.split_at_mut(idx
);
686 #[stable(feature = "fused", since = "1.26.0")]
687 impl<T
, P
> FusedIterator
for SplitMut
<'_
, T
, P
> where P
: FnMut(&T
) -> bool {}
689 /// An iterator over the mutable subslices of the vector which are separated
690 /// by elements that match `pred`. Unlike `SplitMut`, it contains the matched
691 /// parts in the ends of the subslices.
693 /// This struct is created by the [`split_inclusive_mut`] method on [slices].
698 /// let mut v = [10, 40, 30, 20, 60, 50];
699 /// let iter = v.split_inclusive_mut(|num| *num % 3 == 0);
702 /// [`split_inclusive_mut`]: slice::split_inclusive_mut
704 #[stable(feature = "split_inclusive", since = "1.51.0")]
705 pub struct SplitInclusiveMut
<'a
, T
: 'a
, P
>
707 P
: FnMut(&T
) -> bool
,
714 impl<'a
, T
: 'a
, P
: FnMut(&T
) -> bool
> SplitInclusiveMut
<'a
, T
, P
> {
716 pub(super) fn new(slice
: &'a
mut [T
], pred
: P
) -> Self {
717 Self { v: slice, pred, finished: false }
721 #[stable(feature = "split_inclusive", since = "1.51.0")]
722 impl<T
: fmt
::Debug
, P
> fmt
::Debug
for SplitInclusiveMut
<'_
, T
, P
>
724 P
: FnMut(&T
) -> bool
,
726 fn fmt(&self, f
: &mut fmt
::Formatter
<'_
>) -> fmt
::Result
{
727 f
.debug_struct("SplitInclusiveMut")
729 .field("finished", &self.finished
)
734 #[stable(feature = "split_inclusive", since = "1.51.0")]
735 impl<'a
, T
, P
> Iterator
for SplitInclusiveMut
<'a
, T
, P
>
737 P
: FnMut(&T
) -> bool
,
739 type Item
= &'a
mut [T
];
742 fn next(&mut self) -> Option
<&'a
mut [T
]> {
748 // work around borrowck limitations
749 let pred
= &mut self.pred
;
750 self.v
.iter().position(|x
| (*pred
)(x
))
752 let idx
= idx_opt
.map(|idx
| idx
+ 1).unwrap_or(self.v
.len());
753 if idx
== self.v
.len() {
754 self.finished
= true;
756 let tmp
= mem
::replace(&mut self.v
, &mut []);
757 let (head
, tail
) = tmp
.split_at_mut(idx
);
763 fn size_hint(&self) -> (usize, Option
<usize>) {
767 // if the predicate doesn't match anything, we yield one slice
768 // if it matches every element, we yield len+1 empty slices.
769 (1, Some(self.v
.len() + 1))
774 #[stable(feature = "split_inclusive", since = "1.51.0")]
775 impl<'a
, T
, P
> DoubleEndedIterator
for SplitInclusiveMut
<'a
, T
, P
>
777 P
: FnMut(&T
) -> bool
,
780 fn next_back(&mut self) -> Option
<&'a
mut [T
]> {
785 let idx_opt
= if self.v
.is_empty() {
788 // work around borrowck limitations
789 let pred
= &mut self.pred
;
791 // The last index of self.v is already checked and found to match
792 // by the last iteration, so we start searching a new match
793 // one index to the left.
794 let remainder
= &self.v
[..(self.v
.len() - 1)];
795 remainder
.iter().rposition(|x
| (*pred
)(x
))
797 let idx
= idx_opt
.map(|idx
| idx
+ 1).unwrap_or(0);
799 self.finished
= true;
801 let tmp
= mem
::replace(&mut self.v
, &mut []);
802 let (head
, tail
) = tmp
.split_at_mut(idx
);
808 #[stable(feature = "split_inclusive", since = "1.51.0")]
809 impl<T
, P
> FusedIterator
for SplitInclusiveMut
<'_
, T
, P
> where P
: FnMut(&T
) -> bool {}
811 /// An iterator over subslices separated by elements that match a predicate
812 /// function, starting from the end of the slice.
814 /// This struct is created by the [`rsplit`] method on [slices].
819 /// let slice = [11, 22, 33, 0, 44, 55];
820 /// let iter = slice.rsplit(|num| *num == 0);
823 /// [`rsplit`]: slice::rsplit
825 #[stable(feature = "slice_rsplit", since = "1.27.0")]
826 #[derive(Clone)] // Is this correct, or does it incorrectly require `T: Clone`?
827 pub struct RSplit
<'a
, T
: 'a
, P
>
829 P
: FnMut(&T
) -> bool
,
831 inner
: Split
<'a
, T
, P
>,
834 impl<'a
, T
: 'a
, P
: FnMut(&T
) -> bool
> RSplit
<'a
, T
, P
> {
836 pub(super) fn new(slice
: &'a
[T
], pred
: P
) -> Self {
837 Self { inner: Split::new(slice, pred) }
841 #[stable(feature = "slice_rsplit", since = "1.27.0")]
842 impl<T
: fmt
::Debug
, P
> fmt
::Debug
for RSplit
<'_
, T
, P
>
844 P
: FnMut(&T
) -> bool
,
846 fn fmt(&self, f
: &mut fmt
::Formatter
<'_
>) -> fmt
::Result
{
847 f
.debug_struct("RSplit")
848 .field("v", &self.inner
.v
)
849 .field("finished", &self.inner
.finished
)
854 #[stable(feature = "slice_rsplit", since = "1.27.0")]
855 impl<'a
, T
, P
> Iterator
for RSplit
<'a
, T
, P
>
857 P
: FnMut(&T
) -> bool
,
862 fn next(&mut self) -> Option
<&'a
[T
]> {
863 self.inner
.next_back()
867 fn size_hint(&self) -> (usize, Option
<usize>) {
868 self.inner
.size_hint()
872 #[stable(feature = "slice_rsplit", since = "1.27.0")]
873 impl<'a
, T
, P
> DoubleEndedIterator
for RSplit
<'a
, T
, P
>
875 P
: FnMut(&T
) -> bool
,
878 fn next_back(&mut self) -> Option
<&'a
[T
]> {
883 #[stable(feature = "slice_rsplit", since = "1.27.0")]
884 impl<'a
, T
, P
> SplitIter
for RSplit
<'a
, T
, P
>
886 P
: FnMut(&T
) -> bool
,
889 fn finish(&mut self) -> Option
<&'a
[T
]> {
894 #[stable(feature = "slice_rsplit", since = "1.27.0")]
895 impl<T
, P
> FusedIterator
for RSplit
<'_
, T
, P
> where P
: FnMut(&T
) -> bool {}
897 /// An iterator over the subslices of the vector which are separated
898 /// by elements that match `pred`, starting from the end of the slice.
900 /// This struct is created by the [`rsplit_mut`] method on [slices].
905 /// let mut slice = [11, 22, 33, 0, 44, 55];
906 /// let iter = slice.rsplit_mut(|num| *num == 0);
909 /// [`rsplit_mut`]: slice::rsplit_mut
911 #[stable(feature = "slice_rsplit", since = "1.27.0")]
912 pub struct RSplitMut
<'a
, T
: 'a
, P
>
914 P
: FnMut(&T
) -> bool
,
916 inner
: SplitMut
<'a
, T
, P
>,
919 impl<'a
, T
: 'a
, P
: FnMut(&T
) -> bool
> RSplitMut
<'a
, T
, P
> {
921 pub(super) fn new(slice
: &'a
mut [T
], pred
: P
) -> Self {
922 Self { inner: SplitMut::new(slice, pred) }
926 #[stable(feature = "slice_rsplit", since = "1.27.0")]
927 impl<T
: fmt
::Debug
, P
> fmt
::Debug
for RSplitMut
<'_
, T
, P
>
929 P
: FnMut(&T
) -> bool
,
931 fn fmt(&self, f
: &mut fmt
::Formatter
<'_
>) -> fmt
::Result
{
932 f
.debug_struct("RSplitMut")
933 .field("v", &self.inner
.v
)
934 .field("finished", &self.inner
.finished
)
939 #[stable(feature = "slice_rsplit", since = "1.27.0")]
940 impl<'a
, T
, P
> SplitIter
for RSplitMut
<'a
, T
, P
>
942 P
: FnMut(&T
) -> bool
,
945 fn finish(&mut self) -> Option
<&'a
mut [T
]> {
950 #[stable(feature = "slice_rsplit", since = "1.27.0")]
951 impl<'a
, T
, P
> Iterator
for RSplitMut
<'a
, T
, P
>
953 P
: FnMut(&T
) -> bool
,
955 type Item
= &'a
mut [T
];
958 fn next(&mut self) -> Option
<&'a
mut [T
]> {
959 self.inner
.next_back()
963 fn size_hint(&self) -> (usize, Option
<usize>) {
964 self.inner
.size_hint()
968 #[stable(feature = "slice_rsplit", since = "1.27.0")]
969 impl<'a
, T
, P
> DoubleEndedIterator
for RSplitMut
<'a
, T
, P
>
971 P
: FnMut(&T
) -> bool
,
974 fn next_back(&mut self) -> Option
<&'a
mut [T
]> {
979 #[stable(feature = "slice_rsplit", since = "1.27.0")]
980 impl<T
, P
> FusedIterator
for RSplitMut
<'_
, T
, P
> where P
: FnMut(&T
) -> bool {}
982 /// An private iterator over subslices separated by elements that
983 /// match a predicate function, splitting at most a fixed number of
986 struct GenericSplitN
<I
> {
991 impl<T
, I
: SplitIter
<Item
= T
>> Iterator
for GenericSplitN
<I
> {
995 fn next(&mut self) -> Option
<T
> {
1010 fn size_hint(&self) -> (usize, Option
<usize>) {
1011 let (lower
, upper_opt
) = self.iter
.size_hint();
1012 (lower
, upper_opt
.map(|upper
| cmp
::min(self.count
, upper
)))
1016 /// An iterator over subslices separated by elements that match a predicate
1017 /// function, limited to a given number of splits.
1019 /// This struct is created by the [`splitn`] method on [slices].
1024 /// let slice = [10, 40, 30, 20, 60, 50];
1025 /// let iter = slice.splitn(2, |num| *num % 3 == 0);
1028 /// [`splitn`]: slice::splitn
1030 #[stable(feature = "rust1", since = "1.0.0")]
1031 pub struct SplitN
<'a
, T
: 'a
, P
>
1033 P
: FnMut(&T
) -> bool
,
1035 inner
: GenericSplitN
<Split
<'a
, T
, P
>>,
1038 impl<'a
, T
: 'a
, P
: FnMut(&T
) -> bool
> SplitN
<'a
, T
, P
> {
1040 pub(super) fn new(s
: Split
<'a
, T
, P
>, n
: usize) -> Self {
1041 Self { inner: GenericSplitN { iter: s, count: n }
}
1045 #[stable(feature = "core_impl_debug", since = "1.9.0")]
1046 impl<T
: fmt
::Debug
, P
> fmt
::Debug
for SplitN
<'_
, T
, P
>
1048 P
: FnMut(&T
) -> bool
,
1050 fn fmt(&self, f
: &mut fmt
::Formatter
<'_
>) -> fmt
::Result
{
1051 f
.debug_struct("SplitN").field("inner", &self.inner
).finish()
1055 /// An iterator over subslices separated by elements that match a
1056 /// predicate function, limited to a given number of splits, starting
1057 /// from the end of the slice.
1059 /// This struct is created by the [`rsplitn`] method on [slices].
1064 /// let slice = [10, 40, 30, 20, 60, 50];
1065 /// let iter = slice.rsplitn(2, |num| *num % 3 == 0);
1068 /// [`rsplitn`]: slice::rsplitn
1070 #[stable(feature = "rust1", since = "1.0.0")]
1071 pub struct RSplitN
<'a
, T
: 'a
, P
>
1073 P
: FnMut(&T
) -> bool
,
1075 inner
: GenericSplitN
<RSplit
<'a
, T
, P
>>,
1078 impl<'a
, T
: 'a
, P
: FnMut(&T
) -> bool
> RSplitN
<'a
, T
, P
> {
1080 pub(super) fn new(s
: RSplit
<'a
, T
, P
>, n
: usize) -> Self {
1081 Self { inner: GenericSplitN { iter: s, count: n }
}
1085 #[stable(feature = "core_impl_debug", since = "1.9.0")]
1086 impl<T
: fmt
::Debug
, P
> fmt
::Debug
for RSplitN
<'_
, T
, P
>
1088 P
: FnMut(&T
) -> bool
,
1090 fn fmt(&self, f
: &mut fmt
::Formatter
<'_
>) -> fmt
::Result
{
1091 f
.debug_struct("RSplitN").field("inner", &self.inner
).finish()
1095 /// An iterator over subslices separated by elements that match a predicate
1096 /// function, limited to a given number of splits.
1098 /// This struct is created by the [`splitn_mut`] method on [slices].
1103 /// let mut slice = [10, 40, 30, 20, 60, 50];
1104 /// let iter = slice.splitn_mut(2, |num| *num % 3 == 0);
1107 /// [`splitn_mut`]: slice::splitn_mut
1109 #[stable(feature = "rust1", since = "1.0.0")]
1110 pub struct SplitNMut
<'a
, T
: 'a
, P
>
1112 P
: FnMut(&T
) -> bool
,
1114 inner
: GenericSplitN
<SplitMut
<'a
, T
, P
>>,
1117 impl<'a
, T
: 'a
, P
: FnMut(&T
) -> bool
> SplitNMut
<'a
, T
, P
> {
1119 pub(super) fn new(s
: SplitMut
<'a
, T
, P
>, n
: usize) -> Self {
1120 Self { inner: GenericSplitN { iter: s, count: n }
}
1124 #[stable(feature = "core_impl_debug", since = "1.9.0")]
1125 impl<T
: fmt
::Debug
, P
> fmt
::Debug
for SplitNMut
<'_
, T
, P
>
1127 P
: FnMut(&T
) -> bool
,
1129 fn fmt(&self, f
: &mut fmt
::Formatter
<'_
>) -> fmt
::Result
{
1130 f
.debug_struct("SplitNMut").field("inner", &self.inner
).finish()
1134 /// An iterator over subslices separated by elements that match a
1135 /// predicate function, limited to a given number of splits, starting
1136 /// from the end of the slice.
1138 /// This struct is created by the [`rsplitn_mut`] method on [slices].
1143 /// let mut slice = [10, 40, 30, 20, 60, 50];
1144 /// let iter = slice.rsplitn_mut(2, |num| *num % 3 == 0);
1147 /// [`rsplitn_mut`]: slice::rsplitn_mut
1149 #[stable(feature = "rust1", since = "1.0.0")]
1150 pub struct RSplitNMut
<'a
, T
: 'a
, P
>
1152 P
: FnMut(&T
) -> bool
,
1154 inner
: GenericSplitN
<RSplitMut
<'a
, T
, P
>>,
1157 impl<'a
, T
: 'a
, P
: FnMut(&T
) -> bool
> RSplitNMut
<'a
, T
, P
> {
1159 pub(super) fn new(s
: RSplitMut
<'a
, T
, P
>, n
: usize) -> Self {
1160 Self { inner: GenericSplitN { iter: s, count: n }
}
1164 #[stable(feature = "core_impl_debug", since = "1.9.0")]
1165 impl<T
: fmt
::Debug
, P
> fmt
::Debug
for RSplitNMut
<'_
, T
, P
>
1167 P
: FnMut(&T
) -> bool
,
1169 fn fmt(&self, f
: &mut fmt
::Formatter
<'_
>) -> fmt
::Result
{
1170 f
.debug_struct("RSplitNMut").field("inner", &self.inner
).finish()
1174 forward_iterator
! { SplitN: T, &'a [T] }
1175 forward_iterator
! { RSplitN: T, &'a [T] }
1176 forward_iterator
! { SplitNMut: T, &'a mut [T] }
1177 forward_iterator
! { RSplitNMut: T, &'a mut [T] }
1179 /// An iterator over overlapping subslices of length `size`.
1181 /// This struct is created by the [`windows`] method on [slices].
1186 /// let slice = ['r', 'u', 's', 't'];
1187 /// let iter = slice.windows(2);
1190 /// [`windows`]: slice::windows
1193 #[stable(feature = "rust1", since = "1.0.0")]
1194 pub struct Windows
<'a
, T
: 'a
> {
1199 impl<'a
, T
: 'a
> Windows
<'a
, T
> {
1201 pub(super) fn new(slice
: &'a
[T
], size
: NonZeroUsize
) -> Self {
1202 Self { v: slice, size }
1206 // FIXME(#26925) Remove in favor of `#[derive(Clone)]`
1207 #[stable(feature = "rust1", since = "1.0.0")]
1208 impl<T
> Clone
for Windows
<'_
, T
> {
1209 fn clone(&self) -> Self {
1210 Windows { v: self.v, size: self.size }
1214 #[stable(feature = "rust1", since = "1.0.0")]
1215 impl<'a
, T
> Iterator
for Windows
<'a
, T
> {
1216 type Item
= &'a
[T
];
1219 fn next(&mut self) -> Option
<&'a
[T
]> {
1220 if self.size
.get() > self.v
.len() {
1223 let ret
= Some(&self.v
[..self.size
.get()]);
1224 self.v
= &self.v
[1..];
1230 fn size_hint(&self) -> (usize, Option
<usize>) {
1231 if self.size
.get() > self.v
.len() {
1234 let size
= self.v
.len() - self.size
.get() + 1;
1240 fn count(self) -> usize {
1245 fn nth(&mut self, n
: usize) -> Option
<Self::Item
> {
1246 let (end
, overflow
) = self.size
.get().overflowing_add(n
);
1247 if end
> self.v
.len() || overflow
{
1251 let nth
= &self.v
[n
..end
];
1252 self.v
= &self.v
[n
+ 1..];
1258 fn last(self) -> Option
<Self::Item
> {
1259 if self.size
.get() > self.v
.len() {
1262 let start
= self.v
.len() - self.size
.get();
1263 Some(&self.v
[start
..])
1268 unsafe fn __iterator_get_unchecked(&mut self, idx
: usize) -> Self::Item
{
1269 // SAFETY: since the caller guarantees that `i` is in bounds,
1270 // which means that `i` cannot overflow an `isize`, and the
1271 // slice created by `from_raw_parts` is a subslice of `self.v`
1272 // thus is guaranteed to be valid for the lifetime `'a` of `self.v`.
1273 unsafe { from_raw_parts(self.v.as_ptr().add(idx), self.size.get()) }
1277 #[stable(feature = "rust1", since = "1.0.0")]
1278 impl<'a
, T
> DoubleEndedIterator
for Windows
<'a
, T
> {
1280 fn next_back(&mut self) -> Option
<&'a
[T
]> {
1281 if self.size
.get() > self.v
.len() {
1284 let ret
= Some(&self.v
[self.v
.len() - self.size
.get()..]);
1285 self.v
= &self.v
[..self.v
.len() - 1];
1291 fn nth_back(&mut self, n
: usize) -> Option
<Self::Item
> {
1292 let (end
, overflow
) = self.v
.len().overflowing_sub(n
);
1293 if end
< self.size
.get() || overflow
{
1297 let ret
= &self.v
[end
- self.size
.get()..end
];
1298 self.v
= &self.v
[..end
- 1];
1304 #[stable(feature = "rust1", since = "1.0.0")]
1305 impl<T
> ExactSizeIterator
for Windows
<'_
, T
> {}
1307 #[unstable(feature = "trusted_len", issue = "37572")]
1308 unsafe impl<T
> TrustedLen
for Windows
<'_
, T
> {}
1310 #[stable(feature = "fused", since = "1.26.0")]
1311 impl<T
> FusedIterator
for Windows
<'_
, T
> {}
1314 #[unstable(feature = "trusted_random_access", issue = "none")]
1315 unsafe impl<'a
, T
> TrustedRandomAccess
for Windows
<'a
, T
> {
1316 const MAY_HAVE_SIDE_EFFECT
: bool
= false;
1319 /// An iterator over a slice in (non-overlapping) chunks (`chunk_size` elements at a
1320 /// time), starting at the beginning of the slice.
1322 /// When the slice len is not evenly divided by the chunk size, the last slice
1323 /// of the iteration will be the remainder.
1325 /// This struct is created by the [`chunks`] method on [slices].
1330 /// let slice = ['l', 'o', 'r', 'e', 'm'];
1331 /// let iter = slice.chunks(2);
1334 /// [`chunks`]: slice::chunks
1337 #[stable(feature = "rust1", since = "1.0.0")]
1338 pub struct Chunks
<'a
, T
: 'a
> {
1343 impl<'a
, T
: 'a
> Chunks
<'a
, T
> {
1345 pub(super) fn new(slice
: &'a
[T
], size
: usize) -> Self {
1346 Self { v: slice, chunk_size: size }
1350 // FIXME(#26925) Remove in favor of `#[derive(Clone)]`
1351 #[stable(feature = "rust1", since = "1.0.0")]
1352 impl<T
> Clone
for Chunks
<'_
, T
> {
1353 fn clone(&self) -> Self {
1354 Chunks { v: self.v, chunk_size: self.chunk_size }
1358 #[stable(feature = "rust1", since = "1.0.0")]
1359 impl<'a
, T
> Iterator
for Chunks
<'a
, T
> {
1360 type Item
= &'a
[T
];
1363 fn next(&mut self) -> Option
<&'a
[T
]> {
1364 if self.v
.is_empty() {
1367 let chunksz
= cmp
::min(self.v
.len(), self.chunk_size
);
1368 let (fst
, snd
) = self.v
.split_at(chunksz
);
1375 fn size_hint(&self) -> (usize, Option
<usize>) {
1376 if self.v
.is_empty() {
1379 let n
= self.v
.len() / self.chunk_size
;
1380 let rem
= self.v
.len() % self.chunk_size
;
1381 let n
= if rem
> 0 { n + 1 }
else { n }
;
1387 fn count(self) -> usize {
1392 fn nth(&mut self, n
: usize) -> Option
<Self::Item
> {
1393 let (start
, overflow
) = n
.overflowing_mul(self.chunk_size
);
1394 if start
>= self.v
.len() || overflow
{
1398 let end
= match start
.checked_add(self.chunk_size
) {
1399 Some(sum
) => cmp
::min(self.v
.len(), sum
),
1400 None
=> self.v
.len(),
1402 let nth
= &self.v
[start
..end
];
1403 self.v
= &self.v
[end
..];
1409 fn last(self) -> Option
<Self::Item
> {
1410 if self.v
.is_empty() {
1413 let start
= (self.v
.len() - 1) / self.chunk_size
* self.chunk_size
;
1414 Some(&self.v
[start
..])
1419 unsafe fn __iterator_get_unchecked(&mut self, idx
: usize) -> Self::Item
{
1420 let start
= idx
* self.chunk_size
;
1421 let end
= match start
.checked_add(self.chunk_size
) {
1422 None
=> self.v
.len(),
1423 Some(end
) => cmp
::min(end
, self.v
.len()),
1425 // SAFETY: the caller guarantees that `i` is in bounds,
1426 // which means that `start` must be in bounds of the
1427 // underlying `self.v` slice, and we made sure that `end`
1428 // is also in bounds of `self.v`. Thus, `start` cannot overflow
1429 // an `isize`, and the slice constructed by `from_raw_parts`
1430 // is a subslice of `self.v` which is guaranteed to be valid
1431 // for the lifetime `'a` of `self.v`.
1432 unsafe { from_raw_parts(self.v.as_ptr().add(start), end - start) }
1436 #[stable(feature = "rust1", since = "1.0.0")]
1437 impl<'a
, T
> DoubleEndedIterator
for Chunks
<'a
, T
> {
1439 fn next_back(&mut self) -> Option
<&'a
[T
]> {
1440 if self.v
.is_empty() {
1443 let remainder
= self.v
.len() % self.chunk_size
;
1444 let chunksz
= if remainder
!= 0 { remainder }
else { self.chunk_size }
;
1445 let (fst
, snd
) = self.v
.split_at(self.v
.len() - chunksz
);
1452 fn nth_back(&mut self, n
: usize) -> Option
<Self::Item
> {
1453 let len
= self.len();
1458 let start
= (len
- 1 - n
) * self.chunk_size
;
1459 let end
= match start
.checked_add(self.chunk_size
) {
1460 Some(res
) => cmp
::min(res
, self.v
.len()),
1461 None
=> self.v
.len(),
1463 let nth_back
= &self.v
[start
..end
];
1464 self.v
= &self.v
[..start
];
1470 #[stable(feature = "rust1", since = "1.0.0")]
1471 impl<T
> ExactSizeIterator
for Chunks
<'_
, T
> {}
1473 #[unstable(feature = "trusted_len", issue = "37572")]
1474 unsafe impl<T
> TrustedLen
for Chunks
<'_
, T
> {}
1476 #[stable(feature = "fused", since = "1.26.0")]
1477 impl<T
> FusedIterator
for Chunks
<'_
, T
> {}
1480 #[unstable(feature = "trusted_random_access", issue = "none")]
1481 unsafe impl<'a
, T
> TrustedRandomAccess
for Chunks
<'a
, T
> {
1482 const MAY_HAVE_SIDE_EFFECT
: bool
= false;
1485 /// An iterator over a slice in (non-overlapping) mutable chunks (`chunk_size`
1486 /// elements at a time), starting at the beginning of the slice.
1488 /// When the slice len is not evenly divided by the chunk size, the last slice
1489 /// of the iteration will be the remainder.
1491 /// This struct is created by the [`chunks_mut`] method on [slices].
1496 /// let mut slice = ['l', 'o', 'r', 'e', 'm'];
1497 /// let iter = slice.chunks_mut(2);
1500 /// [`chunks_mut`]: slice::chunks_mut
1503 #[stable(feature = "rust1", since = "1.0.0")]
1504 pub struct ChunksMut
<'a
, T
: 'a
> {
1509 impl<'a
, T
: 'a
> ChunksMut
<'a
, T
> {
1511 pub(super) fn new(slice
: &'a
mut [T
], size
: usize) -> Self {
1512 Self { v: slice, chunk_size: size }
1516 #[stable(feature = "rust1", since = "1.0.0")]
1517 impl<'a
, T
> Iterator
for ChunksMut
<'a
, T
> {
1518 type Item
= &'a
mut [T
];
1521 fn next(&mut self) -> Option
<&'a
mut [T
]> {
1522 if self.v
.is_empty() {
1525 let sz
= cmp
::min(self.v
.len(), self.chunk_size
);
1526 let tmp
= mem
::replace(&mut self.v
, &mut []);
1527 let (head
, tail
) = tmp
.split_at_mut(sz
);
1534 fn size_hint(&self) -> (usize, Option
<usize>) {
1535 if self.v
.is_empty() {
1538 let n
= self.v
.len() / self.chunk_size
;
1539 let rem
= self.v
.len() % self.chunk_size
;
1540 let n
= if rem
> 0 { n + 1 }
else { n }
;
1546 fn count(self) -> usize {
1551 fn nth(&mut self, n
: usize) -> Option
<&'a
mut [T
]> {
1552 let (start
, overflow
) = n
.overflowing_mul(self.chunk_size
);
1553 if start
>= self.v
.len() || overflow
{
1557 let end
= match start
.checked_add(self.chunk_size
) {
1558 Some(sum
) => cmp
::min(self.v
.len(), sum
),
1559 None
=> self.v
.len(),
1561 let tmp
= mem
::replace(&mut self.v
, &mut []);
1562 let (head
, tail
) = tmp
.split_at_mut(end
);
1563 let (_
, nth
) = head
.split_at_mut(start
);
1570 fn last(self) -> Option
<Self::Item
> {
1571 if self.v
.is_empty() {
1574 let start
= (self.v
.len() - 1) / self.chunk_size
* self.chunk_size
;
1575 Some(&mut self.v
[start
..])
1580 unsafe fn __iterator_get_unchecked(&mut self, idx
: usize) -> Self::Item
{
1581 let start
= idx
* self.chunk_size
;
1582 let end
= match start
.checked_add(self.chunk_size
) {
1583 None
=> self.v
.len(),
1584 Some(end
) => cmp
::min(end
, self.v
.len()),
1586 // SAFETY: see comments for `Chunks::__iterator_get_unchecked`.
1588 // Also note that the caller also guarantees that we're never called
1589 // with the same index again, and that no other methods that will
1590 // access this subslice are called, so it is valid for the returned
1591 // slice to be mutable.
1592 unsafe { from_raw_parts_mut(self.v.as_mut_ptr().add(start), end - start) }
1596 #[stable(feature = "rust1", since = "1.0.0")]
1597 impl<'a
, T
> DoubleEndedIterator
for ChunksMut
<'a
, T
> {
1599 fn next_back(&mut self) -> Option
<&'a
mut [T
]> {
1600 if self.v
.is_empty() {
1603 let remainder
= self.v
.len() % self.chunk_size
;
1604 let sz
= if remainder
!= 0 { remainder }
else { self.chunk_size }
;
1605 let tmp
= mem
::replace(&mut self.v
, &mut []);
1606 let tmp_len
= tmp
.len();
1607 let (head
, tail
) = tmp
.split_at_mut(tmp_len
- sz
);
1614 fn nth_back(&mut self, n
: usize) -> Option
<Self::Item
> {
1615 let len
= self.len();
1620 let start
= (len
- 1 - n
) * self.chunk_size
;
1621 let end
= match start
.checked_add(self.chunk_size
) {
1622 Some(res
) => cmp
::min(res
, self.v
.len()),
1623 None
=> self.v
.len(),
1625 let (temp
, _tail
) = mem
::replace(&mut self.v
, &mut []).split_at_mut(end
);
1626 let (head
, nth_back
) = temp
.split_at_mut(start
);
1633 #[stable(feature = "rust1", since = "1.0.0")]
1634 impl<T
> ExactSizeIterator
for ChunksMut
<'_
, T
> {}
1636 #[unstable(feature = "trusted_len", issue = "37572")]
1637 unsafe impl<T
> TrustedLen
for ChunksMut
<'_
, T
> {}
1639 #[stable(feature = "fused", since = "1.26.0")]
1640 impl<T
> FusedIterator
for ChunksMut
<'_
, T
> {}
1643 #[unstable(feature = "trusted_random_access", issue = "none")]
1644 unsafe impl<'a
, T
> TrustedRandomAccess
for ChunksMut
<'a
, T
> {
1645 const MAY_HAVE_SIDE_EFFECT
: bool
= false;
1648 /// An iterator over a slice in (non-overlapping) chunks (`chunk_size` elements at a
1649 /// time), starting at the beginning of the slice.
1651 /// When the slice len is not evenly divided by the chunk size, the last
1652 /// up to `chunk_size-1` elements will be omitted but can be retrieved from
1653 /// the [`remainder`] function from the iterator.
1655 /// This struct is created by the [`chunks_exact`] method on [slices].
1660 /// let slice = ['l', 'o', 'r', 'e', 'm'];
1661 /// let iter = slice.chunks_exact(2);
1664 /// [`chunks_exact`]: slice::chunks_exact
1665 /// [`remainder`]: ChunksExact::remainder
1668 #[stable(feature = "chunks_exact", since = "1.31.0")]
1669 pub struct ChunksExact
<'a
, T
: 'a
> {
1675 impl<'a
, T
> ChunksExact
<'a
, T
> {
1677 pub(super) fn new(slice
: &'a
[T
], chunk_size
: usize) -> Self {
1678 let rem
= slice
.len() % chunk_size
;
1679 let fst_len
= slice
.len() - rem
;
1680 // SAFETY: 0 <= fst_len <= slice.len() by construction above
1681 let (fst
, snd
) = unsafe { slice.split_at_unchecked(fst_len) }
;
1682 Self { v: fst, rem: snd, chunk_size }
1685 /// Returns the remainder of the original slice that is not going to be
1686 /// returned by the iterator. The returned slice has at most `chunk_size-1`
1688 #[stable(feature = "chunks_exact", since = "1.31.0")]
1689 pub fn remainder(&self) -> &'a
[T
] {
1694 // FIXME(#26925) Remove in favor of `#[derive(Clone)]`
1695 #[stable(feature = "chunks_exact", since = "1.31.0")]
1696 impl<T
> Clone
for ChunksExact
<'_
, T
> {
1697 fn clone(&self) -> Self {
1698 ChunksExact { v: self.v, rem: self.rem, chunk_size: self.chunk_size }
1702 #[stable(feature = "chunks_exact", since = "1.31.0")]
1703 impl<'a
, T
> Iterator
for ChunksExact
<'a
, T
> {
1704 type Item
= &'a
[T
];
1707 fn next(&mut self) -> Option
<&'a
[T
]> {
1708 if self.v
.len() < self.chunk_size
{
1711 let (fst
, snd
) = self.v
.split_at(self.chunk_size
);
1718 fn size_hint(&self) -> (usize, Option
<usize>) {
1719 let n
= self.v
.len() / self.chunk_size
;
1724 fn count(self) -> usize {
1729 fn nth(&mut self, n
: usize) -> Option
<Self::Item
> {
1730 let (start
, overflow
) = n
.overflowing_mul(self.chunk_size
);
1731 if start
>= self.v
.len() || overflow
{
1735 let (_
, snd
) = self.v
.split_at(start
);
1742 fn last(mut self) -> Option
<Self::Item
> {
1747 unsafe fn __iterator_get_unchecked(&mut self, idx
: usize) -> Self::Item
{
1748 let start
= idx
* self.chunk_size
;
1749 // SAFETY: mostly identical to `Chunks::__iterator_get_unchecked`.
1750 unsafe { from_raw_parts(self.v.as_ptr().add(start), self.chunk_size) }
1754 #[stable(feature = "chunks_exact", since = "1.31.0")]
1755 impl<'a
, T
> DoubleEndedIterator
for ChunksExact
<'a
, T
> {
1757 fn next_back(&mut self) -> Option
<&'a
[T
]> {
1758 if self.v
.len() < self.chunk_size
{
1761 let (fst
, snd
) = self.v
.split_at(self.v
.len() - self.chunk_size
);
1768 fn nth_back(&mut self, n
: usize) -> Option
<Self::Item
> {
1769 let len
= self.len();
1774 let start
= (len
- 1 - n
) * self.chunk_size
;
1775 let end
= start
+ self.chunk_size
;
1776 let nth_back
= &self.v
[start
..end
];
1777 self.v
= &self.v
[..start
];
1783 #[stable(feature = "chunks_exact", since = "1.31.0")]
1784 impl<T
> ExactSizeIterator
for ChunksExact
<'_
, T
> {
1785 fn is_empty(&self) -> bool
{
1790 #[unstable(feature = "trusted_len", issue = "37572")]
1791 unsafe impl<T
> TrustedLen
for ChunksExact
<'_
, T
> {}
1793 #[stable(feature = "chunks_exact", since = "1.31.0")]
1794 impl<T
> FusedIterator
for ChunksExact
<'_
, T
> {}
1797 #[unstable(feature = "trusted_random_access", issue = "none")]
1798 unsafe impl<'a
, T
> TrustedRandomAccess
for ChunksExact
<'a
, T
> {
1799 const MAY_HAVE_SIDE_EFFECT
: bool
= false;
1802 /// An iterator over a slice in (non-overlapping) mutable chunks (`chunk_size`
1803 /// elements at a time), starting at the beginning of the slice.
1805 /// When the slice len is not evenly divided by the chunk size, the last up to
1806 /// `chunk_size-1` elements will be omitted but can be retrieved from the
1807 /// [`into_remainder`] function from the iterator.
1809 /// This struct is created by the [`chunks_exact_mut`] method on [slices].
1814 /// let mut slice = ['l', 'o', 'r', 'e', 'm'];
1815 /// let iter = slice.chunks_exact_mut(2);
1818 /// [`chunks_exact_mut`]: slice::chunks_exact_mut
1819 /// [`into_remainder`]: ChunksExactMut::into_remainder
1822 #[stable(feature = "chunks_exact", since = "1.31.0")]
1823 pub struct ChunksExactMut
<'a
, T
: 'a
> {
1829 impl<'a
, T
> ChunksExactMut
<'a
, T
> {
1831 pub(super) fn new(slice
: &'a
mut [T
], chunk_size
: usize) -> Self {
1832 let rem
= slice
.len() % chunk_size
;
1833 let fst_len
= slice
.len() - rem
;
1834 // SAFETY: 0 <= fst_len <= slice.len() by construction above
1835 let (fst
, snd
) = unsafe { slice.split_at_mut_unchecked(fst_len) }
;
1836 Self { v: fst, rem: snd, chunk_size }
1839 /// Returns the remainder of the original slice that is not going to be
1840 /// returned by the iterator. The returned slice has at most `chunk_size-1`
1842 #[stable(feature = "chunks_exact", since = "1.31.0")]
1843 pub fn into_remainder(self) -> &'a
mut [T
] {
1848 #[stable(feature = "chunks_exact", since = "1.31.0")]
1849 impl<'a
, T
> Iterator
for ChunksExactMut
<'a
, T
> {
1850 type Item
= &'a
mut [T
];
1853 fn next(&mut self) -> Option
<&'a
mut [T
]> {
1854 if self.v
.len() < self.chunk_size
{
1857 let tmp
= mem
::replace(&mut self.v
, &mut []);
1858 let (head
, tail
) = tmp
.split_at_mut(self.chunk_size
);
1865 fn size_hint(&self) -> (usize, Option
<usize>) {
1866 let n
= self.v
.len() / self.chunk_size
;
1871 fn count(self) -> usize {
1876 fn nth(&mut self, n
: usize) -> Option
<&'a
mut [T
]> {
1877 let (start
, overflow
) = n
.overflowing_mul(self.chunk_size
);
1878 if start
>= self.v
.len() || overflow
{
1882 let tmp
= mem
::replace(&mut self.v
, &mut []);
1883 let (_
, snd
) = tmp
.split_at_mut(start
);
1890 fn last(mut self) -> Option
<Self::Item
> {
1895 unsafe fn __iterator_get_unchecked(&mut self, idx
: usize) -> Self::Item
{
1896 let start
= idx
* self.chunk_size
;
1897 // SAFETY: see comments for `ChunksMut::__iterator_get_unchecked`.
1898 unsafe { from_raw_parts_mut(self.v.as_mut_ptr().add(start), self.chunk_size) }
1902 #[stable(feature = "chunks_exact", since = "1.31.0")]
1903 impl<'a
, T
> DoubleEndedIterator
for ChunksExactMut
<'a
, T
> {
1905 fn next_back(&mut self) -> Option
<&'a
mut [T
]> {
1906 if self.v
.len() < self.chunk_size
{
1909 let tmp
= mem
::replace(&mut self.v
, &mut []);
1910 let tmp_len
= tmp
.len();
1911 let (head
, tail
) = tmp
.split_at_mut(tmp_len
- self.chunk_size
);
1918 fn nth_back(&mut self, n
: usize) -> Option
<Self::Item
> {
1919 let len
= self.len();
1924 let start
= (len
- 1 - n
) * self.chunk_size
;
1925 let end
= start
+ self.chunk_size
;
1926 let (temp
, _tail
) = mem
::replace(&mut self.v
, &mut []).split_at_mut(end
);
1927 let (head
, nth_back
) = temp
.split_at_mut(start
);
1934 #[stable(feature = "chunks_exact", since = "1.31.0")]
1935 impl<T
> ExactSizeIterator
for ChunksExactMut
<'_
, T
> {
1936 fn is_empty(&self) -> bool
{
1941 #[unstable(feature = "trusted_len", issue = "37572")]
1942 unsafe impl<T
> TrustedLen
for ChunksExactMut
<'_
, T
> {}
1944 #[stable(feature = "chunks_exact", since = "1.31.0")]
1945 impl<T
> FusedIterator
for ChunksExactMut
<'_
, T
> {}
1948 #[unstable(feature = "trusted_random_access", issue = "none")]
1949 unsafe impl<'a
, T
> TrustedRandomAccess
for ChunksExactMut
<'a
, T
> {
1950 const MAY_HAVE_SIDE_EFFECT
: bool
= false;
1953 /// A windowed iterator over a slice in overlapping chunks (`N` elements at a
1954 /// time), starting at the beginning of the slice
1956 /// This struct is created by the [`array_windows`] method on [slices].
1961 /// #![feature(array_windows)]
1963 /// let slice = [0, 1, 2, 3];
1964 /// let iter = slice.array_windows::<2>();
1967 /// [`array_windows`]: slice::array_windows
1969 #[derive(Debug, Clone, Copy)]
1970 #[unstable(feature = "array_windows", issue = "75027")]
1971 pub struct ArrayWindows
<'a
, T
: 'a
, const N
: usize> {
1972 slice_head
: *const T
,
1974 marker
: PhantomData
<&'a
[T
; N
]>,
1977 impl<'a
, T
: 'a
, const N
: usize> ArrayWindows
<'a
, T
, N
> {
1979 pub(super) fn new(slice
: &'a
[T
]) -> Self {
1980 let num_windows
= slice
.len().saturating_sub(N
- 1);
1981 Self { slice_head: slice.as_ptr(), num: num_windows, marker: PhantomData }
1985 #[unstable(feature = "array_windows", issue = "75027")]
1986 impl<'a
, T
, const N
: usize> Iterator
for ArrayWindows
<'a
, T
, N
> {
1987 type Item
= &'a
[T
; N
];
1990 fn next(&mut self) -> Option
<Self::Item
> {
1995 // This is safe because it's indexing into a slice guaranteed to be length > N.
1996 let ret
= unsafe { &*self.slice_head.cast::<[T; N]>() }
;
1997 // SAFETY: Guaranteed that there are at least 1 item remaining otherwise
1998 // earlier branch would've been hit
1999 self.slice_head
= unsafe { self.slice_head.add(1) }
;
2006 fn size_hint(&self) -> (usize, Option
<usize>) {
2007 (self.num
, Some(self.num
))
2011 fn count(self) -> usize {
2016 fn nth(&mut self, n
: usize) -> Option
<Self::Item
> {
2022 // This is safe because it's indexing into a slice guaranteed to be length > N.
2023 let ret
= unsafe { &*self.slice_head.add(n).cast::<[T; N]>() }
;
2024 // SAFETY: Guaranteed that there are at least n items remaining
2025 self.slice_head
= unsafe { self.slice_head.add(n + 1) }
;
2032 fn last(mut self) -> Option
<Self::Item
> {
2033 self.nth(self.num
.checked_sub(1)?
)
2037 #[unstable(feature = "array_windows", issue = "75027")]
2038 impl<'a
, T
, const N
: usize> DoubleEndedIterator
for ArrayWindows
<'a
, T
, N
> {
2040 fn next_back(&mut self) -> Option
<&'a
[T
; N
]> {
2044 // SAFETY: Guaranteed that there are n items remaining, n-1 for 0-indexing.
2045 let ret
= unsafe { &*self.slice_head.add(self.num - 1).cast::<[T; N]>() }
;
2051 fn nth_back(&mut self, n
: usize) -> Option
<&'a
[T
; N
]> {
2056 // SAFETY: Guaranteed that there are n items remaining, n-1 for 0-indexing.
2057 let ret
= unsafe { &*self.slice_head.add(self.num - (n + 1)).cast::<[T; N]>() }
;
2063 #[unstable(feature = "array_windows", issue = "75027")]
2064 impl<T
, const N
: usize> ExactSizeIterator
for ArrayWindows
<'_
, T
, N
> {
2065 fn is_empty(&self) -> bool
{
2070 /// An iterator over a slice in (non-overlapping) chunks (`N` elements at a
2071 /// time), starting at the beginning of the slice.
2073 /// When the slice len is not evenly divided by the chunk size, the last
2074 /// up to `N-1` elements will be omitted but can be retrieved from
2075 /// the [`remainder`] function from the iterator.
2077 /// This struct is created by the [`array_chunks`] method on [slices].
2082 /// #![feature(array_chunks)]
2084 /// let slice = ['l', 'o', 'r', 'e', 'm'];
2085 /// let iter = slice.array_chunks::<2>();
2088 /// [`array_chunks`]: slice::array_chunks
2089 /// [`remainder`]: ArrayChunks::remainder
2092 #[unstable(feature = "array_chunks", issue = "74985")]
2093 pub struct ArrayChunks
<'a
, T
: 'a
, const N
: usize> {
2094 iter
: Iter
<'a
, [T
; N
]>,
2098 impl<'a
, T
, const N
: usize> ArrayChunks
<'a
, T
, N
> {
2100 pub(super) fn new(slice
: &'a
[T
]) -> Self {
2101 let (array_slice
, rem
) = slice
.as_chunks();
2102 Self { iter: array_slice.iter(), rem }
2105 /// Returns the remainder of the original slice that is not going to be
2106 /// returned by the iterator. The returned slice has at most `N-1`
2108 #[unstable(feature = "array_chunks", issue = "74985")]
2109 pub fn remainder(&self) -> &'a
[T
] {
2114 // FIXME(#26925) Remove in favor of `#[derive(Clone)]`
2115 #[unstable(feature = "array_chunks", issue = "74985")]
2116 impl<T
, const N
: usize> Clone
for ArrayChunks
<'_
, T
, N
> {
2117 fn clone(&self) -> Self {
2118 ArrayChunks { iter: self.iter.clone(), rem: self.rem }
2122 #[unstable(feature = "array_chunks", issue = "74985")]
2123 impl<'a
, T
, const N
: usize> Iterator
for ArrayChunks
<'a
, T
, N
> {
2124 type Item
= &'a
[T
; N
];
2127 fn next(&mut self) -> Option
<&'a
[T
; N
]> {
2132 fn size_hint(&self) -> (usize, Option
<usize>) {
2133 self.iter
.size_hint()
2137 fn count(self) -> usize {
2142 fn nth(&mut self, n
: usize) -> Option
<Self::Item
> {
2147 fn last(self) -> Option
<Self::Item
> {
2151 unsafe fn __iterator_get_unchecked(&mut self, i
: usize) -> &'a
[T
; N
] {
2152 // SAFETY: The safety guarantees of `__iterator_get_unchecked` are
2153 // transferred to the caller.
2154 unsafe { self.iter.__iterator_get_unchecked(i) }
2158 #[unstable(feature = "array_chunks", issue = "74985")]
2159 impl<'a
, T
, const N
: usize> DoubleEndedIterator
for ArrayChunks
<'a
, T
, N
> {
2161 fn next_back(&mut self) -> Option
<&'a
[T
; N
]> {
2162 self.iter
.next_back()
2166 fn nth_back(&mut self, n
: usize) -> Option
<Self::Item
> {
2167 self.iter
.nth_back(n
)
2171 #[unstable(feature = "array_chunks", issue = "74985")]
2172 impl<T
, const N
: usize> ExactSizeIterator
for ArrayChunks
<'_
, T
, N
> {
2173 fn is_empty(&self) -> bool
{
2174 self.iter
.is_empty()
2178 #[unstable(feature = "trusted_len", issue = "37572")]
2179 unsafe impl<T
, const N
: usize> TrustedLen
for ArrayChunks
<'_
, T
, N
> {}
2181 #[unstable(feature = "array_chunks", issue = "74985")]
2182 impl<T
, const N
: usize> FusedIterator
for ArrayChunks
<'_
, T
, N
> {}
2185 #[unstable(feature = "array_chunks", issue = "74985")]
2186 unsafe impl<'a
, T
, const N
: usize> TrustedRandomAccess
for ArrayChunks
<'a
, T
, N
> {
2187 const MAY_HAVE_SIDE_EFFECT
: bool
= false;
2190 /// An iterator over a slice in (non-overlapping) mutable chunks (`N` elements
2191 /// at a time), starting at the beginning of the slice.
2193 /// When the slice len is not evenly divided by the chunk size, the last
2194 /// up to `N-1` elements will be omitted but can be retrieved from
2195 /// the [`into_remainder`] function from the iterator.
2197 /// This struct is created by the [`array_chunks_mut`] method on [slices].
2202 /// #![feature(array_chunks)]
2204 /// let mut slice = ['l', 'o', 'r', 'e', 'm'];
2205 /// let iter = slice.array_chunks_mut::<2>();
2208 /// [`array_chunks_mut`]: slice::array_chunks_mut
2209 /// [`into_remainder`]: ../../std/slice/struct.ArrayChunksMut.html#method.into_remainder
2212 #[unstable(feature = "array_chunks", issue = "74985")]
2213 pub struct ArrayChunksMut
<'a
, T
: 'a
, const N
: usize> {
2214 iter
: IterMut
<'a
, [T
; N
]>,
2218 impl<'a
, T
, const N
: usize> ArrayChunksMut
<'a
, T
, N
> {
2220 pub(super) fn new(slice
: &'a
mut [T
]) -> Self {
2221 let (array_slice
, rem
) = slice
.as_chunks_mut();
2222 Self { iter: array_slice.iter_mut(), rem }
2225 /// Returns the remainder of the original slice that is not going to be
2226 /// returned by the iterator. The returned slice has at most `N-1`
2228 #[unstable(feature = "array_chunks", issue = "74985")]
2229 pub fn into_remainder(self) -> &'a
mut [T
] {
2234 #[unstable(feature = "array_chunks", issue = "74985")]
2235 impl<'a
, T
, const N
: usize> Iterator
for ArrayChunksMut
<'a
, T
, N
> {
2236 type Item
= &'a
mut [T
; N
];
2239 fn next(&mut self) -> Option
<&'a
mut [T
; N
]> {
2244 fn size_hint(&self) -> (usize, Option
<usize>) {
2245 self.iter
.size_hint()
2249 fn count(self) -> usize {
2254 fn nth(&mut self, n
: usize) -> Option
<Self::Item
> {
2259 fn last(self) -> Option
<Self::Item
> {
2263 unsafe fn __iterator_get_unchecked(&mut self, i
: usize) -> &'a
mut [T
; N
] {
2264 // SAFETY: The safety guarantees of `__iterator_get_unchecked` are transferred to
2266 unsafe { self.iter.__iterator_get_unchecked(i) }
2270 #[unstable(feature = "array_chunks", issue = "74985")]
2271 impl<'a
, T
, const N
: usize> DoubleEndedIterator
for ArrayChunksMut
<'a
, T
, N
> {
2273 fn next_back(&mut self) -> Option
<&'a
mut [T
; N
]> {
2274 self.iter
.next_back()
2278 fn nth_back(&mut self, n
: usize) -> Option
<Self::Item
> {
2279 self.iter
.nth_back(n
)
2283 #[unstable(feature = "array_chunks", issue = "74985")]
2284 impl<T
, const N
: usize> ExactSizeIterator
for ArrayChunksMut
<'_
, T
, N
> {
2285 fn is_empty(&self) -> bool
{
2286 self.iter
.is_empty()
2290 #[unstable(feature = "trusted_len", issue = "37572")]
2291 unsafe impl<T
, const N
: usize> TrustedLen
for ArrayChunksMut
<'_
, T
, N
> {}
2293 #[unstable(feature = "array_chunks", issue = "74985")]
2294 impl<T
, const N
: usize> FusedIterator
for ArrayChunksMut
<'_
, T
, N
> {}
2297 #[unstable(feature = "array_chunks", issue = "74985")]
2298 unsafe impl<'a
, T
, const N
: usize> TrustedRandomAccess
for ArrayChunksMut
<'a
, T
, N
> {
2299 const MAY_HAVE_SIDE_EFFECT
: bool
= false;
2302 /// An iterator over a slice in (non-overlapping) chunks (`chunk_size` elements at a
2303 /// time), starting at the end of the slice.
2305 /// When the slice len is not evenly divided by the chunk size, the last slice
2306 /// of the iteration will be the remainder.
2308 /// This struct is created by the [`rchunks`] method on [slices].
2313 /// let slice = ['l', 'o', 'r', 'e', 'm'];
2314 /// let iter = slice.rchunks(2);
2317 /// [`rchunks`]: slice::rchunks
2320 #[stable(feature = "rchunks", since = "1.31.0")]
2321 pub struct RChunks
<'a
, T
: 'a
> {
2326 impl<'a
, T
: 'a
> RChunks
<'a
, T
> {
2328 pub(super) fn new(slice
: &'a
[T
], size
: usize) -> Self {
2329 Self { v: slice, chunk_size: size }
2333 // FIXME(#26925) Remove in favor of `#[derive(Clone)]`
2334 #[stable(feature = "rchunks", since = "1.31.0")]
2335 impl<T
> Clone
for RChunks
<'_
, T
> {
2336 fn clone(&self) -> Self {
2337 RChunks { v: self.v, chunk_size: self.chunk_size }
2341 #[stable(feature = "rchunks", since = "1.31.0")]
2342 impl<'a
, T
> Iterator
for RChunks
<'a
, T
> {
2343 type Item
= &'a
[T
];
2346 fn next(&mut self) -> Option
<&'a
[T
]> {
2347 if self.v
.is_empty() {
2350 let chunksz
= cmp
::min(self.v
.len(), self.chunk_size
);
2351 let (fst
, snd
) = self.v
.split_at(self.v
.len() - chunksz
);
2358 fn size_hint(&self) -> (usize, Option
<usize>) {
2359 if self.v
.is_empty() {
2362 let n
= self.v
.len() / self.chunk_size
;
2363 let rem
= self.v
.len() % self.chunk_size
;
2364 let n
= if rem
> 0 { n + 1 }
else { n }
;
2370 fn count(self) -> usize {
2375 fn nth(&mut self, n
: usize) -> Option
<Self::Item
> {
2376 let (end
, overflow
) = n
.overflowing_mul(self.chunk_size
);
2377 if end
>= self.v
.len() || overflow
{
2381 // Can't underflow because of the check above
2382 let end
= self.v
.len() - end
;
2383 let start
= match end
.checked_sub(self.chunk_size
) {
2387 let nth
= &self.v
[start
..end
];
2388 self.v
= &self.v
[0..start
];
2394 fn last(self) -> Option
<Self::Item
> {
2395 if self.v
.is_empty() {
2398 let rem
= self.v
.len() % self.chunk_size
;
2399 let end
= if rem
== 0 { self.chunk_size }
else { rem }
;
2400 Some(&self.v
[0..end
])
2405 unsafe fn __iterator_get_unchecked(&mut self, idx
: usize) -> Self::Item
{
2406 let end
= self.v
.len() - idx
* self.chunk_size
;
2407 let start
= match end
.checked_sub(self.chunk_size
) {
2409 Some(start
) => start
,
2411 // SAFETY: mostly identical to `Chunks::__iterator_get_unchecked`.
2412 unsafe { from_raw_parts(self.v.as_ptr().add(start), end - start) }
2416 #[stable(feature = "rchunks", since = "1.31.0")]
2417 impl<'a
, T
> DoubleEndedIterator
for RChunks
<'a
, T
> {
2419 fn next_back(&mut self) -> Option
<&'a
[T
]> {
2420 if self.v
.is_empty() {
2423 let remainder
= self.v
.len() % self.chunk_size
;
2424 let chunksz
= if remainder
!= 0 { remainder }
else { self.chunk_size }
;
2425 let (fst
, snd
) = self.v
.split_at(chunksz
);
2432 fn nth_back(&mut self, n
: usize) -> Option
<Self::Item
> {
2433 let len
= self.len();
2438 // can't underflow because `n < len`
2439 let offset_from_end
= (len
- 1 - n
) * self.chunk_size
;
2440 let end
= self.v
.len() - offset_from_end
;
2441 let start
= end
.saturating_sub(self.chunk_size
);
2442 let nth_back
= &self.v
[start
..end
];
2443 self.v
= &self.v
[end
..];
2449 #[stable(feature = "rchunks", since = "1.31.0")]
2450 impl<T
> ExactSizeIterator
for RChunks
<'_
, T
> {}
2452 #[unstable(feature = "trusted_len", issue = "37572")]
2453 unsafe impl<T
> TrustedLen
for RChunks
<'_
, T
> {}
2455 #[stable(feature = "rchunks", since = "1.31.0")]
2456 impl<T
> FusedIterator
for RChunks
<'_
, T
> {}
2459 #[unstable(feature = "trusted_random_access", issue = "none")]
2460 unsafe impl<'a
, T
> TrustedRandomAccess
for RChunks
<'a
, T
> {
2461 const MAY_HAVE_SIDE_EFFECT
: bool
= false;
2464 /// An iterator over a slice in (non-overlapping) mutable chunks (`chunk_size`
2465 /// elements at a time), starting at the end of the slice.
2467 /// When the slice len is not evenly divided by the chunk size, the last slice
2468 /// of the iteration will be the remainder.
2470 /// This struct is created by the [`rchunks_mut`] method on [slices].
2475 /// let mut slice = ['l', 'o', 'r', 'e', 'm'];
2476 /// let iter = slice.rchunks_mut(2);
2479 /// [`rchunks_mut`]: slice::rchunks_mut
2482 #[stable(feature = "rchunks", since = "1.31.0")]
2483 pub struct RChunksMut
<'a
, T
: 'a
> {
2488 impl<'a
, T
: 'a
> RChunksMut
<'a
, T
> {
2490 pub(super) fn new(slice
: &'a
mut [T
], size
: usize) -> Self {
2491 Self { v: slice, chunk_size: size }
2495 #[stable(feature = "rchunks", since = "1.31.0")]
2496 impl<'a
, T
> Iterator
for RChunksMut
<'a
, T
> {
2497 type Item
= &'a
mut [T
];
2500 fn next(&mut self) -> Option
<&'a
mut [T
]> {
2501 if self.v
.is_empty() {
2504 let sz
= cmp
::min(self.v
.len(), self.chunk_size
);
2505 let tmp
= mem
::replace(&mut self.v
, &mut []);
2506 let tmp_len
= tmp
.len();
2507 let (head
, tail
) = tmp
.split_at_mut(tmp_len
- sz
);
2514 fn size_hint(&self) -> (usize, Option
<usize>) {
2515 if self.v
.is_empty() {
2518 let n
= self.v
.len() / self.chunk_size
;
2519 let rem
= self.v
.len() % self.chunk_size
;
2520 let n
= if rem
> 0 { n + 1 }
else { n }
;
2526 fn count(self) -> usize {
2531 fn nth(&mut self, n
: usize) -> Option
<&'a
mut [T
]> {
2532 let (end
, overflow
) = n
.overflowing_mul(self.chunk_size
);
2533 if end
>= self.v
.len() || overflow
{
2537 // Can't underflow because of the check above
2538 let end
= self.v
.len() - end
;
2539 let start
= match end
.checked_sub(self.chunk_size
) {
2543 let tmp
= mem
::replace(&mut self.v
, &mut []);
2544 let (head
, tail
) = tmp
.split_at_mut(start
);
2545 let (nth
, _
) = tail
.split_at_mut(end
- start
);
2552 fn last(self) -> Option
<Self::Item
> {
2553 if self.v
.is_empty() {
2556 let rem
= self.v
.len() % self.chunk_size
;
2557 let end
= if rem
== 0 { self.chunk_size }
else { rem }
;
2558 Some(&mut self.v
[0..end
])
2563 unsafe fn __iterator_get_unchecked(&mut self, idx
: usize) -> Self::Item
{
2564 let end
= self.v
.len() - idx
* self.chunk_size
;
2565 let start
= match end
.checked_sub(self.chunk_size
) {
2567 Some(start
) => start
,
2569 // SAFETY: see comments for `RChunks::__iterator_get_unchecked` and
2570 // `ChunksMut::__iterator_get_unchecked`
2571 unsafe { from_raw_parts_mut(self.v.as_mut_ptr().add(start), end - start) }
2575 #[stable(feature = "rchunks", since = "1.31.0")]
2576 impl<'a
, T
> DoubleEndedIterator
for RChunksMut
<'a
, T
> {
2578 fn next_back(&mut self) -> Option
<&'a
mut [T
]> {
2579 if self.v
.is_empty() {
2582 let remainder
= self.v
.len() % self.chunk_size
;
2583 let sz
= if remainder
!= 0 { remainder }
else { self.chunk_size }
;
2584 let tmp
= mem
::replace(&mut self.v
, &mut []);
2585 let (head
, tail
) = tmp
.split_at_mut(sz
);
2592 fn nth_back(&mut self, n
: usize) -> Option
<Self::Item
> {
2593 let len
= self.len();
2598 // can't underflow because `n < len`
2599 let offset_from_end
= (len
- 1 - n
) * self.chunk_size
;
2600 let end
= self.v
.len() - offset_from_end
;
2601 let start
= end
.saturating_sub(self.chunk_size
);
2602 let (tmp
, tail
) = mem
::replace(&mut self.v
, &mut []).split_at_mut(end
);
2603 let (_
, nth_back
) = tmp
.split_at_mut(start
);
2610 #[stable(feature = "rchunks", since = "1.31.0")]
2611 impl<T
> ExactSizeIterator
for RChunksMut
<'_
, T
> {}
2613 #[unstable(feature = "trusted_len", issue = "37572")]
2614 unsafe impl<T
> TrustedLen
for RChunksMut
<'_
, T
> {}
2616 #[stable(feature = "rchunks", since = "1.31.0")]
2617 impl<T
> FusedIterator
for RChunksMut
<'_
, T
> {}
2620 #[unstable(feature = "trusted_random_access", issue = "none")]
2621 unsafe impl<'a
, T
> TrustedRandomAccess
for RChunksMut
<'a
, T
> {
2622 const MAY_HAVE_SIDE_EFFECT
: bool
= false;
2625 /// An iterator over a slice in (non-overlapping) chunks (`chunk_size` elements at a
2626 /// time), starting at the end of the slice.
2628 /// When the slice len is not evenly divided by the chunk size, the last
2629 /// up to `chunk_size-1` elements will be omitted but can be retrieved from
2630 /// the [`remainder`] function from the iterator.
2632 /// This struct is created by the [`rchunks_exact`] method on [slices].
2637 /// let slice = ['l', 'o', 'r', 'e', 'm'];
2638 /// let iter = slice.rchunks_exact(2);
2641 /// [`rchunks_exact`]: slice::rchunks_exact
2642 /// [`remainder`]: ChunksExact::remainder
2645 #[stable(feature = "rchunks", since = "1.31.0")]
2646 pub struct RChunksExact
<'a
, T
: 'a
> {
2652 impl<'a
, T
> RChunksExact
<'a
, T
> {
2654 pub(super) fn new(slice
: &'a
[T
], chunk_size
: usize) -> Self {
2655 let rem
= slice
.len() % chunk_size
;
2656 // SAFETY: 0 <= rem <= slice.len() by construction above
2657 let (fst
, snd
) = unsafe { slice.split_at_unchecked(rem) }
;
2658 Self { v: snd, rem: fst, chunk_size }
2661 /// Returns the remainder of the original slice that is not going to be
2662 /// returned by the iterator. The returned slice has at most `chunk_size-1`
2664 #[stable(feature = "rchunks", since = "1.31.0")]
2665 pub fn remainder(&self) -> &'a
[T
] {
2670 // FIXME(#26925) Remove in favor of `#[derive(Clone)]`
2671 #[stable(feature = "rchunks", since = "1.31.0")]
2672 impl<'a
, T
> Clone
for RChunksExact
<'a
, T
> {
2673 fn clone(&self) -> RChunksExact
<'a
, T
> {
2674 RChunksExact { v: self.v, rem: self.rem, chunk_size: self.chunk_size }
2678 #[stable(feature = "rchunks", since = "1.31.0")]
2679 impl<'a
, T
> Iterator
for RChunksExact
<'a
, T
> {
2680 type Item
= &'a
[T
];
2683 fn next(&mut self) -> Option
<&'a
[T
]> {
2684 if self.v
.len() < self.chunk_size
{
2687 let (fst
, snd
) = self.v
.split_at(self.v
.len() - self.chunk_size
);
2694 fn size_hint(&self) -> (usize, Option
<usize>) {
2695 let n
= self.v
.len() / self.chunk_size
;
2700 fn count(self) -> usize {
2705 fn nth(&mut self, n
: usize) -> Option
<Self::Item
> {
2706 let (end
, overflow
) = n
.overflowing_mul(self.chunk_size
);
2707 if end
>= self.v
.len() || overflow
{
2711 let (fst
, _
) = self.v
.split_at(self.v
.len() - end
);
2718 fn last(mut self) -> Option
<Self::Item
> {
2723 unsafe fn __iterator_get_unchecked(&mut self, idx
: usize) -> Self::Item
{
2724 let end
= self.v
.len() - idx
* self.chunk_size
;
2725 let start
= end
- self.chunk_size
;
2727 // SAFETY: mostmy identical to `Chunks::__iterator_get_unchecked`.
2728 unsafe { from_raw_parts(self.v.as_ptr().add(start), self.chunk_size) }
2732 #[stable(feature = "rchunks", since = "1.31.0")]
2733 impl<'a
, T
> DoubleEndedIterator
for RChunksExact
<'a
, T
> {
2735 fn next_back(&mut self) -> Option
<&'a
[T
]> {
2736 if self.v
.len() < self.chunk_size
{
2739 let (fst
, snd
) = self.v
.split_at(self.chunk_size
);
2746 fn nth_back(&mut self, n
: usize) -> Option
<Self::Item
> {
2747 let len
= self.len();
2752 // now that we know that `n` corresponds to a chunk,
2753 // none of these operations can underflow/overflow
2754 let offset
= (len
- n
) * self.chunk_size
;
2755 let start
= self.v
.len() - offset
;
2756 let end
= start
+ self.chunk_size
;
2757 let nth_back
= &self.v
[start
..end
];
2758 self.v
= &self.v
[end
..];
2764 #[stable(feature = "rchunks", since = "1.31.0")]
2765 impl<'a
, T
> ExactSizeIterator
for RChunksExact
<'a
, T
> {
2766 fn is_empty(&self) -> bool
{
2771 #[unstable(feature = "trusted_len", issue = "37572")]
2772 unsafe impl<T
> TrustedLen
for RChunksExact
<'_
, T
> {}
2774 #[stable(feature = "rchunks", since = "1.31.0")]
2775 impl<T
> FusedIterator
for RChunksExact
<'_
, T
> {}
2778 #[unstable(feature = "trusted_random_access", issue = "none")]
2779 unsafe impl<'a
, T
> TrustedRandomAccess
for RChunksExact
<'a
, T
> {
2780 const MAY_HAVE_SIDE_EFFECT
: bool
= false;
2783 /// An iterator over a slice in (non-overlapping) mutable chunks (`chunk_size`
2784 /// elements at a time), starting at the end of the slice.
2786 /// When the slice len is not evenly divided by the chunk size, the last up to
2787 /// `chunk_size-1` elements will be omitted but can be retrieved from the
2788 /// [`into_remainder`] function from the iterator.
2790 /// This struct is created by the [`rchunks_exact_mut`] method on [slices].
2795 /// let mut slice = ['l', 'o', 'r', 'e', 'm'];
2796 /// let iter = slice.rchunks_exact_mut(2);
2799 /// [`rchunks_exact_mut`]: slice::rchunks_exact_mut
2800 /// [`into_remainder`]: ChunksExactMut::into_remainder
2803 #[stable(feature = "rchunks", since = "1.31.0")]
2804 pub struct RChunksExactMut
<'a
, T
: 'a
> {
2810 impl<'a
, T
> RChunksExactMut
<'a
, T
> {
2812 pub(super) fn new(slice
: &'a
mut [T
], chunk_size
: usize) -> Self {
2813 let rem
= slice
.len() % chunk_size
;
2814 // SAFETY: 0 <= rem <= slice.len() by construction above
2815 let (fst
, snd
) = unsafe { slice.split_at_mut_unchecked(rem) }
;
2816 Self { v: snd, rem: fst, chunk_size }
2819 /// Returns the remainder of the original slice that is not going to be
2820 /// returned by the iterator. The returned slice has at most `chunk_size-1`
2822 #[stable(feature = "rchunks", since = "1.31.0")]
2823 pub fn into_remainder(self) -> &'a
mut [T
] {
2828 #[stable(feature = "rchunks", since = "1.31.0")]
2829 impl<'a
, T
> Iterator
for RChunksExactMut
<'a
, T
> {
2830 type Item
= &'a
mut [T
];
2833 fn next(&mut self) -> Option
<&'a
mut [T
]> {
2834 if self.v
.len() < self.chunk_size
{
2837 let tmp
= mem
::replace(&mut self.v
, &mut []);
2838 let tmp_len
= tmp
.len();
2839 let (head
, tail
) = tmp
.split_at_mut(tmp_len
- self.chunk_size
);
2846 fn size_hint(&self) -> (usize, Option
<usize>) {
2847 let n
= self.v
.len() / self.chunk_size
;
2852 fn count(self) -> usize {
2857 fn nth(&mut self, n
: usize) -> Option
<&'a
mut [T
]> {
2858 let (end
, overflow
) = n
.overflowing_mul(self.chunk_size
);
2859 if end
>= self.v
.len() || overflow
{
2863 let tmp
= mem
::replace(&mut self.v
, &mut []);
2864 let tmp_len
= tmp
.len();
2865 let (fst
, _
) = tmp
.split_at_mut(tmp_len
- end
);
2872 fn last(mut self) -> Option
<Self::Item
> {
2877 unsafe fn __iterator_get_unchecked(&mut self, idx
: usize) -> Self::Item
{
2878 let end
= self.v
.len() - idx
* self.chunk_size
;
2879 let start
= end
- self.chunk_size
;
2880 // SAFETY: see comments for `RChunksMut::__iterator_get_unchecked`.
2881 unsafe { from_raw_parts_mut(self.v.as_mut_ptr().add(start), self.chunk_size) }
2885 #[stable(feature = "rchunks", since = "1.31.0")]
2886 impl<'a
, T
> DoubleEndedIterator
for RChunksExactMut
<'a
, T
> {
2888 fn next_back(&mut self) -> Option
<&'a
mut [T
]> {
2889 if self.v
.len() < self.chunk_size
{
2892 let tmp
= mem
::replace(&mut self.v
, &mut []);
2893 let (head
, tail
) = tmp
.split_at_mut(self.chunk_size
);
2900 fn nth_back(&mut self, n
: usize) -> Option
<Self::Item
> {
2901 let len
= self.len();
2906 // now that we know that `n` corresponds to a chunk,
2907 // none of these operations can underflow/overflow
2908 let offset
= (len
- n
) * self.chunk_size
;
2909 let start
= self.v
.len() - offset
;
2910 let end
= start
+ self.chunk_size
;
2911 let (tmp
, tail
) = mem
::replace(&mut self.v
, &mut []).split_at_mut(end
);
2912 let (_
, nth_back
) = tmp
.split_at_mut(start
);
2919 #[stable(feature = "rchunks", since = "1.31.0")]
2920 impl<T
> ExactSizeIterator
for RChunksExactMut
<'_
, T
> {
2921 fn is_empty(&self) -> bool
{
2926 #[unstable(feature = "trusted_len", issue = "37572")]
2927 unsafe impl<T
> TrustedLen
for RChunksExactMut
<'_
, T
> {}
2929 #[stable(feature = "rchunks", since = "1.31.0")]
2930 impl<T
> FusedIterator
for RChunksExactMut
<'_
, T
> {}
2933 #[unstable(feature = "trusted_random_access", issue = "none")]
2934 unsafe impl<'a
, T
> TrustedRandomAccess
for RChunksExactMut
<'a
, T
> {
2935 const MAY_HAVE_SIDE_EFFECT
: bool
= false;
2939 #[unstable(feature = "trusted_random_access", issue = "none")]
2940 unsafe impl<'a
, T
> TrustedRandomAccess
for Iter
<'a
, T
> {
2941 const MAY_HAVE_SIDE_EFFECT
: bool
= false;
2945 #[unstable(feature = "trusted_random_access", issue = "none")]
2946 unsafe impl<'a
, T
> TrustedRandomAccess
for IterMut
<'a
, T
> {
2947 const MAY_HAVE_SIDE_EFFECT
: bool
= false;
2950 /// An iterator over slice in (non-overlapping) chunks separated by a predicate.
2952 /// This struct is created by the [`group_by`] method on [slices].
2954 /// [`group_by`]: slice::group_by
2956 #[unstable(feature = "slice_group_by", issue = "80552")]
2957 pub struct GroupBy
<'a
, T
: 'a
, P
> {
2962 #[unstable(feature = "slice_group_by", issue = "80552")]
2963 impl<'a
, T
: 'a
, P
> GroupBy
<'a
, T
, P
> {
2964 pub(super) fn new(slice
: &'a
[T
], predicate
: P
) -> Self {
2965 GroupBy { slice, predicate }
2969 #[unstable(feature = "slice_group_by", issue = "80552")]
2970 impl<'a
, T
: 'a
, P
> Iterator
for GroupBy
<'a
, T
, P
>
2972 P
: FnMut(&T
, &T
) -> bool
,
2974 type Item
= &'a
[T
];
2977 fn next(&mut self) -> Option
<Self::Item
> {
2978 if self.slice
.is_empty() {
2982 let mut iter
= self.slice
.windows(2);
2983 while let Some([l
, r
]) = iter
.next() {
2984 if (self.predicate
)(l
, r
) { len += 1 }
else { break }
2986 let (head
, tail
) = self.slice
.split_at(len
);
2993 fn size_hint(&self) -> (usize, Option
<usize>) {
2994 if self.slice
.is_empty() { (0, Some(0)) }
else { (1, Some(self.slice.len())) }
2998 fn last(mut self) -> Option
<Self::Item
> {
3003 #[unstable(feature = "slice_group_by", issue = "80552")]
3004 impl<'a
, T
: 'a
, P
> DoubleEndedIterator
for GroupBy
<'a
, T
, P
>
3006 P
: FnMut(&T
, &T
) -> bool
,
3009 fn next_back(&mut self) -> Option
<Self::Item
> {
3010 if self.slice
.is_empty() {
3014 let mut iter
= self.slice
.windows(2);
3015 while let Some([l
, r
]) = iter
.next_back() {
3016 if (self.predicate
)(l
, r
) { len += 1 }
else { break }
3018 let (head
, tail
) = self.slice
.split_at(self.slice
.len() - len
);
3025 #[unstable(feature = "slice_group_by", issue = "80552")]
3026 impl<'a
, T
: 'a
, P
> FusedIterator
for GroupBy
<'a
, T
, P
> where P
: FnMut(&T
, &T
) -> bool {}
3028 #[unstable(feature = "slice_group_by", issue = "80552")]
3029 impl<'a
, T
: 'a
+ fmt
::Debug
, P
> fmt
::Debug
for GroupBy
<'a
, T
, P
> {
3030 fn fmt(&self, f
: &mut fmt
::Formatter
<'_
>) -> fmt
::Result
{
3031 f
.debug_struct("GroupBy").field("slice", &self.slice
).finish()
3035 /// An iterator over slice in (non-overlapping) mutable chunks separated
3038 /// This struct is created by the [`group_by_mut`] method on [slices].
3040 /// [`group_by_mut`]: slice::group_by_mut
3042 #[unstable(feature = "slice_group_by", issue = "80552")]
3043 pub struct GroupByMut
<'a
, T
: 'a
, P
> {
3048 #[unstable(feature = "slice_group_by", issue = "80552")]
3049 impl<'a
, T
: 'a
, P
> GroupByMut
<'a
, T
, P
> {
3050 pub(super) fn new(slice
: &'a
mut [T
], predicate
: P
) -> Self {
3051 GroupByMut { slice, predicate }
3055 #[unstable(feature = "slice_group_by", issue = "80552")]
3056 impl<'a
, T
: 'a
, P
> Iterator
for GroupByMut
<'a
, T
, P
>
3058 P
: FnMut(&T
, &T
) -> bool
,
3060 type Item
= &'a
mut [T
];
3063 fn next(&mut self) -> Option
<Self::Item
> {
3064 if self.slice
.is_empty() {
3068 let mut iter
= self.slice
.windows(2);
3069 while let Some([l
, r
]) = iter
.next() {
3070 if (self.predicate
)(l
, r
) { len += 1 }
else { break }
3072 let slice
= mem
::take(&mut self.slice
);
3073 let (head
, tail
) = slice
.split_at_mut(len
);
3080 fn size_hint(&self) -> (usize, Option
<usize>) {
3081 if self.slice
.is_empty() { (0, Some(0)) }
else { (1, Some(self.slice.len())) }
3085 fn last(mut self) -> Option
<Self::Item
> {
3090 #[unstable(feature = "slice_group_by", issue = "80552")]
3091 impl<'a
, T
: 'a
, P
> DoubleEndedIterator
for GroupByMut
<'a
, T
, P
>
3093 P
: FnMut(&T
, &T
) -> bool
,
3096 fn next_back(&mut self) -> Option
<Self::Item
> {
3097 if self.slice
.is_empty() {
3101 let mut iter
= self.slice
.windows(2);
3102 while let Some([l
, r
]) = iter
.next_back() {
3103 if (self.predicate
)(l
, r
) { len += 1 }
else { break }
3105 let slice
= mem
::take(&mut self.slice
);
3106 let (head
, tail
) = slice
.split_at_mut(slice
.len() - len
);
3113 #[unstable(feature = "slice_group_by", issue = "80552")]
3114 impl<'a
, T
: 'a
, P
> FusedIterator
for GroupByMut
<'a
, T
, P
> where P
: FnMut(&T
, &T
) -> bool {}
3116 #[unstable(feature = "slice_group_by", issue = "80552")]
3117 impl<'a
, T
: 'a
+ fmt
::Debug
, P
> fmt
::Debug
for GroupByMut
<'a
, T
, P
> {
3118 fn fmt(&self, f
: &mut fmt
::Formatter
<'_
>) -> fmt
::Result
{
3119 f
.debug_struct("GroupByMut").field("slice", &self.slice
).finish()