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
;
10 use crate::iter
::{FusedIterator, TrustedLen, TrustedRandomAccess, TrustedRandomAccessNoCoerce}
;
11 use crate::marker
::{PhantomData, Send, Sized, Sync}
;
12 use crate::mem
::{self, SizedTypeProperties}
;
13 use crate::num
::NonZeroUsize
;
14 use crate::ptr
::NonNull
;
16 use super::{from_raw_parts, from_raw_parts_mut}
;
18 #[stable(feature = "rust1", since = "1.0.0")]
19 impl<'a
, T
> IntoIterator
for &'a
[T
] {
21 type IntoIter
= Iter
<'a
, T
>;
23 fn into_iter(self) -> Iter
<'a
, T
> {
28 #[stable(feature = "rust1", since = "1.0.0")]
29 impl<'a
, T
> IntoIterator
for &'a
mut [T
] {
30 type Item
= &'a
mut T
;
31 type IntoIter
= IterMut
<'a
, T
>;
33 fn into_iter(self) -> IterMut
<'a
, T
> {
38 /// Immutable slice iterator
40 /// This struct is created by the [`iter`] method on [slices].
47 /// // First, we declare a type which has `iter` method to get the `Iter` struct (`&[usize]` here):
48 /// let slice = &[1, 2, 3];
50 /// // Then, we iterate over it:
51 /// for element in slice.iter() {
52 /// println!("{element}");
56 /// [`iter`]: slice::iter
58 #[stable(feature = "rust1", since = "1.0.0")]
59 #[must_use = "iterators are lazy and do nothing unless consumed"]
60 pub struct Iter
<'a
, T
: 'a
> {
62 end
: *const T
, // If T is a ZST, this is actually ptr+len. This encoding is picked so that
63 // ptr == end is a quick test for the Iterator being empty, that works
64 // for both ZST and non-ZST.
65 _marker
: PhantomData
<&'a T
>,
68 #[stable(feature = "core_impl_debug", since = "1.9.0")]
69 impl<T
: fmt
::Debug
> fmt
::Debug
for Iter
<'_
, T
> {
70 fn fmt(&self, f
: &mut fmt
::Formatter
<'_
>) -> fmt
::Result
{
71 f
.debug_tuple("Iter").field(&self.as_slice()).finish()
75 #[stable(feature = "rust1", since = "1.0.0")]
76 unsafe impl<T
: Sync
> Sync
for Iter
<'_
, T
> {}
77 #[stable(feature = "rust1", since = "1.0.0")]
78 unsafe impl<T
: Sync
> Send
for Iter
<'_
, T
> {}
80 impl<'a
, T
> Iter
<'a
, T
> {
82 pub(super) fn new(slice
: &'a
[T
]) -> Self {
83 let ptr
= slice
.as_ptr();
84 // SAFETY: Similar to `IterMut::new`.
86 assume(!ptr
.is_null());
89 if T
::IS_ZST { ptr.wrapping_byte_add(slice.len()) }
else { ptr.add(slice.len()) }
;
91 Self { ptr: NonNull::new_unchecked(ptr as *mut T), end, _marker: PhantomData }
95 /// Views the underlying data as a subslice of the original data.
97 /// This has the same lifetime as the original slice, and so the
98 /// iterator can continue to be used while this exists.
105 /// // First, we declare a type which has the `iter` method to get the `Iter`
106 /// // struct (`&[usize]` here):
107 /// let slice = &[1, 2, 3];
109 /// // Then, we get the iterator:
110 /// let mut iter = slice.iter();
111 /// // So if we print what `as_slice` method returns here, we have "[1, 2, 3]":
112 /// println!("{:?}", iter.as_slice());
114 /// // Next, we move to the second element of the slice:
116 /// // Now `as_slice` returns "[2, 3]":
117 /// println!("{:?}", iter.as_slice());
120 #[stable(feature = "iter_to_slice", since = "1.4.0")]
122 pub fn as_slice(&self) -> &'a
[T
] {
127 iterator
! {struct Iter -> *const T, &'a T, const, {/* no mut */}
, {
128 fn is_sorted_by
<F
>(self, mut compare
: F
) -> bool
131 F
: FnMut(&Self::Item
, &Self::Item
) -> Option
<Ordering
>,
133 self.as_slice().windows(2).all(|w
| {
134 compare(&&w
[0], &&w
[1]).map(|o
| o
!= Ordering
::Greater
).unwrap_or(false)
139 #[stable(feature = "rust1", since = "1.0.0")]
140 impl<T
> Clone
for Iter
<'_
, T
> {
142 fn clone(&self) -> Self {
143 Iter { ptr: self.ptr, end: self.end, _marker: self._marker }
147 #[stable(feature = "slice_iter_as_ref", since = "1.13.0")]
148 impl<T
> AsRef
<[T
]> for Iter
<'_
, T
> {
150 fn as_ref(&self) -> &[T
] {
155 /// Mutable slice iterator.
157 /// This struct is created by the [`iter_mut`] method on [slices].
164 /// // First, we declare a type which has `iter_mut` method to get the `IterMut`
165 /// // struct (`&[usize]` here):
166 /// let mut slice = &mut [1, 2, 3];
168 /// // Then, we iterate over it and increment each element value:
169 /// for element in slice.iter_mut() {
173 /// // We now have "[2, 3, 4]":
174 /// println!("{slice:?}");
177 /// [`iter_mut`]: slice::iter_mut
179 #[stable(feature = "rust1", since = "1.0.0")]
180 #[must_use = "iterators are lazy and do nothing unless consumed"]
181 pub struct IterMut
<'a
, T
: 'a
> {
183 end
: *mut T
, // If T is a ZST, this is actually ptr+len. This encoding is picked so that
184 // ptr == end is a quick test for the Iterator being empty, that works
185 // for both ZST and non-ZST.
186 _marker
: PhantomData
<&'a
mut T
>,
189 #[stable(feature = "core_impl_debug", since = "1.9.0")]
190 impl<T
: fmt
::Debug
> fmt
::Debug
for IterMut
<'_
, T
> {
191 fn fmt(&self, f
: &mut fmt
::Formatter
<'_
>) -> fmt
::Result
{
192 f
.debug_tuple("IterMut").field(&self.make_slice()).finish()
196 #[stable(feature = "rust1", since = "1.0.0")]
197 unsafe impl<T
: Sync
> Sync
for IterMut
<'_
, T
> {}
198 #[stable(feature = "rust1", since = "1.0.0")]
199 unsafe impl<T
: Send
> Send
for IterMut
<'_
, T
> {}
201 impl<'a
, T
> IterMut
<'a
, T
> {
203 pub(super) fn new(slice
: &'a
mut [T
]) -> Self {
204 let ptr
= slice
.as_mut_ptr();
205 // SAFETY: There are several things here:
207 // `ptr` has been obtained by `slice.as_ptr()` where `slice` is a valid
208 // reference thus it is non-NUL and safe to use and pass to
209 // `NonNull::new_unchecked` .
211 // Adding `slice.len()` to the starting pointer gives a pointer
212 // at the end of `slice`. `end` will never be dereferenced, only checked
213 // for direct pointer equality with `ptr` to check if the iterator is
216 // In the case of a ZST, the end pointer is just the start pointer plus
217 // the length, to also allows for the fast `ptr == end` check.
219 // See the `next_unchecked!` and `is_empty!` macros as well as the
220 // `post_inc_start` method for more information.
222 assume(!ptr
.is_null());
225 if T
::IS_ZST { ptr.wrapping_byte_add(slice.len()) }
else { ptr.add(slice.len()) }
;
227 Self { ptr: NonNull::new_unchecked(ptr), end, _marker: PhantomData }
231 /// Views the underlying data as a subslice of the original data.
233 /// To avoid creating `&mut` references that alias, this is forced
234 /// to consume the iterator.
241 /// // First, we declare a type which has `iter_mut` method to get the `IterMut`
242 /// // struct (`&[usize]` here):
243 /// let mut slice = &mut [1, 2, 3];
246 /// // Then, we get the iterator:
247 /// let mut iter = slice.iter_mut();
248 /// // We move to next element:
250 /// // So if we print what `into_slice` method returns here, we have "[2, 3]":
251 /// println!("{:?}", iter.into_slice());
254 /// // Now let's modify a value of the slice:
256 /// // First we get back the iterator:
257 /// let mut iter = slice.iter_mut();
258 /// // We change the value of the first element of the slice returned by the `next` method:
259 /// *iter.next().unwrap() += 1;
261 /// // Now slice is "[2, 2, 3]":
262 /// println!("{slice:?}");
264 #[must_use = "`self` will be dropped if the result is not used"]
265 #[stable(feature = "iter_to_slice", since = "1.4.0")]
266 pub fn into_slice(self) -> &'a
mut [T
] {
267 // SAFETY: the iterator was created from a mutable slice with pointer
268 // `self.ptr` and length `len!(self)`. This guarantees that all the prerequisites
269 // for `from_raw_parts_mut` are fulfilled.
270 unsafe { from_raw_parts_mut(self.ptr.as_ptr(), len!(self)) }
273 /// Views the underlying data as a subslice of the original data.
275 /// To avoid creating `&mut [T]` references that alias, the returned slice
276 /// borrows its lifetime from the iterator the method is applied on.
283 /// let mut slice: &mut [usize] = &mut [1, 2, 3];
285 /// // First, we get the iterator:
286 /// let mut iter = slice.iter_mut();
287 /// // So if we check what the `as_slice` method returns here, we have "[1, 2, 3]":
288 /// assert_eq!(iter.as_slice(), &[1, 2, 3]);
290 /// // Next, we move to the second element of the slice:
292 /// // Now `as_slice` returns "[2, 3]":
293 /// assert_eq!(iter.as_slice(), &[2, 3]);
296 #[stable(feature = "slice_iter_mut_as_slice", since = "1.53.0")]
298 pub fn as_slice(&self) -> &[T
] {
302 /// Views the underlying data as a mutable subslice of the original data.
304 /// To avoid creating `&mut [T]` references that alias, the returned slice
305 /// borrows its lifetime from the iterator the method is applied on.
312 /// #![feature(slice_iter_mut_as_mut_slice)]
314 /// let mut slice: &mut [usize] = &mut [1, 2, 3];
316 /// // First, we get the iterator:
317 /// let mut iter = slice.iter_mut();
318 /// // Then, we get a mutable slice from it:
319 /// let mut_slice = iter.as_mut_slice();
320 /// // So if we check what the `as_mut_slice` method returned, we have "[1, 2, 3]":
321 /// assert_eq!(mut_slice, &mut [1, 2, 3]);
323 /// // We can use it to mutate the slice:
324 /// mut_slice[0] = 4;
325 /// mut_slice[2] = 5;
327 /// // Next, we can move to the second element of the slice, checking that
328 /// // it yields the value we just wrote:
329 /// assert_eq!(iter.next(), Some(&mut 4));
330 /// // Now `as_mut_slice` returns "[2, 5]":
331 /// assert_eq!(iter.as_mut_slice(), &mut [2, 5]);
334 // FIXME: Uncomment the `AsMut<[T]>` impl when this gets stabilized.
335 #[unstable(feature = "slice_iter_mut_as_mut_slice", issue = "93079")]
336 pub fn as_mut_slice(&mut self) -> &mut [T
] {
337 // SAFETY: the iterator was created from a mutable slice with pointer
338 // `self.ptr` and length `len!(self)`. This guarantees that all the prerequisites
339 // for `from_raw_parts_mut` are fulfilled.
340 unsafe { from_raw_parts_mut(self.ptr.as_ptr(), len!(self)) }
344 #[stable(feature = "slice_iter_mut_as_slice", since = "1.53.0")]
345 impl<T
> AsRef
<[T
]> for IterMut
<'_
, T
> {
347 fn as_ref(&self) -> &[T
] {
352 // #[stable(feature = "slice_iter_mut_as_mut_slice", since = "FIXME")]
353 // impl<T> AsMut<[T]> for IterMut<'_, T> {
354 // fn as_mut(&mut self) -> &mut [T] {
355 // self.as_mut_slice()
359 iterator
! {struct IterMut -> *mut T, &'a mut T, mut, {mut}
, {}
}
361 /// An internal abstraction over the splitting iterators, so that
362 /// splitn, splitn_mut etc can be implemented once.
364 pub(super) trait SplitIter
: DoubleEndedIterator
{
365 /// Marks the underlying iterator as complete, extracting the remaining
366 /// portion of the slice.
367 fn finish(&mut self) -> Option
<Self::Item
>;
370 /// An iterator over subslices separated by elements that match a predicate
373 /// This struct is created by the [`split`] method on [slices].
378 /// let slice = [10, 40, 33, 20];
379 /// let mut iter = slice.split(|num| num % 3 == 0);
382 /// [`split`]: slice::split
384 #[stable(feature = "rust1", since = "1.0.0")]
385 #[must_use = "iterators are lazy and do nothing unless consumed"]
386 pub struct Split
<'a
, T
: 'a
, P
>
388 P
: FnMut(&T
) -> bool
,
390 // Used for `SplitWhitespace` and `SplitAsciiWhitespace` `as_str` methods
391 pub(crate) v
: &'a
[T
],
393 // Used for `SplitAsciiWhitespace` `as_str` method
394 pub(crate) finished
: bool
,
397 impl<'a
, T
: 'a
, P
: FnMut(&T
) -> bool
> Split
<'a
, T
, P
> {
399 pub(super) fn new(slice
: &'a
[T
], pred
: P
) -> Self {
400 Self { v: slice, pred, finished: false }
402 /// Returns a slice which contains items not yet handled by split.
406 /// #![feature(split_as_slice)]
407 /// let slice = [1,2,3,4,5];
408 /// let mut split = slice.split(|v| v % 2 == 0);
409 /// assert!(split.next().is_some());
410 /// assert_eq!(split.as_slice(), &[3,4,5]);
412 #[unstable(feature = "split_as_slice", issue = "96137")]
413 pub fn as_slice(&self) -> &'a
[T
] {
414 if self.finished { &[] }
else { &self.v }
418 #[stable(feature = "core_impl_debug", since = "1.9.0")]
419 impl<T
: fmt
::Debug
, P
> fmt
::Debug
for Split
<'_
, T
, P
>
421 P
: FnMut(&T
) -> bool
,
423 fn fmt(&self, f
: &mut fmt
::Formatter
<'_
>) -> fmt
::Result
{
424 f
.debug_struct("Split").field("v", &self.v
).field("finished", &self.finished
).finish()
428 // FIXME(#26925) Remove in favor of `#[derive(Clone)]`
429 #[stable(feature = "rust1", since = "1.0.0")]
430 impl<T
, P
> Clone
for Split
<'_
, T
, P
>
432 P
: Clone
+ FnMut(&T
) -> bool
,
434 fn clone(&self) -> Self {
435 Split { v: self.v, pred: self.pred.clone(), finished: self.finished }
439 #[stable(feature = "rust1", since = "1.0.0")]
440 impl<'a
, T
, P
> Iterator
for Split
<'a
, T
, P
>
442 P
: FnMut(&T
) -> bool
,
447 fn next(&mut self) -> Option
<&'a
[T
]> {
452 match self.v
.iter().position(|x
| (self.pred
)(x
)) {
453 None
=> self.finish(),
455 let ret
= Some(&self.v
[..idx
]);
456 self.v
= &self.v
[idx
+ 1..];
463 fn size_hint(&self) -> (usize, Option
<usize>) {
467 // If the predicate doesn't match anything, we yield one slice.
468 // If it matches every element, we yield `len() + 1` empty slices.
469 (1, Some(self.v
.len() + 1))
474 #[stable(feature = "rust1", since = "1.0.0")]
475 impl<'a
, T
, P
> DoubleEndedIterator
for Split
<'a
, T
, P
>
477 P
: FnMut(&T
) -> bool
,
480 fn next_back(&mut self) -> Option
<&'a
[T
]> {
485 match self.v
.iter().rposition(|x
| (self.pred
)(x
)) {
486 None
=> self.finish(),
488 let ret
= Some(&self.v
[idx
+ 1..]);
489 self.v
= &self.v
[..idx
];
496 impl<'a
, T
, P
> SplitIter
for Split
<'a
, T
, P
>
498 P
: FnMut(&T
) -> bool
,
501 fn finish(&mut self) -> Option
<&'a
[T
]> {
505 self.finished
= true;
511 #[stable(feature = "fused", since = "1.26.0")]
512 impl<T
, P
> FusedIterator
for Split
<'_
, T
, P
> where P
: FnMut(&T
) -> bool {}
514 /// An iterator over subslices separated by elements that match a predicate
515 /// function. Unlike `Split`, it contains the matched part as a terminator
518 /// This struct is created by the [`split_inclusive`] method on [slices].
523 /// let slice = [10, 40, 33, 20];
524 /// let mut iter = slice.split_inclusive(|num| num % 3 == 0);
527 /// [`split_inclusive`]: slice::split_inclusive
529 #[stable(feature = "split_inclusive", since = "1.51.0")]
530 #[must_use = "iterators are lazy and do nothing unless consumed"]
531 pub struct SplitInclusive
<'a
, T
: 'a
, P
>
533 P
: FnMut(&T
) -> bool
,
540 impl<'a
, T
: 'a
, P
: FnMut(&T
) -> bool
> SplitInclusive
<'a
, T
, P
> {
542 pub(super) fn new(slice
: &'a
[T
], pred
: P
) -> Self {
543 let finished
= slice
.is_empty();
544 Self { v: slice, pred, finished }
548 #[stable(feature = "split_inclusive", since = "1.51.0")]
549 impl<T
: fmt
::Debug
, P
> fmt
::Debug
for SplitInclusive
<'_
, T
, P
>
551 P
: FnMut(&T
) -> bool
,
553 fn fmt(&self, f
: &mut fmt
::Formatter
<'_
>) -> fmt
::Result
{
554 f
.debug_struct("SplitInclusive")
556 .field("finished", &self.finished
)
561 // FIXME(#26925) Remove in favor of `#[derive(Clone)]`
562 #[stable(feature = "split_inclusive", since = "1.51.0")]
563 impl<T
, P
> Clone
for SplitInclusive
<'_
, T
, P
>
565 P
: Clone
+ FnMut(&T
) -> bool
,
567 fn clone(&self) -> Self {
568 SplitInclusive { v: self.v, pred: self.pred.clone(), finished: self.finished }
572 #[stable(feature = "split_inclusive", since = "1.51.0")]
573 impl<'a
, T
, P
> Iterator
for SplitInclusive
<'a
, T
, P
>
575 P
: FnMut(&T
) -> bool
,
580 fn next(&mut self) -> Option
<&'a
[T
]> {
586 self.v
.iter().position(|x
| (self.pred
)(x
)).map(|idx
| idx
+ 1).unwrap_or(self.v
.len());
587 if idx
== self.v
.len() {
588 self.finished
= true;
590 let ret
= Some(&self.v
[..idx
]);
591 self.v
= &self.v
[idx
..];
596 fn size_hint(&self) -> (usize, Option
<usize>) {
600 // If the predicate doesn't match anything, we yield one slice.
601 // If it matches every element, we yield `len()` one-element slices,
602 // or a single empty slice.
603 (1, Some(cmp
::max(1, self.v
.len())))
608 #[stable(feature = "split_inclusive", since = "1.51.0")]
609 impl<'a
, T
, P
> DoubleEndedIterator
for SplitInclusive
<'a
, T
, P
>
611 P
: FnMut(&T
) -> bool
,
614 fn next_back(&mut self) -> Option
<&'a
[T
]> {
619 // The last index of self.v is already checked and found to match
620 // by the last iteration, so we start searching a new match
621 // one index to the left.
622 let remainder
= if self.v
.is_empty() { &[] }
else { &self.v[..(self.v.len() - 1)] }
;
623 let idx
= remainder
.iter().rposition(|x
| (self.pred
)(x
)).map(|idx
| idx
+ 1).unwrap_or(0);
625 self.finished
= true;
627 let ret
= Some(&self.v
[idx
..]);
628 self.v
= &self.v
[..idx
];
633 #[stable(feature = "split_inclusive", since = "1.51.0")]
634 impl<T
, P
> FusedIterator
for SplitInclusive
<'_
, T
, P
> where P
: FnMut(&T
) -> bool {}
636 /// An iterator over the mutable subslices of the vector which are separated
637 /// by elements that match `pred`.
639 /// This struct is created by the [`split_mut`] method on [slices].
644 /// let mut v = [10, 40, 30, 20, 60, 50];
645 /// let iter = v.split_mut(|num| *num % 3 == 0);
648 /// [`split_mut`]: slice::split_mut
650 #[stable(feature = "rust1", since = "1.0.0")]
651 #[must_use = "iterators are lazy and do nothing unless consumed"]
652 pub struct SplitMut
<'a
, T
: 'a
, P
>
654 P
: FnMut(&T
) -> bool
,
661 impl<'a
, T
: 'a
, P
: FnMut(&T
) -> bool
> SplitMut
<'a
, T
, P
> {
663 pub(super) fn new(slice
: &'a
mut [T
], pred
: P
) -> Self {
664 Self { v: slice, pred, finished: false }
668 #[stable(feature = "core_impl_debug", since = "1.9.0")]
669 impl<T
: fmt
::Debug
, P
> fmt
::Debug
for SplitMut
<'_
, T
, P
>
671 P
: FnMut(&T
) -> bool
,
673 fn fmt(&self, f
: &mut fmt
::Formatter
<'_
>) -> fmt
::Result
{
674 f
.debug_struct("SplitMut").field("v", &self.v
).field("finished", &self.finished
).finish()
678 impl<'a
, T
, P
> SplitIter
for SplitMut
<'a
, T
, P
>
680 P
: FnMut(&T
) -> bool
,
683 fn finish(&mut self) -> Option
<&'a
mut [T
]> {
687 self.finished
= true;
688 Some(mem
::replace(&mut self.v
, &mut []))
693 #[stable(feature = "rust1", since = "1.0.0")]
694 impl<'a
, T
, P
> Iterator
for SplitMut
<'a
, T
, P
>
696 P
: FnMut(&T
) -> bool
,
698 type Item
= &'a
mut [T
];
701 fn next(&mut self) -> Option
<&'a
mut [T
]> {
706 match self.v
.iter().position(|x
| (self.pred
)(x
)) {
707 None
=> self.finish(),
709 let tmp
= mem
::take(&mut self.v
);
710 // idx is the index of the element we are splitting on. We want to set self to the
711 // region after idx, and return the subslice before and not including idx.
712 // So first we split after idx
713 let (head
, tail
) = tmp
.split_at_mut(idx
+ 1);
715 // Then return the subslice up to but not including the found element
716 Some(&mut head
[..idx
])
722 fn size_hint(&self) -> (usize, Option
<usize>) {
726 // If the predicate doesn't match anything, we yield one slice.
727 // If it matches every element, we yield `len() + 1` empty slices.
728 (1, Some(self.v
.len() + 1))
733 #[stable(feature = "rust1", since = "1.0.0")]
734 impl<'a
, T
, P
> DoubleEndedIterator
for SplitMut
<'a
, T
, P
>
736 P
: FnMut(&T
) -> bool
,
739 fn next_back(&mut self) -> Option
<&'a
mut [T
]> {
745 // work around borrowck limitations
746 let pred
= &mut self.pred
;
747 self.v
.iter().rposition(|x
| (*pred
)(x
))
750 None
=> self.finish(),
752 let tmp
= mem
::replace(&mut self.v
, &mut []);
753 let (head
, tail
) = tmp
.split_at_mut(idx
);
761 #[stable(feature = "fused", since = "1.26.0")]
762 impl<T
, P
> FusedIterator
for SplitMut
<'_
, T
, P
> where P
: FnMut(&T
) -> bool {}
764 /// An iterator over the mutable subslices of the vector which are separated
765 /// by elements that match `pred`. Unlike `SplitMut`, it contains the matched
766 /// parts in the ends of the subslices.
768 /// This struct is created by the [`split_inclusive_mut`] method on [slices].
773 /// let mut v = [10, 40, 30, 20, 60, 50];
774 /// let iter = v.split_inclusive_mut(|num| *num % 3 == 0);
777 /// [`split_inclusive_mut`]: slice::split_inclusive_mut
779 #[stable(feature = "split_inclusive", since = "1.51.0")]
780 #[must_use = "iterators are lazy and do nothing unless consumed"]
781 pub struct SplitInclusiveMut
<'a
, T
: 'a
, P
>
783 P
: FnMut(&T
) -> bool
,
790 impl<'a
, T
: 'a
, P
: FnMut(&T
) -> bool
> SplitInclusiveMut
<'a
, T
, P
> {
792 pub(super) fn new(slice
: &'a
mut [T
], pred
: P
) -> Self {
793 let finished
= slice
.is_empty();
794 Self { v: slice, pred, finished }
798 #[stable(feature = "split_inclusive", since = "1.51.0")]
799 impl<T
: fmt
::Debug
, P
> fmt
::Debug
for SplitInclusiveMut
<'_
, T
, P
>
801 P
: FnMut(&T
) -> bool
,
803 fn fmt(&self, f
: &mut fmt
::Formatter
<'_
>) -> fmt
::Result
{
804 f
.debug_struct("SplitInclusiveMut")
806 .field("finished", &self.finished
)
811 #[stable(feature = "split_inclusive", since = "1.51.0")]
812 impl<'a
, T
, P
> Iterator
for SplitInclusiveMut
<'a
, T
, P
>
814 P
: FnMut(&T
) -> bool
,
816 type Item
= &'a
mut [T
];
819 fn next(&mut self) -> Option
<&'a
mut [T
]> {
825 // work around borrowck limitations
826 let pred
= &mut self.pred
;
827 self.v
.iter().position(|x
| (*pred
)(x
))
829 let idx
= idx_opt
.map(|idx
| idx
+ 1).unwrap_or(self.v
.len());
830 if idx
== self.v
.len() {
831 self.finished
= true;
833 let tmp
= mem
::replace(&mut self.v
, &mut []);
834 let (head
, tail
) = tmp
.split_at_mut(idx
);
840 fn size_hint(&self) -> (usize, Option
<usize>) {
844 // If the predicate doesn't match anything, we yield one slice.
845 // If it matches every element, we yield `len()` one-element slices,
846 // or a single empty slice.
847 (1, Some(cmp
::max(1, self.v
.len())))
852 #[stable(feature = "split_inclusive", since = "1.51.0")]
853 impl<'a
, T
, P
> DoubleEndedIterator
for SplitInclusiveMut
<'a
, T
, P
>
855 P
: FnMut(&T
) -> bool
,
858 fn next_back(&mut self) -> Option
<&'a
mut [T
]> {
863 let idx_opt
= if self.v
.is_empty() {
866 // work around borrowck limitations
867 let pred
= &mut self.pred
;
869 // The last index of self.v is already checked and found to match
870 // by the last iteration, so we start searching a new match
871 // one index to the left.
872 let remainder
= &self.v
[..(self.v
.len() - 1)];
873 remainder
.iter().rposition(|x
| (*pred
)(x
))
875 let idx
= idx_opt
.map(|idx
| idx
+ 1).unwrap_or(0);
877 self.finished
= true;
879 let tmp
= mem
::replace(&mut self.v
, &mut []);
880 let (head
, tail
) = tmp
.split_at_mut(idx
);
886 #[stable(feature = "split_inclusive", since = "1.51.0")]
887 impl<T
, P
> FusedIterator
for SplitInclusiveMut
<'_
, T
, P
> where P
: FnMut(&T
) -> bool {}
889 /// An iterator over subslices separated by elements that match a predicate
890 /// function, starting from the end of the slice.
892 /// This struct is created by the [`rsplit`] method on [slices].
897 /// let slice = [11, 22, 33, 0, 44, 55];
898 /// let iter = slice.rsplit(|num| *num == 0);
901 /// [`rsplit`]: slice::rsplit
903 #[stable(feature = "slice_rsplit", since = "1.27.0")]
904 #[must_use = "iterators are lazy and do nothing unless consumed"]
905 pub struct RSplit
<'a
, T
: 'a
, P
>
907 P
: FnMut(&T
) -> bool
,
909 inner
: Split
<'a
, T
, P
>,
912 impl<'a
, T
: 'a
, P
: FnMut(&T
) -> bool
> RSplit
<'a
, T
, P
> {
914 pub(super) fn new(slice
: &'a
[T
], pred
: P
) -> Self {
915 Self { inner: Split::new(slice, pred) }
919 #[stable(feature = "slice_rsplit", since = "1.27.0")]
920 impl<T
: fmt
::Debug
, P
> fmt
::Debug
for RSplit
<'_
, T
, P
>
922 P
: FnMut(&T
) -> bool
,
924 fn fmt(&self, f
: &mut fmt
::Formatter
<'_
>) -> fmt
::Result
{
925 f
.debug_struct("RSplit")
926 .field("v", &self.inner
.v
)
927 .field("finished", &self.inner
.finished
)
932 // FIXME(#26925) Remove in favor of `#[derive(Clone)]`
933 #[stable(feature = "slice_rsplit", since = "1.27.0")]
934 impl<T
, P
> Clone
for RSplit
<'_
, T
, P
>
936 P
: Clone
+ FnMut(&T
) -> bool
,
938 fn clone(&self) -> Self {
939 RSplit { inner: self.inner.clone() }
943 #[stable(feature = "slice_rsplit", since = "1.27.0")]
944 impl<'a
, T
, P
> Iterator
for RSplit
<'a
, T
, P
>
946 P
: FnMut(&T
) -> bool
,
951 fn next(&mut self) -> Option
<&'a
[T
]> {
952 self.inner
.next_back()
956 fn size_hint(&self) -> (usize, Option
<usize>) {
957 self.inner
.size_hint()
961 #[stable(feature = "slice_rsplit", since = "1.27.0")]
962 impl<'a
, T
, P
> DoubleEndedIterator
for RSplit
<'a
, T
, P
>
964 P
: FnMut(&T
) -> bool
,
967 fn next_back(&mut self) -> Option
<&'a
[T
]> {
972 #[stable(feature = "slice_rsplit", since = "1.27.0")]
973 impl<'a
, T
, P
> SplitIter
for RSplit
<'a
, T
, P
>
975 P
: FnMut(&T
) -> bool
,
978 fn finish(&mut self) -> Option
<&'a
[T
]> {
983 #[stable(feature = "slice_rsplit", since = "1.27.0")]
984 impl<T
, P
> FusedIterator
for RSplit
<'_
, T
, P
> where P
: FnMut(&T
) -> bool {}
986 /// An iterator over the subslices of the vector which are separated
987 /// by elements that match `pred`, starting from the end of the slice.
989 /// This struct is created by the [`rsplit_mut`] method on [slices].
994 /// let mut slice = [11, 22, 33, 0, 44, 55];
995 /// let iter = slice.rsplit_mut(|num| *num == 0);
998 /// [`rsplit_mut`]: slice::rsplit_mut
1000 #[stable(feature = "slice_rsplit", since = "1.27.0")]
1001 #[must_use = "iterators are lazy and do nothing unless consumed"]
1002 pub struct RSplitMut
<'a
, T
: 'a
, P
>
1004 P
: FnMut(&T
) -> bool
,
1006 inner
: SplitMut
<'a
, T
, P
>,
1009 impl<'a
, T
: 'a
, P
: FnMut(&T
) -> bool
> RSplitMut
<'a
, T
, P
> {
1011 pub(super) fn new(slice
: &'a
mut [T
], pred
: P
) -> Self {
1012 Self { inner: SplitMut::new(slice, pred) }
1016 #[stable(feature = "slice_rsplit", since = "1.27.0")]
1017 impl<T
: fmt
::Debug
, P
> fmt
::Debug
for RSplitMut
<'_
, T
, P
>
1019 P
: FnMut(&T
) -> bool
,
1021 fn fmt(&self, f
: &mut fmt
::Formatter
<'_
>) -> fmt
::Result
{
1022 f
.debug_struct("RSplitMut")
1023 .field("v", &self.inner
.v
)
1024 .field("finished", &self.inner
.finished
)
1029 #[stable(feature = "slice_rsplit", since = "1.27.0")]
1030 impl<'a
, T
, P
> SplitIter
for RSplitMut
<'a
, T
, P
>
1032 P
: FnMut(&T
) -> bool
,
1035 fn finish(&mut self) -> Option
<&'a
mut [T
]> {
1040 #[stable(feature = "slice_rsplit", since = "1.27.0")]
1041 impl<'a
, T
, P
> Iterator
for RSplitMut
<'a
, T
, P
>
1043 P
: FnMut(&T
) -> bool
,
1045 type Item
= &'a
mut [T
];
1048 fn next(&mut self) -> Option
<&'a
mut [T
]> {
1049 self.inner
.next_back()
1053 fn size_hint(&self) -> (usize, Option
<usize>) {
1054 self.inner
.size_hint()
1058 #[stable(feature = "slice_rsplit", since = "1.27.0")]
1059 impl<'a
, T
, P
> DoubleEndedIterator
for RSplitMut
<'a
, T
, P
>
1061 P
: FnMut(&T
) -> bool
,
1064 fn next_back(&mut self) -> Option
<&'a
mut [T
]> {
1069 #[stable(feature = "slice_rsplit", since = "1.27.0")]
1070 impl<T
, P
> FusedIterator
for RSplitMut
<'_
, T
, P
> where P
: FnMut(&T
) -> bool {}
1072 /// An private iterator over subslices separated by elements that
1073 /// match a predicate function, splitting at most a fixed number of
1076 struct GenericSplitN
<I
> {
1081 impl<T
, I
: SplitIter
<Item
= T
>> Iterator
for GenericSplitN
<I
> {
1085 fn next(&mut self) -> Option
<T
> {
1100 fn size_hint(&self) -> (usize, Option
<usize>) {
1101 let (lower
, upper_opt
) = self.iter
.size_hint();
1103 cmp
::min(self.count
, lower
),
1104 Some(upper_opt
.map_or(self.count
, |upper
| cmp
::min(self.count
, upper
))),
1109 /// An iterator over subslices separated by elements that match a predicate
1110 /// function, limited to a given number of splits.
1112 /// This struct is created by the [`splitn`] method on [slices].
1117 /// let slice = [10, 40, 30, 20, 60, 50];
1118 /// let iter = slice.splitn(2, |num| *num % 3 == 0);
1121 /// [`splitn`]: slice::splitn
1123 #[stable(feature = "rust1", since = "1.0.0")]
1124 #[must_use = "iterators are lazy and do nothing unless consumed"]
1125 pub struct SplitN
<'a
, T
: 'a
, P
>
1127 P
: FnMut(&T
) -> bool
,
1129 inner
: GenericSplitN
<Split
<'a
, T
, P
>>,
1132 impl<'a
, T
: 'a
, P
: FnMut(&T
) -> bool
> SplitN
<'a
, T
, P
> {
1134 pub(super) fn new(s
: Split
<'a
, T
, P
>, n
: usize) -> Self {
1135 Self { inner: GenericSplitN { iter: s, count: n }
}
1139 #[stable(feature = "core_impl_debug", since = "1.9.0")]
1140 impl<T
: fmt
::Debug
, P
> fmt
::Debug
for SplitN
<'_
, T
, P
>
1142 P
: FnMut(&T
) -> bool
,
1144 fn fmt(&self, f
: &mut fmt
::Formatter
<'_
>) -> fmt
::Result
{
1145 f
.debug_struct("SplitN").field("inner", &self.inner
).finish()
1149 /// An iterator over subslices separated by elements that match a
1150 /// predicate function, limited to a given number of splits, starting
1151 /// from the end of the slice.
1153 /// This struct is created by the [`rsplitn`] method on [slices].
1158 /// let slice = [10, 40, 30, 20, 60, 50];
1159 /// let iter = slice.rsplitn(2, |num| *num % 3 == 0);
1162 /// [`rsplitn`]: slice::rsplitn
1164 #[stable(feature = "rust1", since = "1.0.0")]
1165 #[must_use = "iterators are lazy and do nothing unless consumed"]
1166 pub struct RSplitN
<'a
, T
: 'a
, P
>
1168 P
: FnMut(&T
) -> bool
,
1170 inner
: GenericSplitN
<RSplit
<'a
, T
, P
>>,
1173 impl<'a
, T
: 'a
, P
: FnMut(&T
) -> bool
> RSplitN
<'a
, T
, P
> {
1175 pub(super) fn new(s
: RSplit
<'a
, T
, P
>, n
: usize) -> Self {
1176 Self { inner: GenericSplitN { iter: s, count: n }
}
1180 #[stable(feature = "core_impl_debug", since = "1.9.0")]
1181 impl<T
: fmt
::Debug
, P
> fmt
::Debug
for RSplitN
<'_
, T
, P
>
1183 P
: FnMut(&T
) -> bool
,
1185 fn fmt(&self, f
: &mut fmt
::Formatter
<'_
>) -> fmt
::Result
{
1186 f
.debug_struct("RSplitN").field("inner", &self.inner
).finish()
1190 /// An iterator over subslices separated by elements that match a predicate
1191 /// function, limited to a given number of splits.
1193 /// This struct is created by the [`splitn_mut`] method on [slices].
1198 /// let mut slice = [10, 40, 30, 20, 60, 50];
1199 /// let iter = slice.splitn_mut(2, |num| *num % 3 == 0);
1202 /// [`splitn_mut`]: slice::splitn_mut
1204 #[stable(feature = "rust1", since = "1.0.0")]
1205 #[must_use = "iterators are lazy and do nothing unless consumed"]
1206 pub struct SplitNMut
<'a
, T
: 'a
, P
>
1208 P
: FnMut(&T
) -> bool
,
1210 inner
: GenericSplitN
<SplitMut
<'a
, T
, P
>>,
1213 impl<'a
, T
: 'a
, P
: FnMut(&T
) -> bool
> SplitNMut
<'a
, T
, P
> {
1215 pub(super) fn new(s
: SplitMut
<'a
, T
, P
>, n
: usize) -> Self {
1216 Self { inner: GenericSplitN { iter: s, count: n }
}
1220 #[stable(feature = "core_impl_debug", since = "1.9.0")]
1221 impl<T
: fmt
::Debug
, P
> fmt
::Debug
for SplitNMut
<'_
, T
, P
>
1223 P
: FnMut(&T
) -> bool
,
1225 fn fmt(&self, f
: &mut fmt
::Formatter
<'_
>) -> fmt
::Result
{
1226 f
.debug_struct("SplitNMut").field("inner", &self.inner
).finish()
1230 /// An iterator over subslices separated by elements that match a
1231 /// predicate function, limited to a given number of splits, starting
1232 /// from the end of the slice.
1234 /// This struct is created by the [`rsplitn_mut`] method on [slices].
1239 /// let mut slice = [10, 40, 30, 20, 60, 50];
1240 /// let iter = slice.rsplitn_mut(2, |num| *num % 3 == 0);
1243 /// [`rsplitn_mut`]: slice::rsplitn_mut
1245 #[stable(feature = "rust1", since = "1.0.0")]
1246 #[must_use = "iterators are lazy and do nothing unless consumed"]
1247 pub struct RSplitNMut
<'a
, T
: 'a
, P
>
1249 P
: FnMut(&T
) -> bool
,
1251 inner
: GenericSplitN
<RSplitMut
<'a
, T
, P
>>,
1254 impl<'a
, T
: 'a
, P
: FnMut(&T
) -> bool
> RSplitNMut
<'a
, T
, P
> {
1256 pub(super) fn new(s
: RSplitMut
<'a
, T
, P
>, n
: usize) -> Self {
1257 Self { inner: GenericSplitN { iter: s, count: n }
}
1261 #[stable(feature = "core_impl_debug", since = "1.9.0")]
1262 impl<T
: fmt
::Debug
, P
> fmt
::Debug
for RSplitNMut
<'_
, T
, P
>
1264 P
: FnMut(&T
) -> bool
,
1266 fn fmt(&self, f
: &mut fmt
::Formatter
<'_
>) -> fmt
::Result
{
1267 f
.debug_struct("RSplitNMut").field("inner", &self.inner
).finish()
1271 forward_iterator
! { SplitN: T, &'a [T] }
1272 forward_iterator
! { RSplitN: T, &'a [T] }
1273 forward_iterator
! { SplitNMut: T, &'a mut [T] }
1274 forward_iterator
! { RSplitNMut: T, &'a mut [T] }
1276 /// An iterator over overlapping subslices of length `size`.
1278 /// This struct is created by the [`windows`] method on [slices].
1283 /// let slice = ['r', 'u', 's', 't'];
1284 /// let iter = slice.windows(2);
1287 /// [`windows`]: slice::windows
1290 #[stable(feature = "rust1", since = "1.0.0")]
1291 #[must_use = "iterators are lazy and do nothing unless consumed"]
1292 pub struct Windows
<'a
, T
: 'a
> {
1297 impl<'a
, T
: 'a
> Windows
<'a
, T
> {
1299 pub(super) fn new(slice
: &'a
[T
], size
: NonZeroUsize
) -> Self {
1300 Self { v: slice, size }
1304 // FIXME(#26925) Remove in favor of `#[derive(Clone)]`
1305 #[stable(feature = "rust1", since = "1.0.0")]
1306 impl<T
> Clone
for Windows
<'_
, T
> {
1307 fn clone(&self) -> Self {
1308 Windows { v: self.v, size: self.size }
1312 #[stable(feature = "rust1", since = "1.0.0")]
1313 impl<'a
, T
> Iterator
for Windows
<'a
, T
> {
1314 type Item
= &'a
[T
];
1317 fn next(&mut self) -> Option
<&'a
[T
]> {
1318 if self.size
.get() > self.v
.len() {
1321 let ret
= Some(&self.v
[..self.size
.get()]);
1322 self.v
= &self.v
[1..];
1328 fn size_hint(&self) -> (usize, Option
<usize>) {
1329 if self.size
.get() > self.v
.len() {
1332 let size
= self.v
.len() - self.size
.get() + 1;
1338 fn count(self) -> usize {
1343 fn nth(&mut self, n
: usize) -> Option
<Self::Item
> {
1344 let (end
, overflow
) = self.size
.get().overflowing_add(n
);
1345 if end
> self.v
.len() || overflow
{
1349 let nth
= &self.v
[n
..end
];
1350 self.v
= &self.v
[n
+ 1..];
1356 fn last(self) -> Option
<Self::Item
> {
1357 if self.size
.get() > self.v
.len() {
1360 let start
= self.v
.len() - self.size
.get();
1361 Some(&self.v
[start
..])
1365 unsafe fn __iterator_get_unchecked(&mut self, idx
: usize) -> Self::Item
{
1366 // SAFETY: since the caller guarantees that `i` is in bounds,
1367 // which means that `i` cannot overflow an `isize`, and the
1368 // slice created by `from_raw_parts` is a subslice of `self.v`
1369 // thus is guaranteed to be valid for the lifetime `'a` of `self.v`.
1370 unsafe { from_raw_parts(self.v.as_ptr().add(idx), self.size.get()) }
1374 #[stable(feature = "rust1", since = "1.0.0")]
1375 impl<'a
, T
> DoubleEndedIterator
for Windows
<'a
, T
> {
1377 fn next_back(&mut self) -> Option
<&'a
[T
]> {
1378 if self.size
.get() > self.v
.len() {
1381 let ret
= Some(&self.v
[self.v
.len() - self.size
.get()..]);
1382 self.v
= &self.v
[..self.v
.len() - 1];
1388 fn nth_back(&mut self, n
: usize) -> Option
<Self::Item
> {
1389 let (end
, overflow
) = self.v
.len().overflowing_sub(n
);
1390 if end
< self.size
.get() || overflow
{
1394 let ret
= &self.v
[end
- self.size
.get()..end
];
1395 self.v
= &self.v
[..end
- 1];
1401 #[stable(feature = "rust1", since = "1.0.0")]
1402 impl<T
> ExactSizeIterator
for Windows
<'_
, T
> {}
1404 #[unstable(feature = "trusted_len", issue = "37572")]
1405 unsafe impl<T
> TrustedLen
for Windows
<'_
, T
> {}
1407 #[stable(feature = "fused", since = "1.26.0")]
1408 impl<T
> FusedIterator
for Windows
<'_
, T
> {}
1411 #[unstable(feature = "trusted_random_access", issue = "none")]
1412 unsafe impl<'a
, T
> TrustedRandomAccess
for Windows
<'a
, T
> {}
1415 #[unstable(feature = "trusted_random_access", issue = "none")]
1416 unsafe impl<'a
, T
> TrustedRandomAccessNoCoerce
for Windows
<'a
, T
> {
1417 const MAY_HAVE_SIDE_EFFECT
: bool
= false;
1420 /// An iterator over a slice in (non-overlapping) chunks (`chunk_size` elements at a
1421 /// time), starting at the beginning of the slice.
1423 /// When the slice len is not evenly divided by the chunk size, the last slice
1424 /// of the iteration will be the remainder.
1426 /// This struct is created by the [`chunks`] method on [slices].
1431 /// let slice = ['l', 'o', 'r', 'e', 'm'];
1432 /// let iter = slice.chunks(2);
1435 /// [`chunks`]: slice::chunks
1438 #[stable(feature = "rust1", since = "1.0.0")]
1439 #[must_use = "iterators are lazy and do nothing unless consumed"]
1440 pub struct Chunks
<'a
, T
: 'a
> {
1445 impl<'a
, T
: 'a
> Chunks
<'a
, T
> {
1447 pub(super) fn new(slice
: &'a
[T
], size
: usize) -> Self {
1448 Self { v: slice, chunk_size: size }
1452 // FIXME(#26925) Remove in favor of `#[derive(Clone)]`
1453 #[stable(feature = "rust1", since = "1.0.0")]
1454 impl<T
> Clone
for Chunks
<'_
, T
> {
1455 fn clone(&self) -> Self {
1456 Chunks { v: self.v, chunk_size: self.chunk_size }
1460 #[stable(feature = "rust1", since = "1.0.0")]
1461 impl<'a
, T
> Iterator
for Chunks
<'a
, T
> {
1462 type Item
= &'a
[T
];
1465 fn next(&mut self) -> Option
<&'a
[T
]> {
1466 if self.v
.is_empty() {
1469 let chunksz
= cmp
::min(self.v
.len(), self.chunk_size
);
1470 let (fst
, snd
) = self.v
.split_at(chunksz
);
1477 fn size_hint(&self) -> (usize, Option
<usize>) {
1478 if self.v
.is_empty() {
1481 let n
= self.v
.len() / self.chunk_size
;
1482 let rem
= self.v
.len() % self.chunk_size
;
1483 let n
= if rem
> 0 { n + 1 }
else { n }
;
1489 fn count(self) -> usize {
1494 fn nth(&mut self, n
: usize) -> Option
<Self::Item
> {
1495 let (start
, overflow
) = n
.overflowing_mul(self.chunk_size
);
1496 if start
>= self.v
.len() || overflow
{
1500 let end
= match start
.checked_add(self.chunk_size
) {
1501 Some(sum
) => cmp
::min(self.v
.len(), sum
),
1502 None
=> self.v
.len(),
1504 let nth
= &self.v
[start
..end
];
1505 self.v
= &self.v
[end
..];
1511 fn last(self) -> Option
<Self::Item
> {
1512 if self.v
.is_empty() {
1515 let start
= (self.v
.len() - 1) / self.chunk_size
* self.chunk_size
;
1516 Some(&self.v
[start
..])
1520 unsafe fn __iterator_get_unchecked(&mut self, idx
: usize) -> Self::Item
{
1521 let start
= idx
* self.chunk_size
;
1522 // SAFETY: the caller guarantees that `i` is in bounds,
1523 // which means that `start` must be in bounds of the
1524 // underlying `self.v` slice, and we made sure that `len`
1525 // is also in bounds of `self.v`. Thus, `start` cannot overflow
1526 // an `isize`, and the slice constructed by `from_raw_parts`
1527 // is a subslice of `self.v` which is guaranteed to be valid
1528 // for the lifetime `'a` of `self.v`.
1530 let len
= cmp
::min(self.v
.len().unchecked_sub(start
), self.chunk_size
);
1531 from_raw_parts(self.v
.as_ptr().add(start
), len
)
1536 #[stable(feature = "rust1", since = "1.0.0")]
1537 impl<'a
, T
> DoubleEndedIterator
for Chunks
<'a
, T
> {
1539 fn next_back(&mut self) -> Option
<&'a
[T
]> {
1540 if self.v
.is_empty() {
1543 let remainder
= self.v
.len() % self.chunk_size
;
1544 let chunksz
= if remainder
!= 0 { remainder }
else { self.chunk_size }
;
1545 // SAFETY: split_at_unchecked requires the argument be less than or
1546 // equal to the length. This is guaranteed, but subtle: `chunksz`
1547 // will always either be `self.v.len() % self.chunk_size`, which
1548 // will always evaluate to strictly less than `self.v.len()` (or
1549 // panic, in the case that `self.chunk_size` is zero), or it can be
1550 // `self.chunk_size`, in the case that the length is exactly
1551 // divisible by the chunk size.
1553 // While it seems like using `self.chunk_size` in this case could
1554 // lead to a value greater than `self.v.len()`, it cannot: if
1555 // `self.chunk_size` were greater than `self.v.len()`, then
1556 // `self.v.len() % self.chunk_size` would return nonzero (note that
1557 // in this branch of the `if`, we already know that `self.v` is
1559 let (fst
, snd
) = unsafe { self.v.split_at_unchecked(self.v.len() - chunksz) }
;
1566 fn nth_back(&mut self, n
: usize) -> Option
<Self::Item
> {
1567 let len
= self.len();
1572 let start
= (len
- 1 - n
) * self.chunk_size
;
1573 let end
= match start
.checked_add(self.chunk_size
) {
1574 Some(res
) => cmp
::min(self.v
.len(), res
),
1575 None
=> self.v
.len(),
1577 let nth_back
= &self.v
[start
..end
];
1578 self.v
= &self.v
[..start
];
1584 #[stable(feature = "rust1", since = "1.0.0")]
1585 impl<T
> ExactSizeIterator
for Chunks
<'_
, T
> {}
1587 #[unstable(feature = "trusted_len", issue = "37572")]
1588 unsafe impl<T
> TrustedLen
for Chunks
<'_
, T
> {}
1590 #[stable(feature = "fused", since = "1.26.0")]
1591 impl<T
> FusedIterator
for Chunks
<'_
, T
> {}
1594 #[unstable(feature = "trusted_random_access", issue = "none")]
1595 unsafe impl<'a
, T
> TrustedRandomAccess
for Chunks
<'a
, T
> {}
1598 #[unstable(feature = "trusted_random_access", issue = "none")]
1599 unsafe impl<'a
, T
> TrustedRandomAccessNoCoerce
for Chunks
<'a
, T
> {
1600 const MAY_HAVE_SIDE_EFFECT
: bool
= false;
1603 /// An iterator over a slice in (non-overlapping) mutable chunks (`chunk_size`
1604 /// elements at a time), starting at the beginning of the slice.
1606 /// When the slice len is not evenly divided by the chunk size, the last slice
1607 /// of the iteration will be the remainder.
1609 /// This struct is created by the [`chunks_mut`] method on [slices].
1614 /// let mut slice = ['l', 'o', 'r', 'e', 'm'];
1615 /// let iter = slice.chunks_mut(2);
1618 /// [`chunks_mut`]: slice::chunks_mut
1621 #[stable(feature = "rust1", since = "1.0.0")]
1622 #[must_use = "iterators are lazy and do nothing unless consumed"]
1623 pub struct ChunksMut
<'a
, T
: 'a
> {
1625 /// This slice pointer must point at a valid region of `T` with at least length `v.len()`. Normally,
1626 /// those requirements would mean that we could instead use a `&mut [T]` here, but we cannot
1627 /// because `__iterator_get_unchecked` needs to return `&mut [T]`, which guarantees certain aliasing
1628 /// properties that we cannot uphold if we hold on to the full original `&mut [T]`. Wrapping a raw
1629 /// slice instead lets us hand out non-overlapping `&mut [T]` subslices of the slice we wrap.
1632 _marker
: PhantomData
<&'a
mut T
>,
1635 impl<'a
, T
: 'a
> ChunksMut
<'a
, T
> {
1637 pub(super) fn new(slice
: &'a
mut [T
], size
: usize) -> Self {
1638 Self { v: slice, chunk_size: size, _marker: PhantomData }
1642 #[stable(feature = "rust1", since = "1.0.0")]
1643 impl<'a
, T
> Iterator
for ChunksMut
<'a
, T
> {
1644 type Item
= &'a
mut [T
];
1647 fn next(&mut self) -> Option
<&'a
mut [T
]> {
1648 if self.v
.is_empty() {
1651 let sz
= cmp
::min(self.v
.len(), self.chunk_size
);
1652 // SAFETY: The self.v contract ensures that any split_at_mut is valid.
1653 let (head
, tail
) = unsafe { self.v.split_at_mut(sz) }
;
1655 // SAFETY: Nothing else points to or will point to the contents of this slice.
1656 Some(unsafe { &mut *head }
)
1661 fn size_hint(&self) -> (usize, Option
<usize>) {
1662 if self.v
.is_empty() {
1665 let n
= self.v
.len() / self.chunk_size
;
1666 let rem
= self.v
.len() % self.chunk_size
;
1667 let n
= if rem
> 0 { n + 1 }
else { n }
;
1673 fn count(self) -> usize {
1678 fn nth(&mut self, n
: usize) -> Option
<&'a
mut [T
]> {
1679 let (start
, overflow
) = n
.overflowing_mul(self.chunk_size
);
1680 if start
>= self.v
.len() || overflow
{
1684 let end
= match start
.checked_add(self.chunk_size
) {
1685 Some(sum
) => cmp
::min(self.v
.len(), sum
),
1686 None
=> self.v
.len(),
1688 // SAFETY: The self.v contract ensures that any split_at_mut is valid.
1689 let (head
, tail
) = unsafe { self.v.split_at_mut(end) }
;
1690 // SAFETY: The self.v contract ensures that any split_at_mut is valid.
1691 let (_
, nth
) = unsafe { head.split_at_mut(start) }
;
1693 // SAFETY: Nothing else points to or will point to the contents of this slice.
1694 Some(unsafe { &mut *nth }
)
1699 fn last(self) -> Option
<Self::Item
> {
1700 if self.v
.is_empty() {
1703 let start
= (self.v
.len() - 1) / self.chunk_size
* self.chunk_size
;
1704 // SAFETY: Nothing else points to or will point to the contents of this slice.
1705 Some(unsafe { &mut *self.v.get_unchecked_mut(start..) }
)
1709 unsafe fn __iterator_get_unchecked(&mut self, idx
: usize) -> Self::Item
{
1710 let start
= idx
* self.chunk_size
;
1711 // SAFETY: see comments for `Chunks::__iterator_get_unchecked` and `self.v`.
1713 // Also note that the caller also guarantees that we're never called
1714 // with the same index again, and that no other methods that will
1715 // access this subslice are called, so it is valid for the returned
1716 // slice to be mutable.
1718 let len
= cmp
::min(self.v
.len().unchecked_sub(start
), self.chunk_size
);
1719 from_raw_parts_mut(self.v
.as_mut_ptr().add(start
), len
)
1724 #[stable(feature = "rust1", since = "1.0.0")]
1725 impl<'a
, T
> DoubleEndedIterator
for ChunksMut
<'a
, T
> {
1727 fn next_back(&mut self) -> Option
<&'a
mut [T
]> {
1728 if self.v
.is_empty() {
1731 let remainder
= self.v
.len() % self.chunk_size
;
1732 let sz
= if remainder
!= 0 { remainder }
else { self.chunk_size }
;
1733 let len
= self.v
.len();
1734 // SAFETY: Similar to `Chunks::next_back`
1735 let (head
, tail
) = unsafe { self.v.split_at_mut_unchecked(len - sz) }
;
1737 // SAFETY: Nothing else points to or will point to the contents of this slice.
1738 Some(unsafe { &mut *tail }
)
1743 fn nth_back(&mut self, n
: usize) -> Option
<Self::Item
> {
1744 let len
= self.len();
1749 let start
= (len
- 1 - n
) * self.chunk_size
;
1750 let end
= match start
.checked_add(self.chunk_size
) {
1751 Some(res
) => cmp
::min(self.v
.len(), res
),
1752 None
=> self.v
.len(),
1754 // SAFETY: The self.v contract ensures that any split_at_mut is valid.
1755 let (temp
, _tail
) = unsafe { self.v.split_at_mut(end) }
;
1756 // SAFETY: The self.v contract ensures that any split_at_mut is valid.
1757 let (head
, nth_back
) = unsafe { temp.split_at_mut(start) }
;
1759 // SAFETY: Nothing else points to or will point to the contents of this slice.
1760 Some(unsafe { &mut *nth_back }
)
1765 #[stable(feature = "rust1", since = "1.0.0")]
1766 impl<T
> ExactSizeIterator
for ChunksMut
<'_
, T
> {}
1768 #[unstable(feature = "trusted_len", issue = "37572")]
1769 unsafe impl<T
> TrustedLen
for ChunksMut
<'_
, T
> {}
1771 #[stable(feature = "fused", since = "1.26.0")]
1772 impl<T
> FusedIterator
for ChunksMut
<'_
, T
> {}
1775 #[unstable(feature = "trusted_random_access", issue = "none")]
1776 unsafe impl<'a
, T
> TrustedRandomAccess
for ChunksMut
<'a
, T
> {}
1779 #[unstable(feature = "trusted_random_access", issue = "none")]
1780 unsafe impl<'a
, T
> TrustedRandomAccessNoCoerce
for ChunksMut
<'a
, T
> {
1781 const MAY_HAVE_SIDE_EFFECT
: bool
= false;
1784 #[stable(feature = "rust1", since = "1.0.0")]
1785 unsafe impl<T
> Send
for ChunksMut
<'_
, T
> where T
: Send {}
1787 #[stable(feature = "rust1", since = "1.0.0")]
1788 unsafe impl<T
> Sync
for ChunksMut
<'_
, T
> where T
: Sync {}
1790 /// An iterator over a slice in (non-overlapping) chunks (`chunk_size` 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 `chunk_size-1` elements will be omitted but can be retrieved from
1795 /// the [`remainder`] function from the iterator.
1797 /// This struct is created by the [`chunks_exact`] method on [slices].
1802 /// let slice = ['l', 'o', 'r', 'e', 'm'];
1803 /// let iter = slice.chunks_exact(2);
1806 /// [`chunks_exact`]: slice::chunks_exact
1807 /// [`remainder`]: ChunksExact::remainder
1810 #[stable(feature = "chunks_exact", since = "1.31.0")]
1811 #[must_use = "iterators are lazy and do nothing unless consumed"]
1812 pub struct ChunksExact
<'a
, T
: 'a
> {
1818 impl<'a
, T
> ChunksExact
<'a
, T
> {
1820 pub(super) fn new(slice
: &'a
[T
], chunk_size
: usize) -> Self {
1821 let rem
= slice
.len() % chunk_size
;
1822 let fst_len
= slice
.len() - rem
;
1823 // SAFETY: 0 <= fst_len <= slice.len() by construction above
1824 let (fst
, snd
) = unsafe { slice.split_at_unchecked(fst_len) }
;
1825 Self { v: fst, rem: snd, chunk_size }
1828 /// Returns the remainder of the original slice that is not going to be
1829 /// returned by the iterator. The returned slice has at most `chunk_size-1`
1835 /// let slice = ['l', 'o', 'r', 'e', 'm'];
1836 /// let mut iter = slice.chunks_exact(2);
1837 /// assert_eq!(iter.remainder(), &['m'][..]);
1838 /// assert_eq!(iter.next(), Some(&['l', 'o'][..]));
1839 /// assert_eq!(iter.remainder(), &['m'][..]);
1840 /// assert_eq!(iter.next(), Some(&['r', 'e'][..]));
1841 /// assert_eq!(iter.remainder(), &['m'][..]);
1842 /// assert_eq!(iter.next(), None);
1843 /// assert_eq!(iter.remainder(), &['m'][..]);
1846 #[stable(feature = "chunks_exact", since = "1.31.0")]
1847 pub fn remainder(&self) -> &'a
[T
] {
1852 // FIXME(#26925) Remove in favor of `#[derive(Clone)]`
1853 #[stable(feature = "chunks_exact", since = "1.31.0")]
1854 impl<T
> Clone
for ChunksExact
<'_
, T
> {
1855 fn clone(&self) -> Self {
1856 ChunksExact { v: self.v, rem: self.rem, chunk_size: self.chunk_size }
1860 #[stable(feature = "chunks_exact", since = "1.31.0")]
1861 impl<'a
, T
> Iterator
for ChunksExact
<'a
, T
> {
1862 type Item
= &'a
[T
];
1865 fn next(&mut self) -> Option
<&'a
[T
]> {
1866 if self.v
.len() < self.chunk_size
{
1869 let (fst
, snd
) = self.v
.split_at(self.chunk_size
);
1876 fn size_hint(&self) -> (usize, Option
<usize>) {
1877 let n
= self.v
.len() / self.chunk_size
;
1882 fn count(self) -> usize {
1887 fn nth(&mut self, n
: usize) -> Option
<Self::Item
> {
1888 let (start
, overflow
) = n
.overflowing_mul(self.chunk_size
);
1889 if start
>= self.v
.len() || overflow
{
1893 let (_
, snd
) = self.v
.split_at(start
);
1900 fn last(mut self) -> Option
<Self::Item
> {
1904 unsafe fn __iterator_get_unchecked(&mut self, idx
: usize) -> Self::Item
{
1905 let start
= idx
* self.chunk_size
;
1906 // SAFETY: mostly identical to `Chunks::__iterator_get_unchecked`.
1907 unsafe { from_raw_parts(self.v.as_ptr().add(start), self.chunk_size) }
1911 #[stable(feature = "chunks_exact", since = "1.31.0")]
1912 impl<'a
, T
> DoubleEndedIterator
for ChunksExact
<'a
, T
> {
1914 fn next_back(&mut self) -> Option
<&'a
[T
]> {
1915 if self.v
.len() < self.chunk_size
{
1918 let (fst
, snd
) = self.v
.split_at(self.v
.len() - self.chunk_size
);
1925 fn nth_back(&mut self, n
: usize) -> Option
<Self::Item
> {
1926 let len
= self.len();
1931 let start
= (len
- 1 - n
) * self.chunk_size
;
1932 let end
= start
+ self.chunk_size
;
1933 let nth_back
= &self.v
[start
..end
];
1934 self.v
= &self.v
[..start
];
1940 #[stable(feature = "chunks_exact", since = "1.31.0")]
1941 impl<T
> ExactSizeIterator
for ChunksExact
<'_
, T
> {
1942 fn is_empty(&self) -> bool
{
1947 #[unstable(feature = "trusted_len", issue = "37572")]
1948 unsafe impl<T
> TrustedLen
for ChunksExact
<'_
, T
> {}
1950 #[stable(feature = "chunks_exact", since = "1.31.0")]
1951 impl<T
> FusedIterator
for ChunksExact
<'_
, T
> {}
1954 #[unstable(feature = "trusted_random_access", issue = "none")]
1955 unsafe impl<'a
, T
> TrustedRandomAccess
for ChunksExact
<'a
, T
> {}
1958 #[unstable(feature = "trusted_random_access", issue = "none")]
1959 unsafe impl<'a
, T
> TrustedRandomAccessNoCoerce
for ChunksExact
<'a
, T
> {
1960 const MAY_HAVE_SIDE_EFFECT
: bool
= false;
1963 /// An iterator over a slice in (non-overlapping) mutable chunks (`chunk_size`
1964 /// elements at a time), starting at the beginning of the slice.
1966 /// When the slice len is not evenly divided by the chunk size, the last up to
1967 /// `chunk_size-1` elements will be omitted but can be retrieved from the
1968 /// [`into_remainder`] function from the iterator.
1970 /// This struct is created by the [`chunks_exact_mut`] method on [slices].
1975 /// let mut slice = ['l', 'o', 'r', 'e', 'm'];
1976 /// let iter = slice.chunks_exact_mut(2);
1979 /// [`chunks_exact_mut`]: slice::chunks_exact_mut
1980 /// [`into_remainder`]: ChunksExactMut::into_remainder
1983 #[stable(feature = "chunks_exact", since = "1.31.0")]
1984 #[must_use = "iterators are lazy and do nothing unless consumed"]
1985 pub struct ChunksExactMut
<'a
, T
: 'a
> {
1987 /// This slice pointer must point at a valid region of `T` with at least length `v.len()`. Normally,
1988 /// those requirements would mean that we could instead use a `&mut [T]` here, but we cannot
1989 /// because `__iterator_get_unchecked` needs to return `&mut [T]`, which guarantees certain aliasing
1990 /// properties that we cannot uphold if we hold on to the full original `&mut [T]`. Wrapping a raw
1991 /// slice instead lets us hand out non-overlapping `&mut [T]` subslices of the slice we wrap.
1993 rem
: &'a
mut [T
], // The iterator never yields from here, so this can be unique
1995 _marker
: PhantomData
<&'a
mut T
>,
1998 impl<'a
, T
> ChunksExactMut
<'a
, T
> {
2000 pub(super) fn new(slice
: &'a
mut [T
], chunk_size
: usize) -> Self {
2001 let rem
= slice
.len() % chunk_size
;
2002 let fst_len
= slice
.len() - rem
;
2003 // SAFETY: 0 <= fst_len <= slice.len() by construction above
2004 let (fst
, snd
) = unsafe { slice.split_at_mut_unchecked(fst_len) }
;
2005 Self { v: fst, rem: snd, chunk_size, _marker: PhantomData }
2008 /// Returns the remainder of the original slice that is not going to be
2009 /// returned by the iterator. The returned slice has at most `chunk_size-1`
2011 #[must_use = "`self` will be dropped if the result is not used"]
2012 #[stable(feature = "chunks_exact", since = "1.31.0")]
2013 pub fn into_remainder(self) -> &'a
mut [T
] {
2018 #[stable(feature = "chunks_exact", since = "1.31.0")]
2019 impl<'a
, T
> Iterator
for ChunksExactMut
<'a
, T
> {
2020 type Item
= &'a
mut [T
];
2023 fn next(&mut self) -> Option
<&'a
mut [T
]> {
2024 if self.v
.len() < self.chunk_size
{
2027 // SAFETY: self.chunk_size is inbounds because we compared above against self.v.len()
2028 let (head
, tail
) = unsafe { self.v.split_at_mut(self.chunk_size) }
;
2030 // SAFETY: Nothing else points to or will point to the contents of this slice.
2031 Some(unsafe { &mut *head }
)
2036 fn size_hint(&self) -> (usize, Option
<usize>) {
2037 let n
= self.v
.len() / self.chunk_size
;
2042 fn count(self) -> usize {
2047 fn nth(&mut self, n
: usize) -> Option
<&'a
mut [T
]> {
2048 let (start
, overflow
) = n
.overflowing_mul(self.chunk_size
);
2049 if start
>= self.v
.len() || overflow
{
2053 // SAFETY: The self.v contract ensures that any split_at_mut is valid.
2054 let (_
, snd
) = unsafe { self.v.split_at_mut(start) }
;
2061 fn last(mut self) -> Option
<Self::Item
> {
2065 unsafe fn __iterator_get_unchecked(&mut self, idx
: usize) -> Self::Item
{
2066 let start
= idx
* self.chunk_size
;
2067 // SAFETY: see comments for `Chunks::__iterator_get_unchecked` and `self.v`.
2068 unsafe { from_raw_parts_mut(self.v.as_mut_ptr().add(start), self.chunk_size) }
2072 #[stable(feature = "chunks_exact", since = "1.31.0")]
2073 impl<'a
, T
> DoubleEndedIterator
for ChunksExactMut
<'a
, T
> {
2075 fn next_back(&mut self) -> Option
<&'a
mut [T
]> {
2076 if self.v
.len() < self.chunk_size
{
2079 // SAFETY: This subtraction is inbounds because of the check above
2080 let (head
, tail
) = unsafe { self.v.split_at_mut(self.v.len() - self.chunk_size) }
;
2082 // SAFETY: Nothing else points to or will point to the contents of this slice.
2083 Some(unsafe { &mut *tail }
)
2088 fn nth_back(&mut self, n
: usize) -> Option
<Self::Item
> {
2089 let len
= self.len();
2094 let start
= (len
- 1 - n
) * self.chunk_size
;
2095 let end
= start
+ self.chunk_size
;
2096 // SAFETY: The self.v contract ensures that any split_at_mut is valid.
2097 let (temp
, _tail
) = unsafe { mem::replace(&mut self.v, &mut []).split_at_mut(end) }
;
2098 // SAFETY: The self.v contract ensures that any split_at_mut is valid.
2099 let (head
, nth_back
) = unsafe { temp.split_at_mut(start) }
;
2101 // SAFETY: Nothing else points to or will point to the contents of this slice.
2102 Some(unsafe { &mut *nth_back }
)
2107 #[stable(feature = "chunks_exact", since = "1.31.0")]
2108 impl<T
> ExactSizeIterator
for ChunksExactMut
<'_
, T
> {
2109 fn is_empty(&self) -> bool
{
2114 #[unstable(feature = "trusted_len", issue = "37572")]
2115 unsafe impl<T
> TrustedLen
for ChunksExactMut
<'_
, T
> {}
2117 #[stable(feature = "chunks_exact", since = "1.31.0")]
2118 impl<T
> FusedIterator
for ChunksExactMut
<'_
, T
> {}
2121 #[unstable(feature = "trusted_random_access", issue = "none")]
2122 unsafe impl<'a
, T
> TrustedRandomAccess
for ChunksExactMut
<'a
, T
> {}
2125 #[unstable(feature = "trusted_random_access", issue = "none")]
2126 unsafe impl<'a
, T
> TrustedRandomAccessNoCoerce
for ChunksExactMut
<'a
, T
> {
2127 const MAY_HAVE_SIDE_EFFECT
: bool
= false;
2130 #[stable(feature = "chunks_exact", since = "1.31.0")]
2131 unsafe impl<T
> Send
for ChunksExactMut
<'_
, T
> where T
: Send {}
2133 #[stable(feature = "chunks_exact", since = "1.31.0")]
2134 unsafe impl<T
> Sync
for ChunksExactMut
<'_
, T
> where T
: Sync {}
2136 /// A windowed iterator over a slice in overlapping chunks (`N` elements at a
2137 /// time), starting at the beginning of the slice
2139 /// This struct is created by the [`array_windows`] method on [slices].
2144 /// #![feature(array_windows)]
2146 /// let slice = [0, 1, 2, 3];
2147 /// let iter = slice.array_windows::<2>();
2150 /// [`array_windows`]: slice::array_windows
2152 #[derive(Debug, Clone, Copy)]
2153 #[unstable(feature = "array_windows", issue = "75027")]
2154 #[must_use = "iterators are lazy and do nothing unless consumed"]
2155 pub struct ArrayWindows
<'a
, T
: 'a
, const N
: usize> {
2156 slice_head
: *const T
,
2158 marker
: PhantomData
<&'a
[T
; N
]>,
2161 impl<'a
, T
: 'a
, const N
: usize> ArrayWindows
<'a
, T
, N
> {
2163 pub(super) fn new(slice
: &'a
[T
]) -> Self {
2164 let num_windows
= slice
.len().saturating_sub(N
- 1);
2165 Self { slice_head: slice.as_ptr(), num: num_windows, marker: PhantomData }
2169 #[unstable(feature = "array_windows", issue = "75027")]
2170 impl<'a
, T
, const N
: usize> Iterator
for ArrayWindows
<'a
, T
, N
> {
2171 type Item
= &'a
[T
; N
];
2174 fn next(&mut self) -> Option
<Self::Item
> {
2179 // This is safe because it's indexing into a slice guaranteed to be length > N.
2180 let ret
= unsafe { &*self.slice_head.cast::<[T; N]>() }
;
2181 // SAFETY: Guaranteed that there are at least 1 item remaining otherwise
2182 // earlier branch would've been hit
2183 self.slice_head
= unsafe { self.slice_head.add(1) }
;
2190 fn size_hint(&self) -> (usize, Option
<usize>) {
2191 (self.num
, Some(self.num
))
2195 fn count(self) -> usize {
2200 fn nth(&mut self, n
: usize) -> Option
<Self::Item
> {
2206 // This is safe because it's indexing into a slice guaranteed to be length > N.
2207 let ret
= unsafe { &*self.slice_head.add(n).cast::<[T; N]>() }
;
2208 // SAFETY: Guaranteed that there are at least n items remaining
2209 self.slice_head
= unsafe { self.slice_head.add(n + 1) }
;
2216 fn last(mut self) -> Option
<Self::Item
> {
2217 self.nth(self.num
.checked_sub(1)?
)
2221 #[unstable(feature = "array_windows", issue = "75027")]
2222 impl<'a
, T
, const N
: usize> DoubleEndedIterator
for ArrayWindows
<'a
, T
, N
> {
2224 fn next_back(&mut self) -> Option
<&'a
[T
; N
]> {
2228 // SAFETY: Guaranteed that there are n items remaining, n-1 for 0-indexing.
2229 let ret
= unsafe { &*self.slice_head.add(self.num - 1).cast::<[T; N]>() }
;
2235 fn nth_back(&mut self, n
: usize) -> Option
<&'a
[T
; N
]> {
2240 // SAFETY: Guaranteed that there are n items remaining, n-1 for 0-indexing.
2241 let ret
= unsafe { &*self.slice_head.add(self.num - (n + 1)).cast::<[T; N]>() }
;
2247 #[unstable(feature = "array_windows", issue = "75027")]
2248 impl<T
, const N
: usize> ExactSizeIterator
for ArrayWindows
<'_
, T
, N
> {
2249 fn is_empty(&self) -> bool
{
2254 /// An iterator over a slice in (non-overlapping) chunks (`N` elements at a
2255 /// time), starting at the beginning of the slice.
2257 /// When the slice len is not evenly divided by the chunk size, the last
2258 /// up to `N-1` elements will be omitted but can be retrieved from
2259 /// the [`remainder`] function from the iterator.
2261 /// This struct is created by the [`array_chunks`] method on [slices].
2266 /// #![feature(array_chunks)]
2268 /// let slice = ['l', 'o', 'r', 'e', 'm'];
2269 /// let iter = slice.array_chunks::<2>();
2272 /// [`array_chunks`]: slice::array_chunks
2273 /// [`remainder`]: ArrayChunks::remainder
2276 #[unstable(feature = "array_chunks", issue = "74985")]
2277 #[must_use = "iterators are lazy and do nothing unless consumed"]
2278 pub struct ArrayChunks
<'a
, T
: 'a
, const N
: usize> {
2279 iter
: Iter
<'a
, [T
; N
]>,
2283 impl<'a
, T
, const N
: usize> ArrayChunks
<'a
, T
, N
> {
2285 pub(super) fn new(slice
: &'a
[T
]) -> Self {
2286 let (array_slice
, rem
) = slice
.as_chunks();
2287 Self { iter: array_slice.iter(), rem }
2290 /// Returns the remainder of the original slice that is not going to be
2291 /// returned by the iterator. The returned slice has at most `N-1`
2294 #[unstable(feature = "array_chunks", issue = "74985")]
2295 pub fn remainder(&self) -> &'a
[T
] {
2300 // FIXME(#26925) Remove in favor of `#[derive(Clone)]`
2301 #[unstable(feature = "array_chunks", issue = "74985")]
2302 impl<T
, const N
: usize> Clone
for ArrayChunks
<'_
, T
, N
> {
2303 fn clone(&self) -> Self {
2304 ArrayChunks { iter: self.iter.clone(), rem: self.rem }
2308 #[unstable(feature = "array_chunks", issue = "74985")]
2309 impl<'a
, T
, const N
: usize> Iterator
for ArrayChunks
<'a
, T
, N
> {
2310 type Item
= &'a
[T
; N
];
2313 fn next(&mut self) -> Option
<&'a
[T
; N
]> {
2318 fn size_hint(&self) -> (usize, Option
<usize>) {
2319 self.iter
.size_hint()
2323 fn count(self) -> usize {
2328 fn nth(&mut self, n
: usize) -> Option
<Self::Item
> {
2333 fn last(self) -> Option
<Self::Item
> {
2337 unsafe fn __iterator_get_unchecked(&mut self, i
: usize) -> &'a
[T
; N
] {
2338 // SAFETY: The safety guarantees of `__iterator_get_unchecked` are
2339 // transferred to the caller.
2340 unsafe { self.iter.__iterator_get_unchecked(i) }
2344 #[unstable(feature = "array_chunks", issue = "74985")]
2345 impl<'a
, T
, const N
: usize> DoubleEndedIterator
for ArrayChunks
<'a
, T
, N
> {
2347 fn next_back(&mut self) -> Option
<&'a
[T
; N
]> {
2348 self.iter
.next_back()
2352 fn nth_back(&mut self, n
: usize) -> Option
<Self::Item
> {
2353 self.iter
.nth_back(n
)
2357 #[unstable(feature = "array_chunks", issue = "74985")]
2358 impl<T
, const N
: usize> ExactSizeIterator
for ArrayChunks
<'_
, T
, N
> {
2359 fn is_empty(&self) -> bool
{
2360 self.iter
.is_empty()
2364 #[unstable(feature = "trusted_len", issue = "37572")]
2365 unsafe impl<T
, const N
: usize> TrustedLen
for ArrayChunks
<'_
, T
, N
> {}
2367 #[unstable(feature = "array_chunks", issue = "74985")]
2368 impl<T
, const N
: usize> FusedIterator
for ArrayChunks
<'_
, T
, N
> {}
2371 #[unstable(feature = "array_chunks", issue = "74985")]
2372 unsafe impl<'a
, T
, const N
: usize> TrustedRandomAccess
for ArrayChunks
<'a
, T
, N
> {}
2375 #[unstable(feature = "array_chunks", issue = "74985")]
2376 unsafe impl<'a
, T
, const N
: usize> TrustedRandomAccessNoCoerce
for ArrayChunks
<'a
, T
, N
> {
2377 const MAY_HAVE_SIDE_EFFECT
: bool
= false;
2380 /// An iterator over a slice in (non-overlapping) mutable chunks (`N` elements
2381 /// at a time), starting at the beginning of the slice.
2383 /// When the slice len is not evenly divided by the chunk size, the last
2384 /// up to `N-1` elements will be omitted but can be retrieved from
2385 /// the [`into_remainder`] function from the iterator.
2387 /// This struct is created by the [`array_chunks_mut`] method on [slices].
2392 /// #![feature(array_chunks)]
2394 /// let mut slice = ['l', 'o', 'r', 'e', 'm'];
2395 /// let iter = slice.array_chunks_mut::<2>();
2398 /// [`array_chunks_mut`]: slice::array_chunks_mut
2399 /// [`into_remainder`]: ../../std/slice/struct.ArrayChunksMut.html#method.into_remainder
2402 #[unstable(feature = "array_chunks", issue = "74985")]
2403 #[must_use = "iterators are lazy and do nothing unless consumed"]
2404 pub struct ArrayChunksMut
<'a
, T
: 'a
, const N
: usize> {
2405 iter
: IterMut
<'a
, [T
; N
]>,
2409 impl<'a
, T
, const N
: usize> ArrayChunksMut
<'a
, T
, N
> {
2411 pub(super) fn new(slice
: &'a
mut [T
]) -> Self {
2412 let (array_slice
, rem
) = slice
.as_chunks_mut();
2413 Self { iter: array_slice.iter_mut(), rem }
2416 /// Returns the remainder of the original slice that is not going to be
2417 /// returned by the iterator. The returned slice has at most `N-1`
2419 #[must_use = "`self` will be dropped if the result is not used"]
2420 #[unstable(feature = "array_chunks", issue = "74985")]
2421 pub fn into_remainder(self) -> &'a
mut [T
] {
2426 #[unstable(feature = "array_chunks", issue = "74985")]
2427 impl<'a
, T
, const N
: usize> Iterator
for ArrayChunksMut
<'a
, T
, N
> {
2428 type Item
= &'a
mut [T
; N
];
2431 fn next(&mut self) -> Option
<&'a
mut [T
; N
]> {
2436 fn size_hint(&self) -> (usize, Option
<usize>) {
2437 self.iter
.size_hint()
2441 fn count(self) -> usize {
2446 fn nth(&mut self, n
: usize) -> Option
<Self::Item
> {
2451 fn last(self) -> Option
<Self::Item
> {
2455 unsafe fn __iterator_get_unchecked(&mut self, i
: usize) -> &'a
mut [T
; N
] {
2456 // SAFETY: The safety guarantees of `__iterator_get_unchecked` are transferred to
2458 unsafe { self.iter.__iterator_get_unchecked(i) }
2462 #[unstable(feature = "array_chunks", issue = "74985")]
2463 impl<'a
, T
, const N
: usize> DoubleEndedIterator
for ArrayChunksMut
<'a
, T
, N
> {
2465 fn next_back(&mut self) -> Option
<&'a
mut [T
; N
]> {
2466 self.iter
.next_back()
2470 fn nth_back(&mut self, n
: usize) -> Option
<Self::Item
> {
2471 self.iter
.nth_back(n
)
2475 #[unstable(feature = "array_chunks", issue = "74985")]
2476 impl<T
, const N
: usize> ExactSizeIterator
for ArrayChunksMut
<'_
, T
, N
> {
2477 fn is_empty(&self) -> bool
{
2478 self.iter
.is_empty()
2482 #[unstable(feature = "trusted_len", issue = "37572")]
2483 unsafe impl<T
, const N
: usize> TrustedLen
for ArrayChunksMut
<'_
, T
, N
> {}
2485 #[unstable(feature = "array_chunks", issue = "74985")]
2486 impl<T
, const N
: usize> FusedIterator
for ArrayChunksMut
<'_
, T
, N
> {}
2489 #[unstable(feature = "array_chunks", issue = "74985")]
2490 unsafe impl<'a
, T
, const N
: usize> TrustedRandomAccess
for ArrayChunksMut
<'a
, T
, N
> {}
2493 #[unstable(feature = "array_chunks", issue = "74985")]
2494 unsafe impl<'a
, T
, const N
: usize> TrustedRandomAccessNoCoerce
for ArrayChunksMut
<'a
, T
, N
> {
2495 const MAY_HAVE_SIDE_EFFECT
: bool
= false;
2498 /// An iterator over a slice in (non-overlapping) chunks (`chunk_size` elements at a
2499 /// time), starting at the end of the slice.
2501 /// When the slice len is not evenly divided by the chunk size, the last slice
2502 /// of the iteration will be the remainder.
2504 /// This struct is created by the [`rchunks`] method on [slices].
2509 /// let slice = ['l', 'o', 'r', 'e', 'm'];
2510 /// let iter = slice.rchunks(2);
2513 /// [`rchunks`]: slice::rchunks
2516 #[stable(feature = "rchunks", since = "1.31.0")]
2517 #[must_use = "iterators are lazy and do nothing unless consumed"]
2518 pub struct RChunks
<'a
, T
: 'a
> {
2523 impl<'a
, T
: 'a
> RChunks
<'a
, T
> {
2525 pub(super) fn new(slice
: &'a
[T
], size
: usize) -> Self {
2526 Self { v: slice, chunk_size: size }
2530 // FIXME(#26925) Remove in favor of `#[derive(Clone)]`
2531 #[stable(feature = "rchunks", since = "1.31.0")]
2532 impl<T
> Clone
for RChunks
<'_
, T
> {
2533 fn clone(&self) -> Self {
2534 RChunks { v: self.v, chunk_size: self.chunk_size }
2538 #[stable(feature = "rchunks", since = "1.31.0")]
2539 impl<'a
, T
> Iterator
for RChunks
<'a
, T
> {
2540 type Item
= &'a
[T
];
2543 fn next(&mut self) -> Option
<&'a
[T
]> {
2544 if self.v
.is_empty() {
2547 let len
= self.v
.len();
2548 let chunksz
= cmp
::min(len
, self.chunk_size
);
2549 // SAFETY: split_at_unchecked just requires the argument be less
2550 // than the length. This could only happen if the expression `len -
2551 // chunksz` overflows. This could only happen if `chunksz > len`,
2552 // which is impossible as we initialize it as the `min` of `len` and
2553 // `self.chunk_size`.
2554 let (fst
, snd
) = unsafe { self.v.split_at_unchecked(len - chunksz) }
;
2561 fn size_hint(&self) -> (usize, Option
<usize>) {
2562 if self.v
.is_empty() {
2565 let n
= self.v
.len() / self.chunk_size
;
2566 let rem
= self.v
.len() % self.chunk_size
;
2567 let n
= if rem
> 0 { n + 1 }
else { n }
;
2573 fn count(self) -> usize {
2578 fn nth(&mut self, n
: usize) -> Option
<Self::Item
> {
2579 let (end
, overflow
) = n
.overflowing_mul(self.chunk_size
);
2580 if end
>= self.v
.len() || overflow
{
2584 // Can't underflow because of the check above
2585 let end
= self.v
.len() - end
;
2586 let start
= match end
.checked_sub(self.chunk_size
) {
2590 let nth
= &self.v
[start
..end
];
2591 self.v
= &self.v
[0..start
];
2597 fn last(self) -> Option
<Self::Item
> {
2598 if self.v
.is_empty() {
2601 let rem
= self.v
.len() % self.chunk_size
;
2602 let end
= if rem
== 0 { self.chunk_size }
else { rem }
;
2603 Some(&self.v
[0..end
])
2607 unsafe fn __iterator_get_unchecked(&mut self, idx
: usize) -> Self::Item
{
2608 let end
= self.v
.len() - idx
* self.chunk_size
;
2609 let start
= match end
.checked_sub(self.chunk_size
) {
2611 Some(start
) => start
,
2613 // SAFETY: mostly identical to `Chunks::__iterator_get_unchecked`.
2614 unsafe { from_raw_parts(self.v.as_ptr().add(start), end - start) }
2618 #[stable(feature = "rchunks", since = "1.31.0")]
2619 impl<'a
, T
> DoubleEndedIterator
for RChunks
<'a
, T
> {
2621 fn next_back(&mut self) -> Option
<&'a
[T
]> {
2622 if self.v
.is_empty() {
2625 let remainder
= self.v
.len() % self.chunk_size
;
2626 let chunksz
= if remainder
!= 0 { remainder }
else { self.chunk_size }
;
2627 // SAFETY: similar to Chunks::next_back
2628 let (fst
, snd
) = unsafe { self.v.split_at_unchecked(chunksz) }
;
2635 fn nth_back(&mut self, n
: usize) -> Option
<Self::Item
> {
2636 let len
= self.len();
2641 // can't underflow because `n < len`
2642 let offset_from_end
= (len
- 1 - n
) * self.chunk_size
;
2643 let end
= self.v
.len() - offset_from_end
;
2644 let start
= end
.saturating_sub(self.chunk_size
);
2645 let nth_back
= &self.v
[start
..end
];
2646 self.v
= &self.v
[end
..];
2652 #[stable(feature = "rchunks", since = "1.31.0")]
2653 impl<T
> ExactSizeIterator
for RChunks
<'_
, T
> {}
2655 #[unstable(feature = "trusted_len", issue = "37572")]
2656 unsafe impl<T
> TrustedLen
for RChunks
<'_
, T
> {}
2658 #[stable(feature = "rchunks", since = "1.31.0")]
2659 impl<T
> FusedIterator
for RChunks
<'_
, T
> {}
2662 #[unstable(feature = "trusted_random_access", issue = "none")]
2663 unsafe impl<'a
, T
> TrustedRandomAccess
for RChunks
<'a
, T
> {}
2666 #[unstable(feature = "trusted_random_access", issue = "none")]
2667 unsafe impl<'a
, T
> TrustedRandomAccessNoCoerce
for RChunks
<'a
, T
> {
2668 const MAY_HAVE_SIDE_EFFECT
: bool
= false;
2671 /// An iterator over a slice in (non-overlapping) mutable chunks (`chunk_size`
2672 /// elements at a time), starting at the end of the slice.
2674 /// When the slice len is not evenly divided by the chunk size, the last slice
2675 /// of the iteration will be the remainder.
2677 /// This struct is created by the [`rchunks_mut`] method on [slices].
2682 /// let mut slice = ['l', 'o', 'r', 'e', 'm'];
2683 /// let iter = slice.rchunks_mut(2);
2686 /// [`rchunks_mut`]: slice::rchunks_mut
2689 #[stable(feature = "rchunks", since = "1.31.0")]
2690 #[must_use = "iterators are lazy and do nothing unless consumed"]
2691 pub struct RChunksMut
<'a
, T
: 'a
> {
2693 /// This slice pointer must point at a valid region of `T` with at least length `v.len()`. Normally,
2694 /// those requirements would mean that we could instead use a `&mut [T]` here, but we cannot
2695 /// because `__iterator_get_unchecked` needs to return `&mut [T]`, which guarantees certain aliasing
2696 /// properties that we cannot uphold if we hold on to the full original `&mut [T]`. Wrapping a raw
2697 /// slice instead lets us hand out non-overlapping `&mut [T]` subslices of the slice we wrap.
2700 _marker
: PhantomData
<&'a
mut T
>,
2703 impl<'a
, T
: 'a
> RChunksMut
<'a
, T
> {
2705 pub(super) fn new(slice
: &'a
mut [T
], size
: usize) -> Self {
2706 Self { v: slice, chunk_size: size, _marker: PhantomData }
2710 #[stable(feature = "rchunks", since = "1.31.0")]
2711 impl<'a
, T
> Iterator
for RChunksMut
<'a
, T
> {
2712 type Item
= &'a
mut [T
];
2715 fn next(&mut self) -> Option
<&'a
mut [T
]> {
2716 if self.v
.is_empty() {
2719 let sz
= cmp
::min(self.v
.len(), self.chunk_size
);
2720 let len
= self.v
.len();
2721 // SAFETY: split_at_mut_unchecked just requires the argument be less
2722 // than the length. This could only happen if the expression
2723 // `len - sz` overflows. This could only happen if `sz >
2724 // len`, which is impossible as we initialize it as the `min` of
2725 // `self.v.len()` (e.g. `len`) and `self.chunk_size`.
2726 let (head
, tail
) = unsafe { self.v.split_at_mut_unchecked(len - sz) }
;
2728 // SAFETY: Nothing else points to or will point to the contents of this slice.
2729 Some(unsafe { &mut *tail }
)
2734 fn size_hint(&self) -> (usize, Option
<usize>) {
2735 if self.v
.is_empty() {
2738 let n
= self.v
.len() / self.chunk_size
;
2739 let rem
= self.v
.len() % self.chunk_size
;
2740 let n
= if rem
> 0 { n + 1 }
else { n }
;
2746 fn count(self) -> usize {
2751 fn nth(&mut self, n
: usize) -> Option
<&'a
mut [T
]> {
2752 let (end
, overflow
) = n
.overflowing_mul(self.chunk_size
);
2753 if end
>= self.v
.len() || overflow
{
2757 // Can't underflow because of the check above
2758 let end
= self.v
.len() - end
;
2759 let start
= match end
.checked_sub(self.chunk_size
) {
2763 // SAFETY: This type ensures that self.v is a valid pointer with a correct len.
2764 // Therefore the bounds check in split_at_mut guarantees the split point is inbounds.
2765 let (head
, tail
) = unsafe { self.v.split_at_mut(start) }
;
2766 // SAFETY: This type ensures that self.v is a valid pointer with a correct len.
2767 // Therefore the bounds check in split_at_mut guarantees the split point is inbounds.
2768 let (nth
, _
) = unsafe { tail.split_at_mut(end - start) }
;
2770 // SAFETY: Nothing else points to or will point to the contents of this slice.
2771 Some(unsafe { &mut *nth }
)
2776 fn last(self) -> Option
<Self::Item
> {
2777 if self.v
.is_empty() {
2780 let rem
= self.v
.len() % self.chunk_size
;
2781 let end
= if rem
== 0 { self.chunk_size }
else { rem }
;
2782 // SAFETY: Nothing else points to or will point to the contents of this slice.
2783 Some(unsafe { &mut *self.v.get_unchecked_mut(0..end) }
)
2787 unsafe fn __iterator_get_unchecked(&mut self, idx
: usize) -> Self::Item
{
2788 let end
= self.v
.len() - idx
* self.chunk_size
;
2789 let start
= match end
.checked_sub(self.chunk_size
) {
2791 Some(start
) => start
,
2793 // SAFETY: see comments for `RChunks::__iterator_get_unchecked` and
2794 // `ChunksMut::__iterator_get_unchecked`, `self.v`.
2795 unsafe { from_raw_parts_mut(self.v.as_mut_ptr().add(start), end - start) }
2799 #[stable(feature = "rchunks", since = "1.31.0")]
2800 impl<'a
, T
> DoubleEndedIterator
for RChunksMut
<'a
, T
> {
2802 fn next_back(&mut self) -> Option
<&'a
mut [T
]> {
2803 if self.v
.is_empty() {
2806 let remainder
= self.v
.len() % self.chunk_size
;
2807 let sz
= if remainder
!= 0 { remainder }
else { self.chunk_size }
;
2808 // SAFETY: Similar to `Chunks::next_back`
2809 let (head
, tail
) = unsafe { self.v.split_at_mut_unchecked(sz) }
;
2811 // SAFETY: Nothing else points to or will point to the contents of this slice.
2812 Some(unsafe { &mut *head }
)
2817 fn nth_back(&mut self, n
: usize) -> Option
<Self::Item
> {
2818 let len
= self.len();
2823 // can't underflow because `n < len`
2824 let offset_from_end
= (len
- 1 - n
) * self.chunk_size
;
2825 let end
= self.v
.len() - offset_from_end
;
2826 let start
= end
.saturating_sub(self.chunk_size
);
2827 // SAFETY: The self.v contract ensures that any split_at_mut is valid.
2828 let (tmp
, tail
) = unsafe { self.v.split_at_mut(end) }
;
2829 // SAFETY: The self.v contract ensures that any split_at_mut is valid.
2830 let (_
, nth_back
) = unsafe { tmp.split_at_mut(start) }
;
2832 // SAFETY: Nothing else points to or will point to the contents of this slice.
2833 Some(unsafe { &mut *nth_back }
)
2838 #[stable(feature = "rchunks", since = "1.31.0")]
2839 impl<T
> ExactSizeIterator
for RChunksMut
<'_
, T
> {}
2841 #[unstable(feature = "trusted_len", issue = "37572")]
2842 unsafe impl<T
> TrustedLen
for RChunksMut
<'_
, T
> {}
2844 #[stable(feature = "rchunks", since = "1.31.0")]
2845 impl<T
> FusedIterator
for RChunksMut
<'_
, T
> {}
2848 #[unstable(feature = "trusted_random_access", issue = "none")]
2849 unsafe impl<'a
, T
> TrustedRandomAccess
for RChunksMut
<'a
, T
> {}
2852 #[unstable(feature = "trusted_random_access", issue = "none")]
2853 unsafe impl<'a
, T
> TrustedRandomAccessNoCoerce
for RChunksMut
<'a
, T
> {
2854 const MAY_HAVE_SIDE_EFFECT
: bool
= false;
2857 #[stable(feature = "rchunks", since = "1.31.0")]
2858 unsafe impl<T
> Send
for RChunksMut
<'_
, T
> where T
: Send {}
2860 #[stable(feature = "rchunks", since = "1.31.0")]
2861 unsafe impl<T
> Sync
for RChunksMut
<'_
, T
> where T
: Sync {}
2863 /// An iterator over a slice in (non-overlapping) chunks (`chunk_size` elements at a
2864 /// time), starting at the end of the slice.
2866 /// When the slice len is not evenly divided by the chunk size, the last
2867 /// up to `chunk_size-1` elements will be omitted but can be retrieved from
2868 /// the [`remainder`] function from the iterator.
2870 /// This struct is created by the [`rchunks_exact`] method on [slices].
2875 /// let slice = ['l', 'o', 'r', 'e', 'm'];
2876 /// let iter = slice.rchunks_exact(2);
2879 /// [`rchunks_exact`]: slice::rchunks_exact
2880 /// [`remainder`]: RChunksExact::remainder
2883 #[stable(feature = "rchunks", since = "1.31.0")]
2884 #[must_use = "iterators are lazy and do nothing unless consumed"]
2885 pub struct RChunksExact
<'a
, T
: 'a
> {
2891 impl<'a
, T
> RChunksExact
<'a
, T
> {
2893 pub(super) fn new(slice
: &'a
[T
], chunk_size
: usize) -> Self {
2894 let rem
= slice
.len() % chunk_size
;
2895 // SAFETY: 0 <= rem <= slice.len() by construction above
2896 let (fst
, snd
) = unsafe { slice.split_at_unchecked(rem) }
;
2897 Self { v: snd, rem: fst, chunk_size }
2900 /// Returns the remainder of the original slice that is not going to be
2901 /// returned by the iterator. The returned slice has at most `chunk_size-1`
2907 /// let slice = ['l', 'o', 'r', 'e', 'm'];
2908 /// let mut iter = slice.rchunks_exact(2);
2909 /// assert_eq!(iter.remainder(), &['l'][..]);
2910 /// assert_eq!(iter.next(), Some(&['e', 'm'][..]));
2911 /// assert_eq!(iter.remainder(), &['l'][..]);
2912 /// assert_eq!(iter.next(), Some(&['o', 'r'][..]));
2913 /// assert_eq!(iter.remainder(), &['l'][..]);
2914 /// assert_eq!(iter.next(), None);
2915 /// assert_eq!(iter.remainder(), &['l'][..]);
2918 #[stable(feature = "rchunks", since = "1.31.0")]
2919 pub fn remainder(&self) -> &'a
[T
] {
2924 // FIXME(#26925) Remove in favor of `#[derive(Clone)]`
2925 #[stable(feature = "rchunks", since = "1.31.0")]
2926 impl<'a
, T
> Clone
for RChunksExact
<'a
, T
> {
2927 fn clone(&self) -> RChunksExact
<'a
, T
> {
2928 RChunksExact { v: self.v, rem: self.rem, chunk_size: self.chunk_size }
2932 #[stable(feature = "rchunks", since = "1.31.0")]
2933 impl<'a
, T
> Iterator
for RChunksExact
<'a
, T
> {
2934 type Item
= &'a
[T
];
2937 fn next(&mut self) -> Option
<&'a
[T
]> {
2938 if self.v
.len() < self.chunk_size
{
2941 let (fst
, snd
) = self.v
.split_at(self.v
.len() - self.chunk_size
);
2948 fn size_hint(&self) -> (usize, Option
<usize>) {
2949 let n
= self.v
.len() / self.chunk_size
;
2954 fn count(self) -> usize {
2959 fn nth(&mut self, n
: usize) -> Option
<Self::Item
> {
2960 let (end
, overflow
) = n
.overflowing_mul(self.chunk_size
);
2961 if end
>= self.v
.len() || overflow
{
2965 let (fst
, _
) = self.v
.split_at(self.v
.len() - end
);
2972 fn last(mut self) -> Option
<Self::Item
> {
2976 unsafe fn __iterator_get_unchecked(&mut self, idx
: usize) -> Self::Item
{
2977 let end
= self.v
.len() - idx
* self.chunk_size
;
2978 let start
= end
- self.chunk_size
;
2979 // SAFETY: mostly identical to `Chunks::__iterator_get_unchecked`.
2980 unsafe { from_raw_parts(self.v.as_ptr().add(start), self.chunk_size) }
2984 #[stable(feature = "rchunks", since = "1.31.0")]
2985 impl<'a
, T
> DoubleEndedIterator
for RChunksExact
<'a
, T
> {
2987 fn next_back(&mut self) -> Option
<&'a
[T
]> {
2988 if self.v
.len() < self.chunk_size
{
2991 let (fst
, snd
) = self.v
.split_at(self.chunk_size
);
2998 fn nth_back(&mut self, n
: usize) -> Option
<Self::Item
> {
2999 let len
= self.len();
3004 // now that we know that `n` corresponds to a chunk,
3005 // none of these operations can underflow/overflow
3006 let offset
= (len
- n
) * self.chunk_size
;
3007 let start
= self.v
.len() - offset
;
3008 let end
= start
+ self.chunk_size
;
3009 let nth_back
= &self.v
[start
..end
];
3010 self.v
= &self.v
[end
..];
3016 #[stable(feature = "rchunks", since = "1.31.0")]
3017 impl<'a
, T
> ExactSizeIterator
for RChunksExact
<'a
, T
> {
3018 fn is_empty(&self) -> bool
{
3023 #[unstable(feature = "trusted_len", issue = "37572")]
3024 unsafe impl<T
> TrustedLen
for RChunksExact
<'_
, T
> {}
3026 #[stable(feature = "rchunks", since = "1.31.0")]
3027 impl<T
> FusedIterator
for RChunksExact
<'_
, T
> {}
3030 #[unstable(feature = "trusted_random_access", issue = "none")]
3031 unsafe impl<'a
, T
> TrustedRandomAccess
for RChunksExact
<'a
, T
> {}
3034 #[unstable(feature = "trusted_random_access", issue = "none")]
3035 unsafe impl<'a
, T
> TrustedRandomAccessNoCoerce
for RChunksExact
<'a
, T
> {
3036 const MAY_HAVE_SIDE_EFFECT
: bool
= false;
3039 /// An iterator over a slice in (non-overlapping) mutable chunks (`chunk_size`
3040 /// elements at a time), starting at the end of the slice.
3042 /// When the slice len is not evenly divided by the chunk size, the last up to
3043 /// `chunk_size-1` elements will be omitted but can be retrieved from the
3044 /// [`into_remainder`] function from the iterator.
3046 /// This struct is created by the [`rchunks_exact_mut`] method on [slices].
3051 /// let mut slice = ['l', 'o', 'r', 'e', 'm'];
3052 /// let iter = slice.rchunks_exact_mut(2);
3055 /// [`rchunks_exact_mut`]: slice::rchunks_exact_mut
3056 /// [`into_remainder`]: RChunksExactMut::into_remainder
3059 #[stable(feature = "rchunks", since = "1.31.0")]
3060 #[must_use = "iterators are lazy and do nothing unless consumed"]
3061 pub struct RChunksExactMut
<'a
, T
: 'a
> {
3063 /// This slice pointer must point at a valid region of `T` with at least length `v.len()`. Normally,
3064 /// those requirements would mean that we could instead use a `&mut [T]` here, but we cannot
3065 /// because `__iterator_get_unchecked` needs to return `&mut [T]`, which guarantees certain aliasing
3066 /// properties that we cannot uphold if we hold on to the full original `&mut [T]`. Wrapping a raw
3067 /// slice instead lets us hand out non-overlapping `&mut [T]` subslices of the slice we wrap.
3073 impl<'a
, T
> RChunksExactMut
<'a
, T
> {
3075 pub(super) fn new(slice
: &'a
mut [T
], chunk_size
: usize) -> Self {
3076 let rem
= slice
.len() % chunk_size
;
3077 // SAFETY: 0 <= rem <= slice.len() by construction above
3078 let (fst
, snd
) = unsafe { slice.split_at_mut_unchecked(rem) }
;
3079 Self { v: snd, rem: fst, chunk_size }
3082 /// Returns the remainder of the original slice that is not going to be
3083 /// returned by the iterator. The returned slice has at most `chunk_size-1`
3085 #[must_use = "`self` will be dropped if the result is not used"]
3086 #[stable(feature = "rchunks", since = "1.31.0")]
3087 pub fn into_remainder(self) -> &'a
mut [T
] {
3092 #[stable(feature = "rchunks", since = "1.31.0")]
3093 impl<'a
, T
> Iterator
for RChunksExactMut
<'a
, T
> {
3094 type Item
= &'a
mut [T
];
3097 fn next(&mut self) -> Option
<&'a
mut [T
]> {
3098 if self.v
.len() < self.chunk_size
{
3101 let len
= self.v
.len();
3102 // SAFETY: The self.v contract ensures that any split_at_mut is valid.
3103 let (head
, tail
) = unsafe { self.v.split_at_mut(len - self.chunk_size) }
;
3105 // SAFETY: Nothing else points to or will point to the contents of this slice.
3106 Some(unsafe { &mut *tail }
)
3111 fn size_hint(&self) -> (usize, Option
<usize>) {
3112 let n
= self.v
.len() / self.chunk_size
;
3117 fn count(self) -> usize {
3122 fn nth(&mut self, n
: usize) -> Option
<&'a
mut [T
]> {
3123 let (end
, overflow
) = n
.overflowing_mul(self.chunk_size
);
3124 if end
>= self.v
.len() || overflow
{
3128 let len
= self.v
.len();
3129 // SAFETY: The self.v contract ensures that any split_at_mut is valid.
3130 let (fst
, _
) = unsafe { self.v.split_at_mut(len - end) }
;
3137 fn last(mut self) -> Option
<Self::Item
> {
3141 unsafe fn __iterator_get_unchecked(&mut self, idx
: usize) -> Self::Item
{
3142 let end
= self.v
.len() - idx
* self.chunk_size
;
3143 let start
= end
- self.chunk_size
;
3144 // SAFETY: see comments for `RChunksMut::__iterator_get_unchecked` and `self.v`.
3145 unsafe { from_raw_parts_mut(self.v.as_mut_ptr().add(start), self.chunk_size) }
3149 #[stable(feature = "rchunks", since = "1.31.0")]
3150 impl<'a
, T
> DoubleEndedIterator
for RChunksExactMut
<'a
, T
> {
3152 fn next_back(&mut self) -> Option
<&'a
mut [T
]> {
3153 if self.v
.len() < self.chunk_size
{
3156 // SAFETY: The self.v contract ensures that any split_at_mut is valid.
3157 let (head
, tail
) = unsafe { self.v.split_at_mut(self.chunk_size) }
;
3159 // SAFETY: Nothing else points to or will point to the contents of this slice.
3160 Some(unsafe { &mut *head }
)
3165 fn nth_back(&mut self, n
: usize) -> Option
<Self::Item
> {
3166 let len
= self.len();
3171 // now that we know that `n` corresponds to a chunk,
3172 // none of these operations can underflow/overflow
3173 let offset
= (len
- n
) * self.chunk_size
;
3174 let start
= self.v
.len() - offset
;
3175 let end
= start
+ self.chunk_size
;
3176 // SAFETY: The self.v contract ensures that any split_at_mut is valid.
3177 let (tmp
, tail
) = unsafe { self.v.split_at_mut(end) }
;
3178 // SAFETY: The self.v contract ensures that any split_at_mut is valid.
3179 let (_
, nth_back
) = unsafe { tmp.split_at_mut(start) }
;
3181 // SAFETY: Nothing else points to or will point to the contents of this slice.
3182 Some(unsafe { &mut *nth_back }
)
3187 #[stable(feature = "rchunks", since = "1.31.0")]
3188 impl<T
> ExactSizeIterator
for RChunksExactMut
<'_
, T
> {
3189 fn is_empty(&self) -> bool
{
3194 #[unstable(feature = "trusted_len", issue = "37572")]
3195 unsafe impl<T
> TrustedLen
for RChunksExactMut
<'_
, T
> {}
3197 #[stable(feature = "rchunks", since = "1.31.0")]
3198 impl<T
> FusedIterator
for RChunksExactMut
<'_
, T
> {}
3201 #[unstable(feature = "trusted_random_access", issue = "none")]
3202 unsafe impl<'a
, T
> TrustedRandomAccess
for RChunksExactMut
<'a
, T
> {}
3205 #[unstable(feature = "trusted_random_access", issue = "none")]
3206 unsafe impl<'a
, T
> TrustedRandomAccessNoCoerce
for RChunksExactMut
<'a
, T
> {
3207 const MAY_HAVE_SIDE_EFFECT
: bool
= false;
3210 #[stable(feature = "rchunks", since = "1.31.0")]
3211 unsafe impl<T
> Send
for RChunksExactMut
<'_
, T
> where T
: Send {}
3213 #[stable(feature = "rchunks", since = "1.31.0")]
3214 unsafe impl<T
> Sync
for RChunksExactMut
<'_
, T
> where T
: Sync {}
3217 #[unstable(feature = "trusted_random_access", issue = "none")]
3218 unsafe impl<'a
, T
> TrustedRandomAccess
for Iter
<'a
, T
> {}
3221 #[unstable(feature = "trusted_random_access", issue = "none")]
3222 unsafe impl<'a
, T
> TrustedRandomAccessNoCoerce
for Iter
<'a
, T
> {
3223 const MAY_HAVE_SIDE_EFFECT
: bool
= false;
3227 #[unstable(feature = "trusted_random_access", issue = "none")]
3228 unsafe impl<'a
, T
> TrustedRandomAccess
for IterMut
<'a
, T
> {}
3231 #[unstable(feature = "trusted_random_access", issue = "none")]
3232 unsafe impl<'a
, T
> TrustedRandomAccessNoCoerce
for IterMut
<'a
, T
> {
3233 const MAY_HAVE_SIDE_EFFECT
: bool
= false;
3236 /// An iterator over slice in (non-overlapping) chunks separated by a predicate.
3238 /// This struct is created by the [`group_by`] method on [slices].
3240 /// [`group_by`]: slice::group_by
3242 #[unstable(feature = "slice_group_by", issue = "80552")]
3243 #[must_use = "iterators are lazy and do nothing unless consumed"]
3244 pub struct GroupBy
<'a
, T
: 'a
, P
> {
3249 #[unstable(feature = "slice_group_by", issue = "80552")]
3250 impl<'a
, T
: 'a
, P
> GroupBy
<'a
, T
, P
> {
3251 pub(super) fn new(slice
: &'a
[T
], predicate
: P
) -> Self {
3252 GroupBy { slice, predicate }
3256 #[unstable(feature = "slice_group_by", issue = "80552")]
3257 impl<'a
, T
: 'a
, P
> Iterator
for GroupBy
<'a
, T
, P
>
3259 P
: FnMut(&T
, &T
) -> bool
,
3261 type Item
= &'a
[T
];
3264 fn next(&mut self) -> Option
<Self::Item
> {
3265 if self.slice
.is_empty() {
3269 let mut iter
= self.slice
.windows(2);
3270 while let Some([l
, r
]) = iter
.next() {
3271 if (self.predicate
)(l
, r
) { len += 1 }
else { break }
3273 let (head
, tail
) = self.slice
.split_at(len
);
3280 fn size_hint(&self) -> (usize, Option
<usize>) {
3281 if self.slice
.is_empty() { (0, Some(0)) }
else { (1, Some(self.slice.len())) }
3285 fn last(mut self) -> Option
<Self::Item
> {
3290 #[unstable(feature = "slice_group_by", issue = "80552")]
3291 impl<'a
, T
: 'a
, P
> DoubleEndedIterator
for GroupBy
<'a
, T
, P
>
3293 P
: FnMut(&T
, &T
) -> bool
,
3296 fn next_back(&mut self) -> Option
<Self::Item
> {
3297 if self.slice
.is_empty() {
3301 let mut iter
= self.slice
.windows(2);
3302 while let Some([l
, r
]) = iter
.next_back() {
3303 if (self.predicate
)(l
, r
) { len += 1 }
else { break }
3305 let (head
, tail
) = self.slice
.split_at(self.slice
.len() - len
);
3312 #[unstable(feature = "slice_group_by", issue = "80552")]
3313 impl<'a
, T
: 'a
, P
> FusedIterator
for GroupBy
<'a
, T
, P
> where P
: FnMut(&T
, &T
) -> bool {}
3315 #[unstable(feature = "slice_group_by", issue = "80552")]
3316 impl<'a
, T
: 'a
+ fmt
::Debug
, P
> fmt
::Debug
for GroupBy
<'a
, T
, P
> {
3317 fn fmt(&self, f
: &mut fmt
::Formatter
<'_
>) -> fmt
::Result
{
3318 f
.debug_struct("GroupBy").field("slice", &self.slice
).finish()
3322 /// An iterator over slice in (non-overlapping) mutable chunks separated
3325 /// This struct is created by the [`group_by_mut`] method on [slices].
3327 /// [`group_by_mut`]: slice::group_by_mut
3329 #[unstable(feature = "slice_group_by", issue = "80552")]
3330 #[must_use = "iterators are lazy and do nothing unless consumed"]
3331 pub struct GroupByMut
<'a
, T
: 'a
, P
> {
3336 #[unstable(feature = "slice_group_by", issue = "80552")]
3337 impl<'a
, T
: 'a
, P
> GroupByMut
<'a
, T
, P
> {
3338 pub(super) fn new(slice
: &'a
mut [T
], predicate
: P
) -> Self {
3339 GroupByMut { slice, predicate }
3343 #[unstable(feature = "slice_group_by", issue = "80552")]
3344 impl<'a
, T
: 'a
, P
> Iterator
for GroupByMut
<'a
, T
, P
>
3346 P
: FnMut(&T
, &T
) -> bool
,
3348 type Item
= &'a
mut [T
];
3351 fn next(&mut self) -> Option
<Self::Item
> {
3352 if self.slice
.is_empty() {
3356 let mut iter
= self.slice
.windows(2);
3357 while let Some([l
, r
]) = iter
.next() {
3358 if (self.predicate
)(l
, r
) { len += 1 }
else { break }
3360 let slice
= mem
::take(&mut self.slice
);
3361 let (head
, tail
) = slice
.split_at_mut(len
);
3368 fn size_hint(&self) -> (usize, Option
<usize>) {
3369 if self.slice
.is_empty() { (0, Some(0)) }
else { (1, Some(self.slice.len())) }
3373 fn last(mut self) -> Option
<Self::Item
> {
3378 #[unstable(feature = "slice_group_by", issue = "80552")]
3379 impl<'a
, T
: 'a
, P
> DoubleEndedIterator
for GroupByMut
<'a
, T
, P
>
3381 P
: FnMut(&T
, &T
) -> bool
,
3384 fn next_back(&mut self) -> Option
<Self::Item
> {
3385 if self.slice
.is_empty() {
3389 let mut iter
= self.slice
.windows(2);
3390 while let Some([l
, r
]) = iter
.next_back() {
3391 if (self.predicate
)(l
, r
) { len += 1 }
else { break }
3393 let slice
= mem
::take(&mut self.slice
);
3394 let (head
, tail
) = slice
.split_at_mut(slice
.len() - len
);
3401 #[unstable(feature = "slice_group_by", issue = "80552")]
3402 impl<'a
, T
: 'a
, P
> FusedIterator
for GroupByMut
<'a
, T
, P
> where P
: FnMut(&T
, &T
) -> bool {}
3404 #[unstable(feature = "slice_group_by", issue = "80552")]
3405 impl<'a
, T
: 'a
+ fmt
::Debug
, P
> fmt
::Debug
for GroupByMut
<'a
, T
, P
> {
3406 fn fmt(&self, f
: &mut fmt
::Formatter
<'_
>) -> fmt
::Result
{
3407 f
.debug_struct("GroupByMut").field("slice", &self.slice
).finish()