]> git.proxmox.com Git - rustc.git/blob - library/core/src/slice/iter.rs
New upstream version 1.53.0+dfsg1
[rustc.git] / library / core / src / slice / iter.rs
1 // ignore-tidy-filelength
2 //! Definitions of a bunch of iterators for `[T]`.
3
4 #[macro_use] // import iterator! and forward_iterator!
5 mod macros;
6
7 use crate::cmp;
8 use crate::cmp::Ordering;
9 use crate::fmt;
10 use crate::intrinsics::{assume, exact_div, unchecked_sub};
11 use crate::iter::{FusedIterator, TrustedLen, TrustedRandomAccess};
12 use crate::marker::{PhantomData, Send, Sized, Sync};
13 use crate::mem;
14 use crate::num::NonZeroUsize;
15 use crate::ptr::NonNull;
16
17 use super::{from_raw_parts, from_raw_parts_mut};
18
19 #[stable(feature = "rust1", since = "1.0.0")]
20 impl<'a, T> IntoIterator for &'a [T] {
21 type Item = &'a T;
22 type IntoIter = Iter<'a, T>;
23
24 fn into_iter(self) -> Iter<'a, T> {
25 self.iter()
26 }
27 }
28
29 #[stable(feature = "rust1", since = "1.0.0")]
30 impl<'a, T> IntoIterator for &'a mut [T] {
31 type Item = &'a mut T;
32 type IntoIter = IterMut<'a, T>;
33
34 fn into_iter(self) -> IterMut<'a, T> {
35 self.iter_mut()
36 }
37 }
38
39 // Macro helper functions
40 #[inline(always)]
41 fn size_from_ptr<T>(_: *const T) -> usize {
42 mem::size_of::<T>()
43 }
44
45 /// Immutable slice iterator
46 ///
47 /// This struct is created by the [`iter`] method on [slices].
48 ///
49 /// # Examples
50 ///
51 /// Basic usage:
52 ///
53 /// ```
54 /// // First, we declare a type which has `iter` method to get the `Iter` struct (`&[usize]` here):
55 /// let slice = &[1, 2, 3];
56 ///
57 /// // Then, we iterate over it:
58 /// for element in slice.iter() {
59 /// println!("{}", element);
60 /// }
61 /// ```
62 ///
63 /// [`iter`]: slice::iter
64 /// [slices]: slice
65 #[stable(feature = "rust1", since = "1.0.0")]
66 pub struct Iter<'a, T: 'a> {
67 ptr: NonNull<T>,
68 end: *const T, // If T is a ZST, this is actually ptr+len. This encoding is picked so that
69 // ptr == end is a quick test for the Iterator being empty, that works
70 // for both ZST and non-ZST.
71 _marker: PhantomData<&'a T>,
72 }
73
74 #[stable(feature = "core_impl_debug", since = "1.9.0")]
75 impl<T: fmt::Debug> fmt::Debug for Iter<'_, T> {
76 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
77 f.debug_tuple("Iter").field(&self.as_slice()).finish()
78 }
79 }
80
81 #[stable(feature = "rust1", since = "1.0.0")]
82 unsafe impl<T: Sync> Sync for Iter<'_, T> {}
83 #[stable(feature = "rust1", since = "1.0.0")]
84 unsafe impl<T: Sync> Send for Iter<'_, T> {}
85
86 impl<'a, T> Iter<'a, T> {
87 #[inline]
88 pub(super) fn new(slice: &'a [T]) -> Self {
89 let ptr = slice.as_ptr();
90 // SAFETY: Similar to `IterMut::new`.
91 unsafe {
92 assume(!ptr.is_null());
93
94 let end = if mem::size_of::<T>() == 0 {
95 (ptr as *const u8).wrapping_add(slice.len()) as *const T
96 } else {
97 ptr.add(slice.len())
98 };
99
100 Self { ptr: NonNull::new_unchecked(ptr as *mut T), end, _marker: PhantomData }
101 }
102 }
103
104 /// Views the underlying data as a subslice of the original data.
105 ///
106 /// This has the same lifetime as the original slice, and so the
107 /// iterator can continue to be used while this exists.
108 ///
109 /// # Examples
110 ///
111 /// Basic usage:
112 ///
113 /// ```
114 /// // First, we declare a type which has the `iter` method to get the `Iter`
115 /// // struct (`&[usize]` here):
116 /// let slice = &[1, 2, 3];
117 ///
118 /// // Then, we get the iterator:
119 /// let mut iter = slice.iter();
120 /// // So if we print what `as_slice` method returns here, we have "[1, 2, 3]":
121 /// println!("{:?}", iter.as_slice());
122 ///
123 /// // Next, we move to the second element of the slice:
124 /// iter.next();
125 /// // Now `as_slice` returns "[2, 3]":
126 /// println!("{:?}", iter.as_slice());
127 /// ```
128 #[stable(feature = "iter_to_slice", since = "1.4.0")]
129 pub fn as_slice(&self) -> &'a [T] {
130 self.make_slice()
131 }
132 }
133
134 iterator! {struct Iter -> *const T, &'a T, const, {/* no mut */}, {
135 fn is_sorted_by<F>(self, mut compare: F) -> bool
136 where
137 Self: Sized,
138 F: FnMut(&Self::Item, &Self::Item) -> Option<Ordering>,
139 {
140 self.as_slice().windows(2).all(|w| {
141 compare(&&w[0], &&w[1]).map(|o| o != Ordering::Greater).unwrap_or(false)
142 })
143 }
144 }}
145
146 #[stable(feature = "rust1", since = "1.0.0")]
147 impl<T> Clone for Iter<'_, T> {
148 fn clone(&self) -> Self {
149 Iter { ptr: self.ptr, end: self.end, _marker: self._marker }
150 }
151 }
152
153 #[stable(feature = "slice_iter_as_ref", since = "1.13.0")]
154 impl<T> AsRef<[T]> for Iter<'_, T> {
155 fn as_ref(&self) -> &[T] {
156 self.as_slice()
157 }
158 }
159
160 /// Mutable slice iterator.
161 ///
162 /// This struct is created by the [`iter_mut`] method on [slices].
163 ///
164 /// # Examples
165 ///
166 /// Basic usage:
167 ///
168 /// ```
169 /// // First, we declare a type which has `iter_mut` method to get the `IterMut`
170 /// // struct (`&[usize]` here):
171 /// let mut slice = &mut [1, 2, 3];
172 ///
173 /// // Then, we iterate over it and increment each element value:
174 /// for element in slice.iter_mut() {
175 /// *element += 1;
176 /// }
177 ///
178 /// // We now have "[2, 3, 4]":
179 /// println!("{:?}", slice);
180 /// ```
181 ///
182 /// [`iter_mut`]: slice::iter_mut
183 /// [slices]: slice
184 #[stable(feature = "rust1", since = "1.0.0")]
185 pub struct IterMut<'a, T: 'a> {
186 ptr: NonNull<T>,
187 end: *mut T, // If T is a ZST, this is actually ptr+len. This encoding is picked so that
188 // ptr == end is a quick test for the Iterator being empty, that works
189 // for both ZST and non-ZST.
190 _marker: PhantomData<&'a mut T>,
191 }
192
193 #[stable(feature = "core_impl_debug", since = "1.9.0")]
194 impl<T: fmt::Debug> fmt::Debug for IterMut<'_, T> {
195 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
196 f.debug_tuple("IterMut").field(&self.make_slice()).finish()
197 }
198 }
199
200 #[stable(feature = "rust1", since = "1.0.0")]
201 unsafe impl<T: Sync> Sync for IterMut<'_, T> {}
202 #[stable(feature = "rust1", since = "1.0.0")]
203 unsafe impl<T: Send> Send for IterMut<'_, T> {}
204
205 impl<'a, T> IterMut<'a, T> {
206 #[inline]
207 pub(super) fn new(slice: &'a mut [T]) -> Self {
208 let ptr = slice.as_mut_ptr();
209 // SAFETY: There are several things here:
210 //
211 // `ptr` has been obtained by `slice.as_ptr()` where `slice` is a valid
212 // reference thus it is non-NUL and safe to use and pass to
213 // `NonNull::new_unchecked` .
214 //
215 // Adding `slice.len()` to the starting pointer gives a pointer
216 // at the end of `slice`. `end` will never be dereferenced, only checked
217 // for direct pointer equality with `ptr` to check if the iterator is
218 // done.
219 //
220 // In the case of a ZST, the end pointer is just the start pointer plus
221 // the length, to also allows for the fast `ptr == end` check.
222 //
223 // See the `next_unchecked!` and `is_empty!` macros as well as the
224 // `post_inc_start` method for more informations.
225 unsafe {
226 assume(!ptr.is_null());
227
228 let end = if mem::size_of::<T>() == 0 {
229 (ptr as *mut u8).wrapping_add(slice.len()) as *mut T
230 } else {
231 ptr.add(slice.len())
232 };
233
234 Self { ptr: NonNull::new_unchecked(ptr), end, _marker: PhantomData }
235 }
236 }
237
238 /// Views the underlying data as a subslice of the original data.
239 ///
240 /// To avoid creating `&mut` references that alias, this is forced
241 /// to consume the iterator.
242 ///
243 /// # Examples
244 ///
245 /// Basic usage:
246 ///
247 /// ```
248 /// // First, we declare a type which has `iter_mut` method to get the `IterMut`
249 /// // struct (`&[usize]` here):
250 /// let mut slice = &mut [1, 2, 3];
251 ///
252 /// {
253 /// // Then, we get the iterator:
254 /// let mut iter = slice.iter_mut();
255 /// // We move to next element:
256 /// iter.next();
257 /// // So if we print what `into_slice` method returns here, we have "[2, 3]":
258 /// println!("{:?}", iter.into_slice());
259 /// }
260 ///
261 /// // Now let's modify a value of the slice:
262 /// {
263 /// // First we get back the iterator:
264 /// let mut iter = slice.iter_mut();
265 /// // We change the value of the first element of the slice returned by the `next` method:
266 /// *iter.next().unwrap() += 1;
267 /// }
268 /// // Now slice is "[2, 2, 3]":
269 /// println!("{:?}", slice);
270 /// ```
271 #[stable(feature = "iter_to_slice", since = "1.4.0")]
272 pub fn into_slice(self) -> &'a mut [T] {
273 // SAFETY: the iterator was created from a mutable slice with pointer
274 // `self.ptr` and length `len!(self)`. This guarantees that all the prerequisites
275 // for `from_raw_parts_mut` are fulfilled.
276 unsafe { from_raw_parts_mut(self.ptr.as_ptr(), len!(self)) }
277 }
278
279 /// Views the underlying data as a subslice of the original data.
280 ///
281 /// To avoid creating `&mut [T]` references that alias, the returned slice
282 /// borrows its lifetime from the iterator the method is applied on.
283 ///
284 /// # Examples
285 ///
286 /// Basic usage:
287 ///
288 /// ```
289 /// let mut slice: &mut [usize] = &mut [1, 2, 3];
290 ///
291 /// // First, we get the iterator:
292 /// let mut iter = slice.iter_mut();
293 /// // So if we check what the `as_slice` method returns here, we have "[1, 2, 3]":
294 /// assert_eq!(iter.as_slice(), &[1, 2, 3]);
295 ///
296 /// // Next, we move to the second element of the slice:
297 /// iter.next();
298 /// // Now `as_slice` returns "[2, 3]":
299 /// assert_eq!(iter.as_slice(), &[2, 3]);
300 /// ```
301 #[stable(feature = "slice_iter_mut_as_slice", since = "1.53.0")]
302 pub fn as_slice(&self) -> &[T] {
303 self.make_slice()
304 }
305 }
306
307 #[stable(feature = "slice_iter_mut_as_slice", since = "1.53.0")]
308 impl<T> AsRef<[T]> for IterMut<'_, T> {
309 fn as_ref(&self) -> &[T] {
310 self.as_slice()
311 }
312 }
313
314 iterator! {struct IterMut -> *mut T, &'a mut T, mut, {mut}, {}}
315
316 /// An internal abstraction over the splitting iterators, so that
317 /// splitn, splitn_mut etc can be implemented once.
318 #[doc(hidden)]
319 pub(super) trait SplitIter: DoubleEndedIterator {
320 /// Marks the underlying iterator as complete, extracting the remaining
321 /// portion of the slice.
322 fn finish(&mut self) -> Option<Self::Item>;
323 }
324
325 /// An iterator over subslices separated by elements that match a predicate
326 /// function.
327 ///
328 /// This struct is created by the [`split`] method on [slices].
329 ///
330 /// # Example
331 ///
332 /// ```
333 /// let slice = [10, 40, 33, 20];
334 /// let mut iter = slice.split(|num| num % 3 == 0);
335 /// ```
336 ///
337 /// [`split`]: slice::split
338 /// [slices]: slice
339 #[stable(feature = "rust1", since = "1.0.0")]
340 pub struct Split<'a, T: 'a, P>
341 where
342 P: FnMut(&T) -> bool,
343 {
344 // Used for `SplitWhitespace` and `SplitAsciiWhitespace` `as_str` methods
345 pub(crate) v: &'a [T],
346 pred: P,
347 // Used for `SplitAsciiWhitespace` `as_str` method
348 pub(crate) finished: bool,
349 }
350
351 impl<'a, T: 'a, P: FnMut(&T) -> bool> Split<'a, T, P> {
352 #[inline]
353 pub(super) fn new(slice: &'a [T], pred: P) -> Self {
354 Self { v: slice, pred, finished: false }
355 }
356 }
357
358 #[stable(feature = "core_impl_debug", since = "1.9.0")]
359 impl<T: fmt::Debug, P> fmt::Debug for Split<'_, T, P>
360 where
361 P: FnMut(&T) -> bool,
362 {
363 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
364 f.debug_struct("Split").field("v", &self.v).field("finished", &self.finished).finish()
365 }
366 }
367
368 // FIXME(#26925) Remove in favor of `#[derive(Clone)]`
369 #[stable(feature = "rust1", since = "1.0.0")]
370 impl<T, P> Clone for Split<'_, T, P>
371 where
372 P: Clone + FnMut(&T) -> bool,
373 {
374 fn clone(&self) -> Self {
375 Split { v: self.v, pred: self.pred.clone(), finished: self.finished }
376 }
377 }
378
379 #[stable(feature = "rust1", since = "1.0.0")]
380 impl<'a, T, P> Iterator for Split<'a, T, P>
381 where
382 P: FnMut(&T) -> bool,
383 {
384 type Item = &'a [T];
385
386 #[inline]
387 fn next(&mut self) -> Option<&'a [T]> {
388 if self.finished {
389 return None;
390 }
391
392 match self.v.iter().position(|x| (self.pred)(x)) {
393 None => self.finish(),
394 Some(idx) => {
395 let ret = Some(&self.v[..idx]);
396 self.v = &self.v[idx + 1..];
397 ret
398 }
399 }
400 }
401
402 #[inline]
403 fn size_hint(&self) -> (usize, Option<usize>) {
404 if self.finished { (0, Some(0)) } else { (1, Some(self.v.len() + 1)) }
405 }
406 }
407
408 #[stable(feature = "rust1", since = "1.0.0")]
409 impl<'a, T, P> DoubleEndedIterator for Split<'a, T, P>
410 where
411 P: FnMut(&T) -> bool,
412 {
413 #[inline]
414 fn next_back(&mut self) -> Option<&'a [T]> {
415 if self.finished {
416 return None;
417 }
418
419 match self.v.iter().rposition(|x| (self.pred)(x)) {
420 None => self.finish(),
421 Some(idx) => {
422 let ret = Some(&self.v[idx + 1..]);
423 self.v = &self.v[..idx];
424 ret
425 }
426 }
427 }
428 }
429
430 impl<'a, T, P> SplitIter for Split<'a, T, P>
431 where
432 P: FnMut(&T) -> bool,
433 {
434 #[inline]
435 fn finish(&mut self) -> Option<&'a [T]> {
436 if self.finished {
437 None
438 } else {
439 self.finished = true;
440 Some(self.v)
441 }
442 }
443 }
444
445 #[stable(feature = "fused", since = "1.26.0")]
446 impl<T, P> FusedIterator for Split<'_, T, P> where P: FnMut(&T) -> bool {}
447
448 /// An iterator over subslices separated by elements that match a predicate
449 /// function. Unlike `Split`, it contains the matched part as a terminator
450 /// of the subslice.
451 ///
452 /// This struct is created by the [`split_inclusive`] method on [slices].
453 ///
454 /// # Example
455 ///
456 /// ```
457 /// let slice = [10, 40, 33, 20];
458 /// let mut iter = slice.split_inclusive(|num| num % 3 == 0);
459 /// ```
460 ///
461 /// [`split_inclusive`]: slice::split_inclusive
462 /// [slices]: slice
463 #[stable(feature = "split_inclusive", since = "1.51.0")]
464 pub struct SplitInclusive<'a, T: 'a, P>
465 where
466 P: FnMut(&T) -> bool,
467 {
468 v: &'a [T],
469 pred: P,
470 finished: bool,
471 }
472
473 impl<'a, T: 'a, P: FnMut(&T) -> bool> SplitInclusive<'a, T, P> {
474 #[inline]
475 pub(super) fn new(slice: &'a [T], pred: P) -> Self {
476 Self { v: slice, pred, finished: false }
477 }
478 }
479
480 #[stable(feature = "split_inclusive", since = "1.51.0")]
481 impl<T: fmt::Debug, P> fmt::Debug for SplitInclusive<'_, T, P>
482 where
483 P: FnMut(&T) -> bool,
484 {
485 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
486 f.debug_struct("SplitInclusive")
487 .field("v", &self.v)
488 .field("finished", &self.finished)
489 .finish()
490 }
491 }
492
493 // FIXME(#26925) Remove in favor of `#[derive(Clone)]`
494 #[stable(feature = "split_inclusive", since = "1.51.0")]
495 impl<T, P> Clone for SplitInclusive<'_, T, P>
496 where
497 P: Clone + FnMut(&T) -> bool,
498 {
499 fn clone(&self) -> Self {
500 SplitInclusive { v: self.v, pred: self.pred.clone(), finished: self.finished }
501 }
502 }
503
504 #[stable(feature = "split_inclusive", since = "1.51.0")]
505 impl<'a, T, P> Iterator for SplitInclusive<'a, T, P>
506 where
507 P: FnMut(&T) -> bool,
508 {
509 type Item = &'a [T];
510
511 #[inline]
512 fn next(&mut self) -> Option<&'a [T]> {
513 if self.finished {
514 return None;
515 }
516
517 let idx =
518 self.v.iter().position(|x| (self.pred)(x)).map(|idx| idx + 1).unwrap_or(self.v.len());
519 if idx == self.v.len() {
520 self.finished = true;
521 }
522 let ret = Some(&self.v[..idx]);
523 self.v = &self.v[idx..];
524 ret
525 }
526
527 #[inline]
528 fn size_hint(&self) -> (usize, Option<usize>) {
529 if self.finished { (0, Some(0)) } else { (1, Some(self.v.len() + 1)) }
530 }
531 }
532
533 #[stable(feature = "split_inclusive", since = "1.51.0")]
534 impl<'a, T, P> DoubleEndedIterator for SplitInclusive<'a, T, P>
535 where
536 P: FnMut(&T) -> bool,
537 {
538 #[inline]
539 fn next_back(&mut self) -> Option<&'a [T]> {
540 if self.finished {
541 return None;
542 }
543
544 // The last index of self.v is already checked and found to match
545 // by the last iteration, so we start searching a new match
546 // one index to the left.
547 let remainder = if self.v.is_empty() { &[] } else { &self.v[..(self.v.len() - 1)] };
548 let idx = remainder.iter().rposition(|x| (self.pred)(x)).map(|idx| idx + 1).unwrap_or(0);
549 if idx == 0 {
550 self.finished = true;
551 }
552 let ret = Some(&self.v[idx..]);
553 self.v = &self.v[..idx];
554 ret
555 }
556 }
557
558 #[stable(feature = "split_inclusive", since = "1.51.0")]
559 impl<T, P> FusedIterator for SplitInclusive<'_, T, P> where P: FnMut(&T) -> bool {}
560
561 /// An iterator over the mutable subslices of the vector which are separated
562 /// by elements that match `pred`.
563 ///
564 /// This struct is created by the [`split_mut`] method on [slices].
565 ///
566 /// # Example
567 ///
568 /// ```
569 /// let mut v = [10, 40, 30, 20, 60, 50];
570 /// let iter = v.split_mut(|num| *num % 3 == 0);
571 /// ```
572 ///
573 /// [`split_mut`]: slice::split_mut
574 /// [slices]: slice
575 #[stable(feature = "rust1", since = "1.0.0")]
576 pub struct SplitMut<'a, T: 'a, P>
577 where
578 P: FnMut(&T) -> bool,
579 {
580 v: &'a mut [T],
581 pred: P,
582 finished: bool,
583 }
584
585 impl<'a, T: 'a, P: FnMut(&T) -> bool> SplitMut<'a, T, P> {
586 #[inline]
587 pub(super) fn new(slice: &'a mut [T], pred: P) -> Self {
588 Self { v: slice, pred, finished: false }
589 }
590 }
591
592 #[stable(feature = "core_impl_debug", since = "1.9.0")]
593 impl<T: fmt::Debug, P> fmt::Debug for SplitMut<'_, T, P>
594 where
595 P: FnMut(&T) -> bool,
596 {
597 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
598 f.debug_struct("SplitMut").field("v", &self.v).field("finished", &self.finished).finish()
599 }
600 }
601
602 impl<'a, T, P> SplitIter for SplitMut<'a, T, P>
603 where
604 P: FnMut(&T) -> bool,
605 {
606 #[inline]
607 fn finish(&mut self) -> Option<&'a mut [T]> {
608 if self.finished {
609 None
610 } else {
611 self.finished = true;
612 Some(mem::replace(&mut self.v, &mut []))
613 }
614 }
615 }
616
617 #[stable(feature = "rust1", since = "1.0.0")]
618 impl<'a, T, P> Iterator for SplitMut<'a, T, P>
619 where
620 P: FnMut(&T) -> bool,
621 {
622 type Item = &'a mut [T];
623
624 #[inline]
625 fn next(&mut self) -> Option<&'a mut [T]> {
626 if self.finished {
627 return None;
628 }
629
630 let idx_opt = {
631 // work around borrowck limitations
632 let pred = &mut self.pred;
633 self.v.iter().position(|x| (*pred)(x))
634 };
635 match idx_opt {
636 None => self.finish(),
637 Some(idx) => {
638 let tmp = mem::replace(&mut self.v, &mut []);
639 let (head, tail) = tmp.split_at_mut(idx);
640 self.v = &mut tail[1..];
641 Some(head)
642 }
643 }
644 }
645
646 #[inline]
647 fn size_hint(&self) -> (usize, Option<usize>) {
648 if self.finished {
649 (0, Some(0))
650 } else {
651 // if the predicate doesn't match anything, we yield one slice
652 // if it matches every element, we yield len+1 empty slices.
653 (1, Some(self.v.len() + 1))
654 }
655 }
656 }
657
658 #[stable(feature = "rust1", since = "1.0.0")]
659 impl<'a, T, P> DoubleEndedIterator for SplitMut<'a, T, P>
660 where
661 P: FnMut(&T) -> bool,
662 {
663 #[inline]
664 fn next_back(&mut self) -> Option<&'a mut [T]> {
665 if self.finished {
666 return None;
667 }
668
669 let idx_opt = {
670 // work around borrowck limitations
671 let pred = &mut self.pred;
672 self.v.iter().rposition(|x| (*pred)(x))
673 };
674 match idx_opt {
675 None => self.finish(),
676 Some(idx) => {
677 let tmp = mem::replace(&mut self.v, &mut []);
678 let (head, tail) = tmp.split_at_mut(idx);
679 self.v = head;
680 Some(&mut tail[1..])
681 }
682 }
683 }
684 }
685
686 #[stable(feature = "fused", since = "1.26.0")]
687 impl<T, P> FusedIterator for SplitMut<'_, T, P> where P: FnMut(&T) -> bool {}
688
689 /// An iterator over the mutable subslices of the vector which are separated
690 /// by elements that match `pred`. Unlike `SplitMut`, it contains the matched
691 /// parts in the ends of the subslices.
692 ///
693 /// This struct is created by the [`split_inclusive_mut`] method on [slices].
694 ///
695 /// # Example
696 ///
697 /// ```
698 /// let mut v = [10, 40, 30, 20, 60, 50];
699 /// let iter = v.split_inclusive_mut(|num| *num % 3 == 0);
700 /// ```
701 ///
702 /// [`split_inclusive_mut`]: slice::split_inclusive_mut
703 /// [slices]: slice
704 #[stable(feature = "split_inclusive", since = "1.51.0")]
705 pub struct SplitInclusiveMut<'a, T: 'a, P>
706 where
707 P: FnMut(&T) -> bool,
708 {
709 v: &'a mut [T],
710 pred: P,
711 finished: bool,
712 }
713
714 impl<'a, T: 'a, P: FnMut(&T) -> bool> SplitInclusiveMut<'a, T, P> {
715 #[inline]
716 pub(super) fn new(slice: &'a mut [T], pred: P) -> Self {
717 Self { v: slice, pred, finished: false }
718 }
719 }
720
721 #[stable(feature = "split_inclusive", since = "1.51.0")]
722 impl<T: fmt::Debug, P> fmt::Debug for SplitInclusiveMut<'_, T, P>
723 where
724 P: FnMut(&T) -> bool,
725 {
726 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
727 f.debug_struct("SplitInclusiveMut")
728 .field("v", &self.v)
729 .field("finished", &self.finished)
730 .finish()
731 }
732 }
733
734 #[stable(feature = "split_inclusive", since = "1.51.0")]
735 impl<'a, T, P> Iterator for SplitInclusiveMut<'a, T, P>
736 where
737 P: FnMut(&T) -> bool,
738 {
739 type Item = &'a mut [T];
740
741 #[inline]
742 fn next(&mut self) -> Option<&'a mut [T]> {
743 if self.finished {
744 return None;
745 }
746
747 let idx_opt = {
748 // work around borrowck limitations
749 let pred = &mut self.pred;
750 self.v.iter().position(|x| (*pred)(x))
751 };
752 let idx = idx_opt.map(|idx| idx + 1).unwrap_or(self.v.len());
753 if idx == self.v.len() {
754 self.finished = true;
755 }
756 let tmp = mem::replace(&mut self.v, &mut []);
757 let (head, tail) = tmp.split_at_mut(idx);
758 self.v = tail;
759 Some(head)
760 }
761
762 #[inline]
763 fn size_hint(&self) -> (usize, Option<usize>) {
764 if self.finished {
765 (0, Some(0))
766 } else {
767 // if the predicate doesn't match anything, we yield one slice
768 // if it matches every element, we yield len+1 empty slices.
769 (1, Some(self.v.len() + 1))
770 }
771 }
772 }
773
774 #[stable(feature = "split_inclusive", since = "1.51.0")]
775 impl<'a, T, P> DoubleEndedIterator for SplitInclusiveMut<'a, T, P>
776 where
777 P: FnMut(&T) -> bool,
778 {
779 #[inline]
780 fn next_back(&mut self) -> Option<&'a mut [T]> {
781 if self.finished {
782 return None;
783 }
784
785 let idx_opt = if self.v.is_empty() {
786 None
787 } else {
788 // work around borrowck limitations
789 let pred = &mut self.pred;
790
791 // The last index of self.v is already checked and found to match
792 // by the last iteration, so we start searching a new match
793 // one index to the left.
794 let remainder = &self.v[..(self.v.len() - 1)];
795 remainder.iter().rposition(|x| (*pred)(x))
796 };
797 let idx = idx_opt.map(|idx| idx + 1).unwrap_or(0);
798 if idx == 0 {
799 self.finished = true;
800 }
801 let tmp = mem::replace(&mut self.v, &mut []);
802 let (head, tail) = tmp.split_at_mut(idx);
803 self.v = head;
804 Some(tail)
805 }
806 }
807
808 #[stable(feature = "split_inclusive", since = "1.51.0")]
809 impl<T, P> FusedIterator for SplitInclusiveMut<'_, T, P> where P: FnMut(&T) -> bool {}
810
811 /// An iterator over subslices separated by elements that match a predicate
812 /// function, starting from the end of the slice.
813 ///
814 /// This struct is created by the [`rsplit`] method on [slices].
815 ///
816 /// # Example
817 ///
818 /// ```
819 /// let slice = [11, 22, 33, 0, 44, 55];
820 /// let iter = slice.rsplit(|num| *num == 0);
821 /// ```
822 ///
823 /// [`rsplit`]: slice::rsplit
824 /// [slices]: slice
825 #[stable(feature = "slice_rsplit", since = "1.27.0")]
826 #[derive(Clone)] // Is this correct, or does it incorrectly require `T: Clone`?
827 pub struct RSplit<'a, T: 'a, P>
828 where
829 P: FnMut(&T) -> bool,
830 {
831 inner: Split<'a, T, P>,
832 }
833
834 impl<'a, T: 'a, P: FnMut(&T) -> bool> RSplit<'a, T, P> {
835 #[inline]
836 pub(super) fn new(slice: &'a [T], pred: P) -> Self {
837 Self { inner: Split::new(slice, pred) }
838 }
839 }
840
841 #[stable(feature = "slice_rsplit", since = "1.27.0")]
842 impl<T: fmt::Debug, P> fmt::Debug for RSplit<'_, T, P>
843 where
844 P: FnMut(&T) -> bool,
845 {
846 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
847 f.debug_struct("RSplit")
848 .field("v", &self.inner.v)
849 .field("finished", &self.inner.finished)
850 .finish()
851 }
852 }
853
854 #[stable(feature = "slice_rsplit", since = "1.27.0")]
855 impl<'a, T, P> Iterator for RSplit<'a, T, P>
856 where
857 P: FnMut(&T) -> bool,
858 {
859 type Item = &'a [T];
860
861 #[inline]
862 fn next(&mut self) -> Option<&'a [T]> {
863 self.inner.next_back()
864 }
865
866 #[inline]
867 fn size_hint(&self) -> (usize, Option<usize>) {
868 self.inner.size_hint()
869 }
870 }
871
872 #[stable(feature = "slice_rsplit", since = "1.27.0")]
873 impl<'a, T, P> DoubleEndedIterator for RSplit<'a, T, P>
874 where
875 P: FnMut(&T) -> bool,
876 {
877 #[inline]
878 fn next_back(&mut self) -> Option<&'a [T]> {
879 self.inner.next()
880 }
881 }
882
883 #[stable(feature = "slice_rsplit", since = "1.27.0")]
884 impl<'a, T, P> SplitIter for RSplit<'a, T, P>
885 where
886 P: FnMut(&T) -> bool,
887 {
888 #[inline]
889 fn finish(&mut self) -> Option<&'a [T]> {
890 self.inner.finish()
891 }
892 }
893
894 #[stable(feature = "slice_rsplit", since = "1.27.0")]
895 impl<T, P> FusedIterator for RSplit<'_, T, P> where P: FnMut(&T) -> bool {}
896
897 /// An iterator over the subslices of the vector which are separated
898 /// by elements that match `pred`, starting from the end of the slice.
899 ///
900 /// This struct is created by the [`rsplit_mut`] method on [slices].
901 ///
902 /// # Example
903 ///
904 /// ```
905 /// let mut slice = [11, 22, 33, 0, 44, 55];
906 /// let iter = slice.rsplit_mut(|num| *num == 0);
907 /// ```
908 ///
909 /// [`rsplit_mut`]: slice::rsplit_mut
910 /// [slices]: slice
911 #[stable(feature = "slice_rsplit", since = "1.27.0")]
912 pub struct RSplitMut<'a, T: 'a, P>
913 where
914 P: FnMut(&T) -> bool,
915 {
916 inner: SplitMut<'a, T, P>,
917 }
918
919 impl<'a, T: 'a, P: FnMut(&T) -> bool> RSplitMut<'a, T, P> {
920 #[inline]
921 pub(super) fn new(slice: &'a mut [T], pred: P) -> Self {
922 Self { inner: SplitMut::new(slice, pred) }
923 }
924 }
925
926 #[stable(feature = "slice_rsplit", since = "1.27.0")]
927 impl<T: fmt::Debug, P> fmt::Debug for RSplitMut<'_, T, P>
928 where
929 P: FnMut(&T) -> bool,
930 {
931 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
932 f.debug_struct("RSplitMut")
933 .field("v", &self.inner.v)
934 .field("finished", &self.inner.finished)
935 .finish()
936 }
937 }
938
939 #[stable(feature = "slice_rsplit", since = "1.27.0")]
940 impl<'a, T, P> SplitIter for RSplitMut<'a, T, P>
941 where
942 P: FnMut(&T) -> bool,
943 {
944 #[inline]
945 fn finish(&mut self) -> Option<&'a mut [T]> {
946 self.inner.finish()
947 }
948 }
949
950 #[stable(feature = "slice_rsplit", since = "1.27.0")]
951 impl<'a, T, P> Iterator for RSplitMut<'a, T, P>
952 where
953 P: FnMut(&T) -> bool,
954 {
955 type Item = &'a mut [T];
956
957 #[inline]
958 fn next(&mut self) -> Option<&'a mut [T]> {
959 self.inner.next_back()
960 }
961
962 #[inline]
963 fn size_hint(&self) -> (usize, Option<usize>) {
964 self.inner.size_hint()
965 }
966 }
967
968 #[stable(feature = "slice_rsplit", since = "1.27.0")]
969 impl<'a, T, P> DoubleEndedIterator for RSplitMut<'a, T, P>
970 where
971 P: FnMut(&T) -> bool,
972 {
973 #[inline]
974 fn next_back(&mut self) -> Option<&'a mut [T]> {
975 self.inner.next()
976 }
977 }
978
979 #[stable(feature = "slice_rsplit", since = "1.27.0")]
980 impl<T, P> FusedIterator for RSplitMut<'_, T, P> where P: FnMut(&T) -> bool {}
981
982 /// An private iterator over subslices separated by elements that
983 /// match a predicate function, splitting at most a fixed number of
984 /// times.
985 #[derive(Debug)]
986 struct GenericSplitN<I> {
987 iter: I,
988 count: usize,
989 }
990
991 impl<T, I: SplitIter<Item = T>> Iterator for GenericSplitN<I> {
992 type Item = T;
993
994 #[inline]
995 fn next(&mut self) -> Option<T> {
996 match self.count {
997 0 => None,
998 1 => {
999 self.count -= 1;
1000 self.iter.finish()
1001 }
1002 _ => {
1003 self.count -= 1;
1004 self.iter.next()
1005 }
1006 }
1007 }
1008
1009 #[inline]
1010 fn size_hint(&self) -> (usize, Option<usize>) {
1011 let (lower, upper_opt) = self.iter.size_hint();
1012 (lower, upper_opt.map(|upper| cmp::min(self.count, upper)))
1013 }
1014 }
1015
1016 /// An iterator over subslices separated by elements that match a predicate
1017 /// function, limited to a given number of splits.
1018 ///
1019 /// This struct is created by the [`splitn`] method on [slices].
1020 ///
1021 /// # Example
1022 ///
1023 /// ```
1024 /// let slice = [10, 40, 30, 20, 60, 50];
1025 /// let iter = slice.splitn(2, |num| *num % 3 == 0);
1026 /// ```
1027 ///
1028 /// [`splitn`]: slice::splitn
1029 /// [slices]: slice
1030 #[stable(feature = "rust1", since = "1.0.0")]
1031 pub struct SplitN<'a, T: 'a, P>
1032 where
1033 P: FnMut(&T) -> bool,
1034 {
1035 inner: GenericSplitN<Split<'a, T, P>>,
1036 }
1037
1038 impl<'a, T: 'a, P: FnMut(&T) -> bool> SplitN<'a, T, P> {
1039 #[inline]
1040 pub(super) fn new(s: Split<'a, T, P>, n: usize) -> Self {
1041 Self { inner: GenericSplitN { iter: s, count: n } }
1042 }
1043 }
1044
1045 #[stable(feature = "core_impl_debug", since = "1.9.0")]
1046 impl<T: fmt::Debug, P> fmt::Debug for SplitN<'_, T, P>
1047 where
1048 P: FnMut(&T) -> bool,
1049 {
1050 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
1051 f.debug_struct("SplitN").field("inner", &self.inner).finish()
1052 }
1053 }
1054
1055 /// An iterator over subslices separated by elements that match a
1056 /// predicate function, limited to a given number of splits, starting
1057 /// from the end of the slice.
1058 ///
1059 /// This struct is created by the [`rsplitn`] method on [slices].
1060 ///
1061 /// # Example
1062 ///
1063 /// ```
1064 /// let slice = [10, 40, 30, 20, 60, 50];
1065 /// let iter = slice.rsplitn(2, |num| *num % 3 == 0);
1066 /// ```
1067 ///
1068 /// [`rsplitn`]: slice::rsplitn
1069 /// [slices]: slice
1070 #[stable(feature = "rust1", since = "1.0.0")]
1071 pub struct RSplitN<'a, T: 'a, P>
1072 where
1073 P: FnMut(&T) -> bool,
1074 {
1075 inner: GenericSplitN<RSplit<'a, T, P>>,
1076 }
1077
1078 impl<'a, T: 'a, P: FnMut(&T) -> bool> RSplitN<'a, T, P> {
1079 #[inline]
1080 pub(super) fn new(s: RSplit<'a, T, P>, n: usize) -> Self {
1081 Self { inner: GenericSplitN { iter: s, count: n } }
1082 }
1083 }
1084
1085 #[stable(feature = "core_impl_debug", since = "1.9.0")]
1086 impl<T: fmt::Debug, P> fmt::Debug for RSplitN<'_, T, P>
1087 where
1088 P: FnMut(&T) -> bool,
1089 {
1090 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
1091 f.debug_struct("RSplitN").field("inner", &self.inner).finish()
1092 }
1093 }
1094
1095 /// An iterator over subslices separated by elements that match a predicate
1096 /// function, limited to a given number of splits.
1097 ///
1098 /// This struct is created by the [`splitn_mut`] method on [slices].
1099 ///
1100 /// # Example
1101 ///
1102 /// ```
1103 /// let mut slice = [10, 40, 30, 20, 60, 50];
1104 /// let iter = slice.splitn_mut(2, |num| *num % 3 == 0);
1105 /// ```
1106 ///
1107 /// [`splitn_mut`]: slice::splitn_mut
1108 /// [slices]: slice
1109 #[stable(feature = "rust1", since = "1.0.0")]
1110 pub struct SplitNMut<'a, T: 'a, P>
1111 where
1112 P: FnMut(&T) -> bool,
1113 {
1114 inner: GenericSplitN<SplitMut<'a, T, P>>,
1115 }
1116
1117 impl<'a, T: 'a, P: FnMut(&T) -> bool> SplitNMut<'a, T, P> {
1118 #[inline]
1119 pub(super) fn new(s: SplitMut<'a, T, P>, n: usize) -> Self {
1120 Self { inner: GenericSplitN { iter: s, count: n } }
1121 }
1122 }
1123
1124 #[stable(feature = "core_impl_debug", since = "1.9.0")]
1125 impl<T: fmt::Debug, P> fmt::Debug for SplitNMut<'_, T, P>
1126 where
1127 P: FnMut(&T) -> bool,
1128 {
1129 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
1130 f.debug_struct("SplitNMut").field("inner", &self.inner).finish()
1131 }
1132 }
1133
1134 /// An iterator over subslices separated by elements that match a
1135 /// predicate function, limited to a given number of splits, starting
1136 /// from the end of the slice.
1137 ///
1138 /// This struct is created by the [`rsplitn_mut`] method on [slices].
1139 ///
1140 /// # Example
1141 ///
1142 /// ```
1143 /// let mut slice = [10, 40, 30, 20, 60, 50];
1144 /// let iter = slice.rsplitn_mut(2, |num| *num % 3 == 0);
1145 /// ```
1146 ///
1147 /// [`rsplitn_mut`]: slice::rsplitn_mut
1148 /// [slices]: slice
1149 #[stable(feature = "rust1", since = "1.0.0")]
1150 pub struct RSplitNMut<'a, T: 'a, P>
1151 where
1152 P: FnMut(&T) -> bool,
1153 {
1154 inner: GenericSplitN<RSplitMut<'a, T, P>>,
1155 }
1156
1157 impl<'a, T: 'a, P: FnMut(&T) -> bool> RSplitNMut<'a, T, P> {
1158 #[inline]
1159 pub(super) fn new(s: RSplitMut<'a, T, P>, n: usize) -> Self {
1160 Self { inner: GenericSplitN { iter: s, count: n } }
1161 }
1162 }
1163
1164 #[stable(feature = "core_impl_debug", since = "1.9.0")]
1165 impl<T: fmt::Debug, P> fmt::Debug for RSplitNMut<'_, T, P>
1166 where
1167 P: FnMut(&T) -> bool,
1168 {
1169 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
1170 f.debug_struct("RSplitNMut").field("inner", &self.inner).finish()
1171 }
1172 }
1173
1174 forward_iterator! { SplitN: T, &'a [T] }
1175 forward_iterator! { RSplitN: T, &'a [T] }
1176 forward_iterator! { SplitNMut: T, &'a mut [T] }
1177 forward_iterator! { RSplitNMut: T, &'a mut [T] }
1178
1179 /// An iterator over overlapping subslices of length `size`.
1180 ///
1181 /// This struct is created by the [`windows`] method on [slices].
1182 ///
1183 /// # Example
1184 ///
1185 /// ```
1186 /// let slice = ['r', 'u', 's', 't'];
1187 /// let iter = slice.windows(2);
1188 /// ```
1189 ///
1190 /// [`windows`]: slice::windows
1191 /// [slices]: slice
1192 #[derive(Debug)]
1193 #[stable(feature = "rust1", since = "1.0.0")]
1194 pub struct Windows<'a, T: 'a> {
1195 v: &'a [T],
1196 size: NonZeroUsize,
1197 }
1198
1199 impl<'a, T: 'a> Windows<'a, T> {
1200 #[inline]
1201 pub(super) fn new(slice: &'a [T], size: NonZeroUsize) -> Self {
1202 Self { v: slice, size }
1203 }
1204 }
1205
1206 // FIXME(#26925) Remove in favor of `#[derive(Clone)]`
1207 #[stable(feature = "rust1", since = "1.0.0")]
1208 impl<T> Clone for Windows<'_, T> {
1209 fn clone(&self) -> Self {
1210 Windows { v: self.v, size: self.size }
1211 }
1212 }
1213
1214 #[stable(feature = "rust1", since = "1.0.0")]
1215 impl<'a, T> Iterator for Windows<'a, T> {
1216 type Item = &'a [T];
1217
1218 #[inline]
1219 fn next(&mut self) -> Option<&'a [T]> {
1220 if self.size.get() > self.v.len() {
1221 None
1222 } else {
1223 let ret = Some(&self.v[..self.size.get()]);
1224 self.v = &self.v[1..];
1225 ret
1226 }
1227 }
1228
1229 #[inline]
1230 fn size_hint(&self) -> (usize, Option<usize>) {
1231 if self.size.get() > self.v.len() {
1232 (0, Some(0))
1233 } else {
1234 let size = self.v.len() - self.size.get() + 1;
1235 (size, Some(size))
1236 }
1237 }
1238
1239 #[inline]
1240 fn count(self) -> usize {
1241 self.len()
1242 }
1243
1244 #[inline]
1245 fn nth(&mut self, n: usize) -> Option<Self::Item> {
1246 let (end, overflow) = self.size.get().overflowing_add(n);
1247 if end > self.v.len() || overflow {
1248 self.v = &[];
1249 None
1250 } else {
1251 let nth = &self.v[n..end];
1252 self.v = &self.v[n + 1..];
1253 Some(nth)
1254 }
1255 }
1256
1257 #[inline]
1258 fn last(self) -> Option<Self::Item> {
1259 if self.size.get() > self.v.len() {
1260 None
1261 } else {
1262 let start = self.v.len() - self.size.get();
1263 Some(&self.v[start..])
1264 }
1265 }
1266
1267 #[doc(hidden)]
1268 unsafe fn __iterator_get_unchecked(&mut self, idx: usize) -> Self::Item {
1269 // SAFETY: since the caller guarantees that `i` is in bounds,
1270 // which means that `i` cannot overflow an `isize`, and the
1271 // slice created by `from_raw_parts` is a subslice of `self.v`
1272 // thus is guaranteed to be valid for the lifetime `'a` of `self.v`.
1273 unsafe { from_raw_parts(self.v.as_ptr().add(idx), self.size.get()) }
1274 }
1275 }
1276
1277 #[stable(feature = "rust1", since = "1.0.0")]
1278 impl<'a, T> DoubleEndedIterator for Windows<'a, T> {
1279 #[inline]
1280 fn next_back(&mut self) -> Option<&'a [T]> {
1281 if self.size.get() > self.v.len() {
1282 None
1283 } else {
1284 let ret = Some(&self.v[self.v.len() - self.size.get()..]);
1285 self.v = &self.v[..self.v.len() - 1];
1286 ret
1287 }
1288 }
1289
1290 #[inline]
1291 fn nth_back(&mut self, n: usize) -> Option<Self::Item> {
1292 let (end, overflow) = self.v.len().overflowing_sub(n);
1293 if end < self.size.get() || overflow {
1294 self.v = &[];
1295 None
1296 } else {
1297 let ret = &self.v[end - self.size.get()..end];
1298 self.v = &self.v[..end - 1];
1299 Some(ret)
1300 }
1301 }
1302 }
1303
1304 #[stable(feature = "rust1", since = "1.0.0")]
1305 impl<T> ExactSizeIterator for Windows<'_, T> {}
1306
1307 #[unstable(feature = "trusted_len", issue = "37572")]
1308 unsafe impl<T> TrustedLen for Windows<'_, T> {}
1309
1310 #[stable(feature = "fused", since = "1.26.0")]
1311 impl<T> FusedIterator for Windows<'_, T> {}
1312
1313 #[doc(hidden)]
1314 #[unstable(feature = "trusted_random_access", issue = "none")]
1315 unsafe impl<'a, T> TrustedRandomAccess for Windows<'a, T> {
1316 const MAY_HAVE_SIDE_EFFECT: bool = false;
1317 }
1318
1319 /// An iterator over a slice in (non-overlapping) chunks (`chunk_size` elements at a
1320 /// time), starting at the beginning of the slice.
1321 ///
1322 /// When the slice len is not evenly divided by the chunk size, the last slice
1323 /// of the iteration will be the remainder.
1324 ///
1325 /// This struct is created by the [`chunks`] method on [slices].
1326 ///
1327 /// # Example
1328 ///
1329 /// ```
1330 /// let slice = ['l', 'o', 'r', 'e', 'm'];
1331 /// let iter = slice.chunks(2);
1332 /// ```
1333 ///
1334 /// [`chunks`]: slice::chunks
1335 /// [slices]: slice
1336 #[derive(Debug)]
1337 #[stable(feature = "rust1", since = "1.0.0")]
1338 pub struct Chunks<'a, T: 'a> {
1339 v: &'a [T],
1340 chunk_size: usize,
1341 }
1342
1343 impl<'a, T: 'a> Chunks<'a, T> {
1344 #[inline]
1345 pub(super) fn new(slice: &'a [T], size: usize) -> Self {
1346 Self { v: slice, chunk_size: size }
1347 }
1348 }
1349
1350 // FIXME(#26925) Remove in favor of `#[derive(Clone)]`
1351 #[stable(feature = "rust1", since = "1.0.0")]
1352 impl<T> Clone for Chunks<'_, T> {
1353 fn clone(&self) -> Self {
1354 Chunks { v: self.v, chunk_size: self.chunk_size }
1355 }
1356 }
1357
1358 #[stable(feature = "rust1", since = "1.0.0")]
1359 impl<'a, T> Iterator for Chunks<'a, T> {
1360 type Item = &'a [T];
1361
1362 #[inline]
1363 fn next(&mut self) -> Option<&'a [T]> {
1364 if self.v.is_empty() {
1365 None
1366 } else {
1367 let chunksz = cmp::min(self.v.len(), self.chunk_size);
1368 let (fst, snd) = self.v.split_at(chunksz);
1369 self.v = snd;
1370 Some(fst)
1371 }
1372 }
1373
1374 #[inline]
1375 fn size_hint(&self) -> (usize, Option<usize>) {
1376 if self.v.is_empty() {
1377 (0, Some(0))
1378 } else {
1379 let n = self.v.len() / self.chunk_size;
1380 let rem = self.v.len() % self.chunk_size;
1381 let n = if rem > 0 { n + 1 } else { n };
1382 (n, Some(n))
1383 }
1384 }
1385
1386 #[inline]
1387 fn count(self) -> usize {
1388 self.len()
1389 }
1390
1391 #[inline]
1392 fn nth(&mut self, n: usize) -> Option<Self::Item> {
1393 let (start, overflow) = n.overflowing_mul(self.chunk_size);
1394 if start >= self.v.len() || overflow {
1395 self.v = &[];
1396 None
1397 } else {
1398 let end = match start.checked_add(self.chunk_size) {
1399 Some(sum) => cmp::min(self.v.len(), sum),
1400 None => self.v.len(),
1401 };
1402 let nth = &self.v[start..end];
1403 self.v = &self.v[end..];
1404 Some(nth)
1405 }
1406 }
1407
1408 #[inline]
1409 fn last(self) -> Option<Self::Item> {
1410 if self.v.is_empty() {
1411 None
1412 } else {
1413 let start = (self.v.len() - 1) / self.chunk_size * self.chunk_size;
1414 Some(&self.v[start..])
1415 }
1416 }
1417
1418 #[doc(hidden)]
1419 unsafe fn __iterator_get_unchecked(&mut self, idx: usize) -> Self::Item {
1420 let start = idx * self.chunk_size;
1421 let end = match start.checked_add(self.chunk_size) {
1422 None => self.v.len(),
1423 Some(end) => cmp::min(end, self.v.len()),
1424 };
1425 // SAFETY: the caller guarantees that `i` is in bounds,
1426 // which means that `start` must be in bounds of the
1427 // underlying `self.v` slice, and we made sure that `end`
1428 // is also in bounds of `self.v`. Thus, `start` cannot overflow
1429 // an `isize`, and the slice constructed by `from_raw_parts`
1430 // is a subslice of `self.v` which is guaranteed to be valid
1431 // for the lifetime `'a` of `self.v`.
1432 unsafe { from_raw_parts(self.v.as_ptr().add(start), end - start) }
1433 }
1434 }
1435
1436 #[stable(feature = "rust1", since = "1.0.0")]
1437 impl<'a, T> DoubleEndedIterator for Chunks<'a, T> {
1438 #[inline]
1439 fn next_back(&mut self) -> Option<&'a [T]> {
1440 if self.v.is_empty() {
1441 None
1442 } else {
1443 let remainder = self.v.len() % self.chunk_size;
1444 let chunksz = if remainder != 0 { remainder } else { self.chunk_size };
1445 let (fst, snd) = self.v.split_at(self.v.len() - chunksz);
1446 self.v = fst;
1447 Some(snd)
1448 }
1449 }
1450
1451 #[inline]
1452 fn nth_back(&mut self, n: usize) -> Option<Self::Item> {
1453 let len = self.len();
1454 if n >= len {
1455 self.v = &[];
1456 None
1457 } else {
1458 let start = (len - 1 - n) * self.chunk_size;
1459 let end = match start.checked_add(self.chunk_size) {
1460 Some(res) => cmp::min(res, self.v.len()),
1461 None => self.v.len(),
1462 };
1463 let nth_back = &self.v[start..end];
1464 self.v = &self.v[..start];
1465 Some(nth_back)
1466 }
1467 }
1468 }
1469
1470 #[stable(feature = "rust1", since = "1.0.0")]
1471 impl<T> ExactSizeIterator for Chunks<'_, T> {}
1472
1473 #[unstable(feature = "trusted_len", issue = "37572")]
1474 unsafe impl<T> TrustedLen for Chunks<'_, T> {}
1475
1476 #[stable(feature = "fused", since = "1.26.0")]
1477 impl<T> FusedIterator for Chunks<'_, T> {}
1478
1479 #[doc(hidden)]
1480 #[unstable(feature = "trusted_random_access", issue = "none")]
1481 unsafe impl<'a, T> TrustedRandomAccess for Chunks<'a, T> {
1482 const MAY_HAVE_SIDE_EFFECT: bool = false;
1483 }
1484
1485 /// An iterator over a slice in (non-overlapping) mutable chunks (`chunk_size`
1486 /// elements at a time), starting at the beginning of the slice.
1487 ///
1488 /// When the slice len is not evenly divided by the chunk size, the last slice
1489 /// of the iteration will be the remainder.
1490 ///
1491 /// This struct is created by the [`chunks_mut`] method on [slices].
1492 ///
1493 /// # Example
1494 ///
1495 /// ```
1496 /// let mut slice = ['l', 'o', 'r', 'e', 'm'];
1497 /// let iter = slice.chunks_mut(2);
1498 /// ```
1499 ///
1500 /// [`chunks_mut`]: slice::chunks_mut
1501 /// [slices]: slice
1502 #[derive(Debug)]
1503 #[stable(feature = "rust1", since = "1.0.0")]
1504 pub struct ChunksMut<'a, T: 'a> {
1505 v: &'a mut [T],
1506 chunk_size: usize,
1507 }
1508
1509 impl<'a, T: 'a> ChunksMut<'a, T> {
1510 #[inline]
1511 pub(super) fn new(slice: &'a mut [T], size: usize) -> Self {
1512 Self { v: slice, chunk_size: size }
1513 }
1514 }
1515
1516 #[stable(feature = "rust1", since = "1.0.0")]
1517 impl<'a, T> Iterator for ChunksMut<'a, T> {
1518 type Item = &'a mut [T];
1519
1520 #[inline]
1521 fn next(&mut self) -> Option<&'a mut [T]> {
1522 if self.v.is_empty() {
1523 None
1524 } else {
1525 let sz = cmp::min(self.v.len(), self.chunk_size);
1526 let tmp = mem::replace(&mut self.v, &mut []);
1527 let (head, tail) = tmp.split_at_mut(sz);
1528 self.v = tail;
1529 Some(head)
1530 }
1531 }
1532
1533 #[inline]
1534 fn size_hint(&self) -> (usize, Option<usize>) {
1535 if self.v.is_empty() {
1536 (0, Some(0))
1537 } else {
1538 let n = self.v.len() / self.chunk_size;
1539 let rem = self.v.len() % self.chunk_size;
1540 let n = if rem > 0 { n + 1 } else { n };
1541 (n, Some(n))
1542 }
1543 }
1544
1545 #[inline]
1546 fn count(self) -> usize {
1547 self.len()
1548 }
1549
1550 #[inline]
1551 fn nth(&mut self, n: usize) -> Option<&'a mut [T]> {
1552 let (start, overflow) = n.overflowing_mul(self.chunk_size);
1553 if start >= self.v.len() || overflow {
1554 self.v = &mut [];
1555 None
1556 } else {
1557 let end = match start.checked_add(self.chunk_size) {
1558 Some(sum) => cmp::min(self.v.len(), sum),
1559 None => self.v.len(),
1560 };
1561 let tmp = mem::replace(&mut self.v, &mut []);
1562 let (head, tail) = tmp.split_at_mut(end);
1563 let (_, nth) = head.split_at_mut(start);
1564 self.v = tail;
1565 Some(nth)
1566 }
1567 }
1568
1569 #[inline]
1570 fn last(self) -> Option<Self::Item> {
1571 if self.v.is_empty() {
1572 None
1573 } else {
1574 let start = (self.v.len() - 1) / self.chunk_size * self.chunk_size;
1575 Some(&mut self.v[start..])
1576 }
1577 }
1578
1579 #[doc(hidden)]
1580 unsafe fn __iterator_get_unchecked(&mut self, idx: usize) -> Self::Item {
1581 let start = idx * self.chunk_size;
1582 let end = match start.checked_add(self.chunk_size) {
1583 None => self.v.len(),
1584 Some(end) => cmp::min(end, self.v.len()),
1585 };
1586 // SAFETY: see comments for `Chunks::__iterator_get_unchecked`.
1587 //
1588 // Also note that the caller also guarantees that we're never called
1589 // with the same index again, and that no other methods that will
1590 // access this subslice are called, so it is valid for the returned
1591 // slice to be mutable.
1592 unsafe { from_raw_parts_mut(self.v.as_mut_ptr().add(start), end - start) }
1593 }
1594 }
1595
1596 #[stable(feature = "rust1", since = "1.0.0")]
1597 impl<'a, T> DoubleEndedIterator for ChunksMut<'a, T> {
1598 #[inline]
1599 fn next_back(&mut self) -> Option<&'a mut [T]> {
1600 if self.v.is_empty() {
1601 None
1602 } else {
1603 let remainder = self.v.len() % self.chunk_size;
1604 let sz = if remainder != 0 { remainder } else { self.chunk_size };
1605 let tmp = mem::replace(&mut self.v, &mut []);
1606 let tmp_len = tmp.len();
1607 let (head, tail) = tmp.split_at_mut(tmp_len - sz);
1608 self.v = head;
1609 Some(tail)
1610 }
1611 }
1612
1613 #[inline]
1614 fn nth_back(&mut self, n: usize) -> Option<Self::Item> {
1615 let len = self.len();
1616 if n >= len {
1617 self.v = &mut [];
1618 None
1619 } else {
1620 let start = (len - 1 - n) * self.chunk_size;
1621 let end = match start.checked_add(self.chunk_size) {
1622 Some(res) => cmp::min(res, self.v.len()),
1623 None => self.v.len(),
1624 };
1625 let (temp, _tail) = mem::replace(&mut self.v, &mut []).split_at_mut(end);
1626 let (head, nth_back) = temp.split_at_mut(start);
1627 self.v = head;
1628 Some(nth_back)
1629 }
1630 }
1631 }
1632
1633 #[stable(feature = "rust1", since = "1.0.0")]
1634 impl<T> ExactSizeIterator for ChunksMut<'_, T> {}
1635
1636 #[unstable(feature = "trusted_len", issue = "37572")]
1637 unsafe impl<T> TrustedLen for ChunksMut<'_, T> {}
1638
1639 #[stable(feature = "fused", since = "1.26.0")]
1640 impl<T> FusedIterator for ChunksMut<'_, T> {}
1641
1642 #[doc(hidden)]
1643 #[unstable(feature = "trusted_random_access", issue = "none")]
1644 unsafe impl<'a, T> TrustedRandomAccess for ChunksMut<'a, T> {
1645 const MAY_HAVE_SIDE_EFFECT: bool = false;
1646 }
1647
1648 /// An iterator over a slice in (non-overlapping) chunks (`chunk_size` elements at a
1649 /// time), starting at the beginning of the slice.
1650 ///
1651 /// When the slice len is not evenly divided by the chunk size, the last
1652 /// up to `chunk_size-1` elements will be omitted but can be retrieved from
1653 /// the [`remainder`] function from the iterator.
1654 ///
1655 /// This struct is created by the [`chunks_exact`] method on [slices].
1656 ///
1657 /// # Example
1658 ///
1659 /// ```
1660 /// let slice = ['l', 'o', 'r', 'e', 'm'];
1661 /// let iter = slice.chunks_exact(2);
1662 /// ```
1663 ///
1664 /// [`chunks_exact`]: slice::chunks_exact
1665 /// [`remainder`]: ChunksExact::remainder
1666 /// [slices]: slice
1667 #[derive(Debug)]
1668 #[stable(feature = "chunks_exact", since = "1.31.0")]
1669 pub struct ChunksExact<'a, T: 'a> {
1670 v: &'a [T],
1671 rem: &'a [T],
1672 chunk_size: usize,
1673 }
1674
1675 impl<'a, T> ChunksExact<'a, T> {
1676 #[inline]
1677 pub(super) fn new(slice: &'a [T], chunk_size: usize) -> Self {
1678 let rem = slice.len() % chunk_size;
1679 let fst_len = slice.len() - rem;
1680 // SAFETY: 0 <= fst_len <= slice.len() by construction above
1681 let (fst, snd) = unsafe { slice.split_at_unchecked(fst_len) };
1682 Self { v: fst, rem: snd, chunk_size }
1683 }
1684
1685 /// Returns the remainder of the original slice that is not going to be
1686 /// returned by the iterator. The returned slice has at most `chunk_size-1`
1687 /// elements.
1688 #[stable(feature = "chunks_exact", since = "1.31.0")]
1689 pub fn remainder(&self) -> &'a [T] {
1690 self.rem
1691 }
1692 }
1693
1694 // FIXME(#26925) Remove in favor of `#[derive(Clone)]`
1695 #[stable(feature = "chunks_exact", since = "1.31.0")]
1696 impl<T> Clone for ChunksExact<'_, T> {
1697 fn clone(&self) -> Self {
1698 ChunksExact { v: self.v, rem: self.rem, chunk_size: self.chunk_size }
1699 }
1700 }
1701
1702 #[stable(feature = "chunks_exact", since = "1.31.0")]
1703 impl<'a, T> Iterator for ChunksExact<'a, T> {
1704 type Item = &'a [T];
1705
1706 #[inline]
1707 fn next(&mut self) -> Option<&'a [T]> {
1708 if self.v.len() < self.chunk_size {
1709 None
1710 } else {
1711 let (fst, snd) = self.v.split_at(self.chunk_size);
1712 self.v = snd;
1713 Some(fst)
1714 }
1715 }
1716
1717 #[inline]
1718 fn size_hint(&self) -> (usize, Option<usize>) {
1719 let n = self.v.len() / self.chunk_size;
1720 (n, Some(n))
1721 }
1722
1723 #[inline]
1724 fn count(self) -> usize {
1725 self.len()
1726 }
1727
1728 #[inline]
1729 fn nth(&mut self, n: usize) -> Option<Self::Item> {
1730 let (start, overflow) = n.overflowing_mul(self.chunk_size);
1731 if start >= self.v.len() || overflow {
1732 self.v = &[];
1733 None
1734 } else {
1735 let (_, snd) = self.v.split_at(start);
1736 self.v = snd;
1737 self.next()
1738 }
1739 }
1740
1741 #[inline]
1742 fn last(mut self) -> Option<Self::Item> {
1743 self.next_back()
1744 }
1745
1746 #[doc(hidden)]
1747 unsafe fn __iterator_get_unchecked(&mut self, idx: usize) -> Self::Item {
1748 let start = idx * self.chunk_size;
1749 // SAFETY: mostly identical to `Chunks::__iterator_get_unchecked`.
1750 unsafe { from_raw_parts(self.v.as_ptr().add(start), self.chunk_size) }
1751 }
1752 }
1753
1754 #[stable(feature = "chunks_exact", since = "1.31.0")]
1755 impl<'a, T> DoubleEndedIterator for ChunksExact<'a, T> {
1756 #[inline]
1757 fn next_back(&mut self) -> Option<&'a [T]> {
1758 if self.v.len() < self.chunk_size {
1759 None
1760 } else {
1761 let (fst, snd) = self.v.split_at(self.v.len() - self.chunk_size);
1762 self.v = fst;
1763 Some(snd)
1764 }
1765 }
1766
1767 #[inline]
1768 fn nth_back(&mut self, n: usize) -> Option<Self::Item> {
1769 let len = self.len();
1770 if n >= len {
1771 self.v = &[];
1772 None
1773 } else {
1774 let start = (len - 1 - n) * self.chunk_size;
1775 let end = start + self.chunk_size;
1776 let nth_back = &self.v[start..end];
1777 self.v = &self.v[..start];
1778 Some(nth_back)
1779 }
1780 }
1781 }
1782
1783 #[stable(feature = "chunks_exact", since = "1.31.0")]
1784 impl<T> ExactSizeIterator for ChunksExact<'_, T> {
1785 fn is_empty(&self) -> bool {
1786 self.v.is_empty()
1787 }
1788 }
1789
1790 #[unstable(feature = "trusted_len", issue = "37572")]
1791 unsafe impl<T> TrustedLen for ChunksExact<'_, T> {}
1792
1793 #[stable(feature = "chunks_exact", since = "1.31.0")]
1794 impl<T> FusedIterator for ChunksExact<'_, T> {}
1795
1796 #[doc(hidden)]
1797 #[unstable(feature = "trusted_random_access", issue = "none")]
1798 unsafe impl<'a, T> TrustedRandomAccess for ChunksExact<'a, T> {
1799 const MAY_HAVE_SIDE_EFFECT: bool = false;
1800 }
1801
1802 /// An iterator over a slice in (non-overlapping) mutable chunks (`chunk_size`
1803 /// elements at a time), starting at the beginning of the slice.
1804 ///
1805 /// When the slice len is not evenly divided by the chunk size, the last up to
1806 /// `chunk_size-1` elements will be omitted but can be retrieved from the
1807 /// [`into_remainder`] function from the iterator.
1808 ///
1809 /// This struct is created by the [`chunks_exact_mut`] method on [slices].
1810 ///
1811 /// # Example
1812 ///
1813 /// ```
1814 /// let mut slice = ['l', 'o', 'r', 'e', 'm'];
1815 /// let iter = slice.chunks_exact_mut(2);
1816 /// ```
1817 ///
1818 /// [`chunks_exact_mut`]: slice::chunks_exact_mut
1819 /// [`into_remainder`]: ChunksExactMut::into_remainder
1820 /// [slices]: slice
1821 #[derive(Debug)]
1822 #[stable(feature = "chunks_exact", since = "1.31.0")]
1823 pub struct ChunksExactMut<'a, T: 'a> {
1824 v: &'a mut [T],
1825 rem: &'a mut [T],
1826 chunk_size: usize,
1827 }
1828
1829 impl<'a, T> ChunksExactMut<'a, T> {
1830 #[inline]
1831 pub(super) fn new(slice: &'a mut [T], chunk_size: usize) -> Self {
1832 let rem = slice.len() % chunk_size;
1833 let fst_len = slice.len() - rem;
1834 // SAFETY: 0 <= fst_len <= slice.len() by construction above
1835 let (fst, snd) = unsafe { slice.split_at_mut_unchecked(fst_len) };
1836 Self { v: fst, rem: snd, chunk_size }
1837 }
1838
1839 /// Returns the remainder of the original slice that is not going to be
1840 /// returned by the iterator. The returned slice has at most `chunk_size-1`
1841 /// elements.
1842 #[stable(feature = "chunks_exact", since = "1.31.0")]
1843 pub fn into_remainder(self) -> &'a mut [T] {
1844 self.rem
1845 }
1846 }
1847
1848 #[stable(feature = "chunks_exact", since = "1.31.0")]
1849 impl<'a, T> Iterator for ChunksExactMut<'a, T> {
1850 type Item = &'a mut [T];
1851
1852 #[inline]
1853 fn next(&mut self) -> Option<&'a mut [T]> {
1854 if self.v.len() < self.chunk_size {
1855 None
1856 } else {
1857 let tmp = mem::replace(&mut self.v, &mut []);
1858 let (head, tail) = tmp.split_at_mut(self.chunk_size);
1859 self.v = tail;
1860 Some(head)
1861 }
1862 }
1863
1864 #[inline]
1865 fn size_hint(&self) -> (usize, Option<usize>) {
1866 let n = self.v.len() / self.chunk_size;
1867 (n, Some(n))
1868 }
1869
1870 #[inline]
1871 fn count(self) -> usize {
1872 self.len()
1873 }
1874
1875 #[inline]
1876 fn nth(&mut self, n: usize) -> Option<&'a mut [T]> {
1877 let (start, overflow) = n.overflowing_mul(self.chunk_size);
1878 if start >= self.v.len() || overflow {
1879 self.v = &mut [];
1880 None
1881 } else {
1882 let tmp = mem::replace(&mut self.v, &mut []);
1883 let (_, snd) = tmp.split_at_mut(start);
1884 self.v = snd;
1885 self.next()
1886 }
1887 }
1888
1889 #[inline]
1890 fn last(mut self) -> Option<Self::Item> {
1891 self.next_back()
1892 }
1893
1894 #[doc(hidden)]
1895 unsafe fn __iterator_get_unchecked(&mut self, idx: usize) -> Self::Item {
1896 let start = idx * self.chunk_size;
1897 // SAFETY: see comments for `ChunksMut::__iterator_get_unchecked`.
1898 unsafe { from_raw_parts_mut(self.v.as_mut_ptr().add(start), self.chunk_size) }
1899 }
1900 }
1901
1902 #[stable(feature = "chunks_exact", since = "1.31.0")]
1903 impl<'a, T> DoubleEndedIterator for ChunksExactMut<'a, T> {
1904 #[inline]
1905 fn next_back(&mut self) -> Option<&'a mut [T]> {
1906 if self.v.len() < self.chunk_size {
1907 None
1908 } else {
1909 let tmp = mem::replace(&mut self.v, &mut []);
1910 let tmp_len = tmp.len();
1911 let (head, tail) = tmp.split_at_mut(tmp_len - self.chunk_size);
1912 self.v = head;
1913 Some(tail)
1914 }
1915 }
1916
1917 #[inline]
1918 fn nth_back(&mut self, n: usize) -> Option<Self::Item> {
1919 let len = self.len();
1920 if n >= len {
1921 self.v = &mut [];
1922 None
1923 } else {
1924 let start = (len - 1 - n) * self.chunk_size;
1925 let end = start + self.chunk_size;
1926 let (temp, _tail) = mem::replace(&mut self.v, &mut []).split_at_mut(end);
1927 let (head, nth_back) = temp.split_at_mut(start);
1928 self.v = head;
1929 Some(nth_back)
1930 }
1931 }
1932 }
1933
1934 #[stable(feature = "chunks_exact", since = "1.31.0")]
1935 impl<T> ExactSizeIterator for ChunksExactMut<'_, T> {
1936 fn is_empty(&self) -> bool {
1937 self.v.is_empty()
1938 }
1939 }
1940
1941 #[unstable(feature = "trusted_len", issue = "37572")]
1942 unsafe impl<T> TrustedLen for ChunksExactMut<'_, T> {}
1943
1944 #[stable(feature = "chunks_exact", since = "1.31.0")]
1945 impl<T> FusedIterator for ChunksExactMut<'_, T> {}
1946
1947 #[doc(hidden)]
1948 #[unstable(feature = "trusted_random_access", issue = "none")]
1949 unsafe impl<'a, T> TrustedRandomAccess for ChunksExactMut<'a, T> {
1950 const MAY_HAVE_SIDE_EFFECT: bool = false;
1951 }
1952
1953 /// A windowed iterator over a slice in overlapping chunks (`N` elements at a
1954 /// time), starting at the beginning of the slice
1955 ///
1956 /// This struct is created by the [`array_windows`] method on [slices].
1957 ///
1958 /// # Example
1959 ///
1960 /// ```
1961 /// #![feature(array_windows)]
1962 ///
1963 /// let slice = [0, 1, 2, 3];
1964 /// let iter = slice.array_windows::<2>();
1965 /// ```
1966 ///
1967 /// [`array_windows`]: slice::array_windows
1968 /// [slices]: slice
1969 #[derive(Debug, Clone, Copy)]
1970 #[unstable(feature = "array_windows", issue = "75027")]
1971 pub struct ArrayWindows<'a, T: 'a, const N: usize> {
1972 slice_head: *const T,
1973 num: usize,
1974 marker: PhantomData<&'a [T; N]>,
1975 }
1976
1977 impl<'a, T: 'a, const N: usize> ArrayWindows<'a, T, N> {
1978 #[inline]
1979 pub(super) fn new(slice: &'a [T]) -> Self {
1980 let num_windows = slice.len().saturating_sub(N - 1);
1981 Self { slice_head: slice.as_ptr(), num: num_windows, marker: PhantomData }
1982 }
1983 }
1984
1985 #[unstable(feature = "array_windows", issue = "75027")]
1986 impl<'a, T, const N: usize> Iterator for ArrayWindows<'a, T, N> {
1987 type Item = &'a [T; N];
1988
1989 #[inline]
1990 fn next(&mut self) -> Option<Self::Item> {
1991 if self.num == 0 {
1992 return None;
1993 }
1994 // SAFETY:
1995 // This is safe because it's indexing into a slice guaranteed to be length > N.
1996 let ret = unsafe { &*self.slice_head.cast::<[T; N]>() };
1997 // SAFETY: Guaranteed that there are at least 1 item remaining otherwise
1998 // earlier branch would've been hit
1999 self.slice_head = unsafe { self.slice_head.add(1) };
2000
2001 self.num -= 1;
2002 Some(ret)
2003 }
2004
2005 #[inline]
2006 fn size_hint(&self) -> (usize, Option<usize>) {
2007 (self.num, Some(self.num))
2008 }
2009
2010 #[inline]
2011 fn count(self) -> usize {
2012 self.num
2013 }
2014
2015 #[inline]
2016 fn nth(&mut self, n: usize) -> Option<Self::Item> {
2017 if self.num <= n {
2018 self.num = 0;
2019 return None;
2020 }
2021 // SAFETY:
2022 // This is safe because it's indexing into a slice guaranteed to be length > N.
2023 let ret = unsafe { &*self.slice_head.add(n).cast::<[T; N]>() };
2024 // SAFETY: Guaranteed that there are at least n items remaining
2025 self.slice_head = unsafe { self.slice_head.add(n + 1) };
2026
2027 self.num -= n + 1;
2028 Some(ret)
2029 }
2030
2031 #[inline]
2032 fn last(mut self) -> Option<Self::Item> {
2033 self.nth(self.num.checked_sub(1)?)
2034 }
2035 }
2036
2037 #[unstable(feature = "array_windows", issue = "75027")]
2038 impl<'a, T, const N: usize> DoubleEndedIterator for ArrayWindows<'a, T, N> {
2039 #[inline]
2040 fn next_back(&mut self) -> Option<&'a [T; N]> {
2041 if self.num == 0 {
2042 return None;
2043 }
2044 // SAFETY: Guaranteed that there are n items remaining, n-1 for 0-indexing.
2045 let ret = unsafe { &*self.slice_head.add(self.num - 1).cast::<[T; N]>() };
2046 self.num -= 1;
2047 Some(ret)
2048 }
2049
2050 #[inline]
2051 fn nth_back(&mut self, n: usize) -> Option<&'a [T; N]> {
2052 if self.num <= n {
2053 self.num = 0;
2054 return None;
2055 }
2056 // SAFETY: Guaranteed that there are n items remaining, n-1 for 0-indexing.
2057 let ret = unsafe { &*self.slice_head.add(self.num - (n + 1)).cast::<[T; N]>() };
2058 self.num -= n + 1;
2059 Some(ret)
2060 }
2061 }
2062
2063 #[unstable(feature = "array_windows", issue = "75027")]
2064 impl<T, const N: usize> ExactSizeIterator for ArrayWindows<'_, T, N> {
2065 fn is_empty(&self) -> bool {
2066 self.num == 0
2067 }
2068 }
2069
2070 /// An iterator over a slice in (non-overlapping) chunks (`N` elements at a
2071 /// time), starting at the beginning of the slice.
2072 ///
2073 /// When the slice len is not evenly divided by the chunk size, the last
2074 /// up to `N-1` elements will be omitted but can be retrieved from
2075 /// the [`remainder`] function from the iterator.
2076 ///
2077 /// This struct is created by the [`array_chunks`] method on [slices].
2078 ///
2079 /// # Example
2080 ///
2081 /// ```
2082 /// #![feature(array_chunks)]
2083 ///
2084 /// let slice = ['l', 'o', 'r', 'e', 'm'];
2085 /// let iter = slice.array_chunks::<2>();
2086 /// ```
2087 ///
2088 /// [`array_chunks`]: slice::array_chunks
2089 /// [`remainder`]: ArrayChunks::remainder
2090 /// [slices]: slice
2091 #[derive(Debug)]
2092 #[unstable(feature = "array_chunks", issue = "74985")]
2093 pub struct ArrayChunks<'a, T: 'a, const N: usize> {
2094 iter: Iter<'a, [T; N]>,
2095 rem: &'a [T],
2096 }
2097
2098 impl<'a, T, const N: usize> ArrayChunks<'a, T, N> {
2099 #[inline]
2100 pub(super) fn new(slice: &'a [T]) -> Self {
2101 let (array_slice, rem) = slice.as_chunks();
2102 Self { iter: array_slice.iter(), rem }
2103 }
2104
2105 /// Returns the remainder of the original slice that is not going to be
2106 /// returned by the iterator. The returned slice has at most `N-1`
2107 /// elements.
2108 #[unstable(feature = "array_chunks", issue = "74985")]
2109 pub fn remainder(&self) -> &'a [T] {
2110 self.rem
2111 }
2112 }
2113
2114 // FIXME(#26925) Remove in favor of `#[derive(Clone)]`
2115 #[unstable(feature = "array_chunks", issue = "74985")]
2116 impl<T, const N: usize> Clone for ArrayChunks<'_, T, N> {
2117 fn clone(&self) -> Self {
2118 ArrayChunks { iter: self.iter.clone(), rem: self.rem }
2119 }
2120 }
2121
2122 #[unstable(feature = "array_chunks", issue = "74985")]
2123 impl<'a, T, const N: usize> Iterator for ArrayChunks<'a, T, N> {
2124 type Item = &'a [T; N];
2125
2126 #[inline]
2127 fn next(&mut self) -> Option<&'a [T; N]> {
2128 self.iter.next()
2129 }
2130
2131 #[inline]
2132 fn size_hint(&self) -> (usize, Option<usize>) {
2133 self.iter.size_hint()
2134 }
2135
2136 #[inline]
2137 fn count(self) -> usize {
2138 self.iter.count()
2139 }
2140
2141 #[inline]
2142 fn nth(&mut self, n: usize) -> Option<Self::Item> {
2143 self.iter.nth(n)
2144 }
2145
2146 #[inline]
2147 fn last(self) -> Option<Self::Item> {
2148 self.iter.last()
2149 }
2150
2151 unsafe fn __iterator_get_unchecked(&mut self, i: usize) -> &'a [T; N] {
2152 // SAFETY: The safety guarantees of `__iterator_get_unchecked` are
2153 // transferred to the caller.
2154 unsafe { self.iter.__iterator_get_unchecked(i) }
2155 }
2156 }
2157
2158 #[unstable(feature = "array_chunks", issue = "74985")]
2159 impl<'a, T, const N: usize> DoubleEndedIterator for ArrayChunks<'a, T, N> {
2160 #[inline]
2161 fn next_back(&mut self) -> Option<&'a [T; N]> {
2162 self.iter.next_back()
2163 }
2164
2165 #[inline]
2166 fn nth_back(&mut self, n: usize) -> Option<Self::Item> {
2167 self.iter.nth_back(n)
2168 }
2169 }
2170
2171 #[unstable(feature = "array_chunks", issue = "74985")]
2172 impl<T, const N: usize> ExactSizeIterator for ArrayChunks<'_, T, N> {
2173 fn is_empty(&self) -> bool {
2174 self.iter.is_empty()
2175 }
2176 }
2177
2178 #[unstable(feature = "trusted_len", issue = "37572")]
2179 unsafe impl<T, const N: usize> TrustedLen for ArrayChunks<'_, T, N> {}
2180
2181 #[unstable(feature = "array_chunks", issue = "74985")]
2182 impl<T, const N: usize> FusedIterator for ArrayChunks<'_, T, N> {}
2183
2184 #[doc(hidden)]
2185 #[unstable(feature = "array_chunks", issue = "74985")]
2186 unsafe impl<'a, T, const N: usize> TrustedRandomAccess for ArrayChunks<'a, T, N> {
2187 const MAY_HAVE_SIDE_EFFECT: bool = false;
2188 }
2189
2190 /// An iterator over a slice in (non-overlapping) mutable chunks (`N` elements
2191 /// at a time), starting at the beginning of the slice.
2192 ///
2193 /// When the slice len is not evenly divided by the chunk size, the last
2194 /// up to `N-1` elements will be omitted but can be retrieved from
2195 /// the [`into_remainder`] function from the iterator.
2196 ///
2197 /// This struct is created by the [`array_chunks_mut`] method on [slices].
2198 ///
2199 /// # Example
2200 ///
2201 /// ```
2202 /// #![feature(array_chunks)]
2203 ///
2204 /// let mut slice = ['l', 'o', 'r', 'e', 'm'];
2205 /// let iter = slice.array_chunks_mut::<2>();
2206 /// ```
2207 ///
2208 /// [`array_chunks_mut`]: slice::array_chunks_mut
2209 /// [`into_remainder`]: ../../std/slice/struct.ArrayChunksMut.html#method.into_remainder
2210 /// [slices]: slice
2211 #[derive(Debug)]
2212 #[unstable(feature = "array_chunks", issue = "74985")]
2213 pub struct ArrayChunksMut<'a, T: 'a, const N: usize> {
2214 iter: IterMut<'a, [T; N]>,
2215 rem: &'a mut [T],
2216 }
2217
2218 impl<'a, T, const N: usize> ArrayChunksMut<'a, T, N> {
2219 #[inline]
2220 pub(super) fn new(slice: &'a mut [T]) -> Self {
2221 let (array_slice, rem) = slice.as_chunks_mut();
2222 Self { iter: array_slice.iter_mut(), rem }
2223 }
2224
2225 /// Returns the remainder of the original slice that is not going to be
2226 /// returned by the iterator. The returned slice has at most `N-1`
2227 /// elements.
2228 #[unstable(feature = "array_chunks", issue = "74985")]
2229 pub fn into_remainder(self) -> &'a mut [T] {
2230 self.rem
2231 }
2232 }
2233
2234 #[unstable(feature = "array_chunks", issue = "74985")]
2235 impl<'a, T, const N: usize> Iterator for ArrayChunksMut<'a, T, N> {
2236 type Item = &'a mut [T; N];
2237
2238 #[inline]
2239 fn next(&mut self) -> Option<&'a mut [T; N]> {
2240 self.iter.next()
2241 }
2242
2243 #[inline]
2244 fn size_hint(&self) -> (usize, Option<usize>) {
2245 self.iter.size_hint()
2246 }
2247
2248 #[inline]
2249 fn count(self) -> usize {
2250 self.iter.count()
2251 }
2252
2253 #[inline]
2254 fn nth(&mut self, n: usize) -> Option<Self::Item> {
2255 self.iter.nth(n)
2256 }
2257
2258 #[inline]
2259 fn last(self) -> Option<Self::Item> {
2260 self.iter.last()
2261 }
2262
2263 unsafe fn __iterator_get_unchecked(&mut self, i: usize) -> &'a mut [T; N] {
2264 // SAFETY: The safety guarantees of `__iterator_get_unchecked` are transferred to
2265 // the caller.
2266 unsafe { self.iter.__iterator_get_unchecked(i) }
2267 }
2268 }
2269
2270 #[unstable(feature = "array_chunks", issue = "74985")]
2271 impl<'a, T, const N: usize> DoubleEndedIterator for ArrayChunksMut<'a, T, N> {
2272 #[inline]
2273 fn next_back(&mut self) -> Option<&'a mut [T; N]> {
2274 self.iter.next_back()
2275 }
2276
2277 #[inline]
2278 fn nth_back(&mut self, n: usize) -> Option<Self::Item> {
2279 self.iter.nth_back(n)
2280 }
2281 }
2282
2283 #[unstable(feature = "array_chunks", issue = "74985")]
2284 impl<T, const N: usize> ExactSizeIterator for ArrayChunksMut<'_, T, N> {
2285 fn is_empty(&self) -> bool {
2286 self.iter.is_empty()
2287 }
2288 }
2289
2290 #[unstable(feature = "trusted_len", issue = "37572")]
2291 unsafe impl<T, const N: usize> TrustedLen for ArrayChunksMut<'_, T, N> {}
2292
2293 #[unstable(feature = "array_chunks", issue = "74985")]
2294 impl<T, const N: usize> FusedIterator for ArrayChunksMut<'_, T, N> {}
2295
2296 #[doc(hidden)]
2297 #[unstable(feature = "array_chunks", issue = "74985")]
2298 unsafe impl<'a, T, const N: usize> TrustedRandomAccess for ArrayChunksMut<'a, T, N> {
2299 const MAY_HAVE_SIDE_EFFECT: bool = false;
2300 }
2301
2302 /// An iterator over a slice in (non-overlapping) chunks (`chunk_size` elements at a
2303 /// time), starting at the end of the slice.
2304 ///
2305 /// When the slice len is not evenly divided by the chunk size, the last slice
2306 /// of the iteration will be the remainder.
2307 ///
2308 /// This struct is created by the [`rchunks`] method on [slices].
2309 ///
2310 /// # Example
2311 ///
2312 /// ```
2313 /// let slice = ['l', 'o', 'r', 'e', 'm'];
2314 /// let iter = slice.rchunks(2);
2315 /// ```
2316 ///
2317 /// [`rchunks`]: slice::rchunks
2318 /// [slices]: slice
2319 #[derive(Debug)]
2320 #[stable(feature = "rchunks", since = "1.31.0")]
2321 pub struct RChunks<'a, T: 'a> {
2322 v: &'a [T],
2323 chunk_size: usize,
2324 }
2325
2326 impl<'a, T: 'a> RChunks<'a, T> {
2327 #[inline]
2328 pub(super) fn new(slice: &'a [T], size: usize) -> Self {
2329 Self { v: slice, chunk_size: size }
2330 }
2331 }
2332
2333 // FIXME(#26925) Remove in favor of `#[derive(Clone)]`
2334 #[stable(feature = "rchunks", since = "1.31.0")]
2335 impl<T> Clone for RChunks<'_, T> {
2336 fn clone(&self) -> Self {
2337 RChunks { v: self.v, chunk_size: self.chunk_size }
2338 }
2339 }
2340
2341 #[stable(feature = "rchunks", since = "1.31.0")]
2342 impl<'a, T> Iterator for RChunks<'a, T> {
2343 type Item = &'a [T];
2344
2345 #[inline]
2346 fn next(&mut self) -> Option<&'a [T]> {
2347 if self.v.is_empty() {
2348 None
2349 } else {
2350 let chunksz = cmp::min(self.v.len(), self.chunk_size);
2351 let (fst, snd) = self.v.split_at(self.v.len() - chunksz);
2352 self.v = fst;
2353 Some(snd)
2354 }
2355 }
2356
2357 #[inline]
2358 fn size_hint(&self) -> (usize, Option<usize>) {
2359 if self.v.is_empty() {
2360 (0, Some(0))
2361 } else {
2362 let n = self.v.len() / self.chunk_size;
2363 let rem = self.v.len() % self.chunk_size;
2364 let n = if rem > 0 { n + 1 } else { n };
2365 (n, Some(n))
2366 }
2367 }
2368
2369 #[inline]
2370 fn count(self) -> usize {
2371 self.len()
2372 }
2373
2374 #[inline]
2375 fn nth(&mut self, n: usize) -> Option<Self::Item> {
2376 let (end, overflow) = n.overflowing_mul(self.chunk_size);
2377 if end >= self.v.len() || overflow {
2378 self.v = &[];
2379 None
2380 } else {
2381 // Can't underflow because of the check above
2382 let end = self.v.len() - end;
2383 let start = match end.checked_sub(self.chunk_size) {
2384 Some(sum) => sum,
2385 None => 0,
2386 };
2387 let nth = &self.v[start..end];
2388 self.v = &self.v[0..start];
2389 Some(nth)
2390 }
2391 }
2392
2393 #[inline]
2394 fn last(self) -> Option<Self::Item> {
2395 if self.v.is_empty() {
2396 None
2397 } else {
2398 let rem = self.v.len() % self.chunk_size;
2399 let end = if rem == 0 { self.chunk_size } else { rem };
2400 Some(&self.v[0..end])
2401 }
2402 }
2403
2404 #[doc(hidden)]
2405 unsafe fn __iterator_get_unchecked(&mut self, idx: usize) -> Self::Item {
2406 let end = self.v.len() - idx * self.chunk_size;
2407 let start = match end.checked_sub(self.chunk_size) {
2408 None => 0,
2409 Some(start) => start,
2410 };
2411 // SAFETY: mostly identical to `Chunks::__iterator_get_unchecked`.
2412 unsafe { from_raw_parts(self.v.as_ptr().add(start), end - start) }
2413 }
2414 }
2415
2416 #[stable(feature = "rchunks", since = "1.31.0")]
2417 impl<'a, T> DoubleEndedIterator for RChunks<'a, T> {
2418 #[inline]
2419 fn next_back(&mut self) -> Option<&'a [T]> {
2420 if self.v.is_empty() {
2421 None
2422 } else {
2423 let remainder = self.v.len() % self.chunk_size;
2424 let chunksz = if remainder != 0 { remainder } else { self.chunk_size };
2425 let (fst, snd) = self.v.split_at(chunksz);
2426 self.v = snd;
2427 Some(fst)
2428 }
2429 }
2430
2431 #[inline]
2432 fn nth_back(&mut self, n: usize) -> Option<Self::Item> {
2433 let len = self.len();
2434 if n >= len {
2435 self.v = &[];
2436 None
2437 } else {
2438 // can't underflow because `n < len`
2439 let offset_from_end = (len - 1 - n) * self.chunk_size;
2440 let end = self.v.len() - offset_from_end;
2441 let start = end.saturating_sub(self.chunk_size);
2442 let nth_back = &self.v[start..end];
2443 self.v = &self.v[end..];
2444 Some(nth_back)
2445 }
2446 }
2447 }
2448
2449 #[stable(feature = "rchunks", since = "1.31.0")]
2450 impl<T> ExactSizeIterator for RChunks<'_, T> {}
2451
2452 #[unstable(feature = "trusted_len", issue = "37572")]
2453 unsafe impl<T> TrustedLen for RChunks<'_, T> {}
2454
2455 #[stable(feature = "rchunks", since = "1.31.0")]
2456 impl<T> FusedIterator for RChunks<'_, T> {}
2457
2458 #[doc(hidden)]
2459 #[unstable(feature = "trusted_random_access", issue = "none")]
2460 unsafe impl<'a, T> TrustedRandomAccess for RChunks<'a, T> {
2461 const MAY_HAVE_SIDE_EFFECT: bool = false;
2462 }
2463
2464 /// An iterator over a slice in (non-overlapping) mutable chunks (`chunk_size`
2465 /// elements at a time), starting at the end of the slice.
2466 ///
2467 /// When the slice len is not evenly divided by the chunk size, the last slice
2468 /// of the iteration will be the remainder.
2469 ///
2470 /// This struct is created by the [`rchunks_mut`] method on [slices].
2471 ///
2472 /// # Example
2473 ///
2474 /// ```
2475 /// let mut slice = ['l', 'o', 'r', 'e', 'm'];
2476 /// let iter = slice.rchunks_mut(2);
2477 /// ```
2478 ///
2479 /// [`rchunks_mut`]: slice::rchunks_mut
2480 /// [slices]: slice
2481 #[derive(Debug)]
2482 #[stable(feature = "rchunks", since = "1.31.0")]
2483 pub struct RChunksMut<'a, T: 'a> {
2484 v: &'a mut [T],
2485 chunk_size: usize,
2486 }
2487
2488 impl<'a, T: 'a> RChunksMut<'a, T> {
2489 #[inline]
2490 pub(super) fn new(slice: &'a mut [T], size: usize) -> Self {
2491 Self { v: slice, chunk_size: size }
2492 }
2493 }
2494
2495 #[stable(feature = "rchunks", since = "1.31.0")]
2496 impl<'a, T> Iterator for RChunksMut<'a, T> {
2497 type Item = &'a mut [T];
2498
2499 #[inline]
2500 fn next(&mut self) -> Option<&'a mut [T]> {
2501 if self.v.is_empty() {
2502 None
2503 } else {
2504 let sz = cmp::min(self.v.len(), self.chunk_size);
2505 let tmp = mem::replace(&mut self.v, &mut []);
2506 let tmp_len = tmp.len();
2507 let (head, tail) = tmp.split_at_mut(tmp_len - sz);
2508 self.v = head;
2509 Some(tail)
2510 }
2511 }
2512
2513 #[inline]
2514 fn size_hint(&self) -> (usize, Option<usize>) {
2515 if self.v.is_empty() {
2516 (0, Some(0))
2517 } else {
2518 let n = self.v.len() / self.chunk_size;
2519 let rem = self.v.len() % self.chunk_size;
2520 let n = if rem > 0 { n + 1 } else { n };
2521 (n, Some(n))
2522 }
2523 }
2524
2525 #[inline]
2526 fn count(self) -> usize {
2527 self.len()
2528 }
2529
2530 #[inline]
2531 fn nth(&mut self, n: usize) -> Option<&'a mut [T]> {
2532 let (end, overflow) = n.overflowing_mul(self.chunk_size);
2533 if end >= self.v.len() || overflow {
2534 self.v = &mut [];
2535 None
2536 } else {
2537 // Can't underflow because of the check above
2538 let end = self.v.len() - end;
2539 let start = match end.checked_sub(self.chunk_size) {
2540 Some(sum) => sum,
2541 None => 0,
2542 };
2543 let tmp = mem::replace(&mut self.v, &mut []);
2544 let (head, tail) = tmp.split_at_mut(start);
2545 let (nth, _) = tail.split_at_mut(end - start);
2546 self.v = head;
2547 Some(nth)
2548 }
2549 }
2550
2551 #[inline]
2552 fn last(self) -> Option<Self::Item> {
2553 if self.v.is_empty() {
2554 None
2555 } else {
2556 let rem = self.v.len() % self.chunk_size;
2557 let end = if rem == 0 { self.chunk_size } else { rem };
2558 Some(&mut self.v[0..end])
2559 }
2560 }
2561
2562 #[doc(hidden)]
2563 unsafe fn __iterator_get_unchecked(&mut self, idx: usize) -> Self::Item {
2564 let end = self.v.len() - idx * self.chunk_size;
2565 let start = match end.checked_sub(self.chunk_size) {
2566 None => 0,
2567 Some(start) => start,
2568 };
2569 // SAFETY: see comments for `RChunks::__iterator_get_unchecked` and
2570 // `ChunksMut::__iterator_get_unchecked`
2571 unsafe { from_raw_parts_mut(self.v.as_mut_ptr().add(start), end - start) }
2572 }
2573 }
2574
2575 #[stable(feature = "rchunks", since = "1.31.0")]
2576 impl<'a, T> DoubleEndedIterator for RChunksMut<'a, T> {
2577 #[inline]
2578 fn next_back(&mut self) -> Option<&'a mut [T]> {
2579 if self.v.is_empty() {
2580 None
2581 } else {
2582 let remainder = self.v.len() % self.chunk_size;
2583 let sz = if remainder != 0 { remainder } else { self.chunk_size };
2584 let tmp = mem::replace(&mut self.v, &mut []);
2585 let (head, tail) = tmp.split_at_mut(sz);
2586 self.v = tail;
2587 Some(head)
2588 }
2589 }
2590
2591 #[inline]
2592 fn nth_back(&mut self, n: usize) -> Option<Self::Item> {
2593 let len = self.len();
2594 if n >= len {
2595 self.v = &mut [];
2596 None
2597 } else {
2598 // can't underflow because `n < len`
2599 let offset_from_end = (len - 1 - n) * self.chunk_size;
2600 let end = self.v.len() - offset_from_end;
2601 let start = end.saturating_sub(self.chunk_size);
2602 let (tmp, tail) = mem::replace(&mut self.v, &mut []).split_at_mut(end);
2603 let (_, nth_back) = tmp.split_at_mut(start);
2604 self.v = tail;
2605 Some(nth_back)
2606 }
2607 }
2608 }
2609
2610 #[stable(feature = "rchunks", since = "1.31.0")]
2611 impl<T> ExactSizeIterator for RChunksMut<'_, T> {}
2612
2613 #[unstable(feature = "trusted_len", issue = "37572")]
2614 unsafe impl<T> TrustedLen for RChunksMut<'_, T> {}
2615
2616 #[stable(feature = "rchunks", since = "1.31.0")]
2617 impl<T> FusedIterator for RChunksMut<'_, T> {}
2618
2619 #[doc(hidden)]
2620 #[unstable(feature = "trusted_random_access", issue = "none")]
2621 unsafe impl<'a, T> TrustedRandomAccess for RChunksMut<'a, T> {
2622 const MAY_HAVE_SIDE_EFFECT: bool = false;
2623 }
2624
2625 /// An iterator over a slice in (non-overlapping) chunks (`chunk_size` elements at a
2626 /// time), starting at the end of the slice.
2627 ///
2628 /// When the slice len is not evenly divided by the chunk size, the last
2629 /// up to `chunk_size-1` elements will be omitted but can be retrieved from
2630 /// the [`remainder`] function from the iterator.
2631 ///
2632 /// This struct is created by the [`rchunks_exact`] method on [slices].
2633 ///
2634 /// # Example
2635 ///
2636 /// ```
2637 /// let slice = ['l', 'o', 'r', 'e', 'm'];
2638 /// let iter = slice.rchunks_exact(2);
2639 /// ```
2640 ///
2641 /// [`rchunks_exact`]: slice::rchunks_exact
2642 /// [`remainder`]: ChunksExact::remainder
2643 /// [slices]: slice
2644 #[derive(Debug)]
2645 #[stable(feature = "rchunks", since = "1.31.0")]
2646 pub struct RChunksExact<'a, T: 'a> {
2647 v: &'a [T],
2648 rem: &'a [T],
2649 chunk_size: usize,
2650 }
2651
2652 impl<'a, T> RChunksExact<'a, T> {
2653 #[inline]
2654 pub(super) fn new(slice: &'a [T], chunk_size: usize) -> Self {
2655 let rem = slice.len() % chunk_size;
2656 // SAFETY: 0 <= rem <= slice.len() by construction above
2657 let (fst, snd) = unsafe { slice.split_at_unchecked(rem) };
2658 Self { v: snd, rem: fst, chunk_size }
2659 }
2660
2661 /// Returns the remainder of the original slice that is not going to be
2662 /// returned by the iterator. The returned slice has at most `chunk_size-1`
2663 /// elements.
2664 #[stable(feature = "rchunks", since = "1.31.0")]
2665 pub fn remainder(&self) -> &'a [T] {
2666 self.rem
2667 }
2668 }
2669
2670 // FIXME(#26925) Remove in favor of `#[derive(Clone)]`
2671 #[stable(feature = "rchunks", since = "1.31.0")]
2672 impl<'a, T> Clone for RChunksExact<'a, T> {
2673 fn clone(&self) -> RChunksExact<'a, T> {
2674 RChunksExact { v: self.v, rem: self.rem, chunk_size: self.chunk_size }
2675 }
2676 }
2677
2678 #[stable(feature = "rchunks", since = "1.31.0")]
2679 impl<'a, T> Iterator for RChunksExact<'a, T> {
2680 type Item = &'a [T];
2681
2682 #[inline]
2683 fn next(&mut self) -> Option<&'a [T]> {
2684 if self.v.len() < self.chunk_size {
2685 None
2686 } else {
2687 let (fst, snd) = self.v.split_at(self.v.len() - self.chunk_size);
2688 self.v = fst;
2689 Some(snd)
2690 }
2691 }
2692
2693 #[inline]
2694 fn size_hint(&self) -> (usize, Option<usize>) {
2695 let n = self.v.len() / self.chunk_size;
2696 (n, Some(n))
2697 }
2698
2699 #[inline]
2700 fn count(self) -> usize {
2701 self.len()
2702 }
2703
2704 #[inline]
2705 fn nth(&mut self, n: usize) -> Option<Self::Item> {
2706 let (end, overflow) = n.overflowing_mul(self.chunk_size);
2707 if end >= self.v.len() || overflow {
2708 self.v = &[];
2709 None
2710 } else {
2711 let (fst, _) = self.v.split_at(self.v.len() - end);
2712 self.v = fst;
2713 self.next()
2714 }
2715 }
2716
2717 #[inline]
2718 fn last(mut self) -> Option<Self::Item> {
2719 self.next_back()
2720 }
2721
2722 #[doc(hidden)]
2723 unsafe fn __iterator_get_unchecked(&mut self, idx: usize) -> Self::Item {
2724 let end = self.v.len() - idx * self.chunk_size;
2725 let start = end - self.chunk_size;
2726 // SAFETY:
2727 // SAFETY: mostmy identical to `Chunks::__iterator_get_unchecked`.
2728 unsafe { from_raw_parts(self.v.as_ptr().add(start), self.chunk_size) }
2729 }
2730 }
2731
2732 #[stable(feature = "rchunks", since = "1.31.0")]
2733 impl<'a, T> DoubleEndedIterator for RChunksExact<'a, T> {
2734 #[inline]
2735 fn next_back(&mut self) -> Option<&'a [T]> {
2736 if self.v.len() < self.chunk_size {
2737 None
2738 } else {
2739 let (fst, snd) = self.v.split_at(self.chunk_size);
2740 self.v = snd;
2741 Some(fst)
2742 }
2743 }
2744
2745 #[inline]
2746 fn nth_back(&mut self, n: usize) -> Option<Self::Item> {
2747 let len = self.len();
2748 if n >= len {
2749 self.v = &[];
2750 None
2751 } else {
2752 // now that we know that `n` corresponds to a chunk,
2753 // none of these operations can underflow/overflow
2754 let offset = (len - n) * self.chunk_size;
2755 let start = self.v.len() - offset;
2756 let end = start + self.chunk_size;
2757 let nth_back = &self.v[start..end];
2758 self.v = &self.v[end..];
2759 Some(nth_back)
2760 }
2761 }
2762 }
2763
2764 #[stable(feature = "rchunks", since = "1.31.0")]
2765 impl<'a, T> ExactSizeIterator for RChunksExact<'a, T> {
2766 fn is_empty(&self) -> bool {
2767 self.v.is_empty()
2768 }
2769 }
2770
2771 #[unstable(feature = "trusted_len", issue = "37572")]
2772 unsafe impl<T> TrustedLen for RChunksExact<'_, T> {}
2773
2774 #[stable(feature = "rchunks", since = "1.31.0")]
2775 impl<T> FusedIterator for RChunksExact<'_, T> {}
2776
2777 #[doc(hidden)]
2778 #[unstable(feature = "trusted_random_access", issue = "none")]
2779 unsafe impl<'a, T> TrustedRandomAccess for RChunksExact<'a, T> {
2780 const MAY_HAVE_SIDE_EFFECT: bool = false;
2781 }
2782
2783 /// An iterator over a slice in (non-overlapping) mutable chunks (`chunk_size`
2784 /// elements at a time), starting at the end of the slice.
2785 ///
2786 /// When the slice len is not evenly divided by the chunk size, the last up to
2787 /// `chunk_size-1` elements will be omitted but can be retrieved from the
2788 /// [`into_remainder`] function from the iterator.
2789 ///
2790 /// This struct is created by the [`rchunks_exact_mut`] method on [slices].
2791 ///
2792 /// # Example
2793 ///
2794 /// ```
2795 /// let mut slice = ['l', 'o', 'r', 'e', 'm'];
2796 /// let iter = slice.rchunks_exact_mut(2);
2797 /// ```
2798 ///
2799 /// [`rchunks_exact_mut`]: slice::rchunks_exact_mut
2800 /// [`into_remainder`]: ChunksExactMut::into_remainder
2801 /// [slices]: slice
2802 #[derive(Debug)]
2803 #[stable(feature = "rchunks", since = "1.31.0")]
2804 pub struct RChunksExactMut<'a, T: 'a> {
2805 v: &'a mut [T],
2806 rem: &'a mut [T],
2807 chunk_size: usize,
2808 }
2809
2810 impl<'a, T> RChunksExactMut<'a, T> {
2811 #[inline]
2812 pub(super) fn new(slice: &'a mut [T], chunk_size: usize) -> Self {
2813 let rem = slice.len() % chunk_size;
2814 // SAFETY: 0 <= rem <= slice.len() by construction above
2815 let (fst, snd) = unsafe { slice.split_at_mut_unchecked(rem) };
2816 Self { v: snd, rem: fst, chunk_size }
2817 }
2818
2819 /// Returns the remainder of the original slice that is not going to be
2820 /// returned by the iterator. The returned slice has at most `chunk_size-1`
2821 /// elements.
2822 #[stable(feature = "rchunks", since = "1.31.0")]
2823 pub fn into_remainder(self) -> &'a mut [T] {
2824 self.rem
2825 }
2826 }
2827
2828 #[stable(feature = "rchunks", since = "1.31.0")]
2829 impl<'a, T> Iterator for RChunksExactMut<'a, T> {
2830 type Item = &'a mut [T];
2831
2832 #[inline]
2833 fn next(&mut self) -> Option<&'a mut [T]> {
2834 if self.v.len() < self.chunk_size {
2835 None
2836 } else {
2837 let tmp = mem::replace(&mut self.v, &mut []);
2838 let tmp_len = tmp.len();
2839 let (head, tail) = tmp.split_at_mut(tmp_len - self.chunk_size);
2840 self.v = head;
2841 Some(tail)
2842 }
2843 }
2844
2845 #[inline]
2846 fn size_hint(&self) -> (usize, Option<usize>) {
2847 let n = self.v.len() / self.chunk_size;
2848 (n, Some(n))
2849 }
2850
2851 #[inline]
2852 fn count(self) -> usize {
2853 self.len()
2854 }
2855
2856 #[inline]
2857 fn nth(&mut self, n: usize) -> Option<&'a mut [T]> {
2858 let (end, overflow) = n.overflowing_mul(self.chunk_size);
2859 if end >= self.v.len() || overflow {
2860 self.v = &mut [];
2861 None
2862 } else {
2863 let tmp = mem::replace(&mut self.v, &mut []);
2864 let tmp_len = tmp.len();
2865 let (fst, _) = tmp.split_at_mut(tmp_len - end);
2866 self.v = fst;
2867 self.next()
2868 }
2869 }
2870
2871 #[inline]
2872 fn last(mut self) -> Option<Self::Item> {
2873 self.next_back()
2874 }
2875
2876 #[doc(hidden)]
2877 unsafe fn __iterator_get_unchecked(&mut self, idx: usize) -> Self::Item {
2878 let end = self.v.len() - idx * self.chunk_size;
2879 let start = end - self.chunk_size;
2880 // SAFETY: see comments for `RChunksMut::__iterator_get_unchecked`.
2881 unsafe { from_raw_parts_mut(self.v.as_mut_ptr().add(start), self.chunk_size) }
2882 }
2883 }
2884
2885 #[stable(feature = "rchunks", since = "1.31.0")]
2886 impl<'a, T> DoubleEndedIterator for RChunksExactMut<'a, T> {
2887 #[inline]
2888 fn next_back(&mut self) -> Option<&'a mut [T]> {
2889 if self.v.len() < self.chunk_size {
2890 None
2891 } else {
2892 let tmp = mem::replace(&mut self.v, &mut []);
2893 let (head, tail) = tmp.split_at_mut(self.chunk_size);
2894 self.v = tail;
2895 Some(head)
2896 }
2897 }
2898
2899 #[inline]
2900 fn nth_back(&mut self, n: usize) -> Option<Self::Item> {
2901 let len = self.len();
2902 if n >= len {
2903 self.v = &mut [];
2904 None
2905 } else {
2906 // now that we know that `n` corresponds to a chunk,
2907 // none of these operations can underflow/overflow
2908 let offset = (len - n) * self.chunk_size;
2909 let start = self.v.len() - offset;
2910 let end = start + self.chunk_size;
2911 let (tmp, tail) = mem::replace(&mut self.v, &mut []).split_at_mut(end);
2912 let (_, nth_back) = tmp.split_at_mut(start);
2913 self.v = tail;
2914 Some(nth_back)
2915 }
2916 }
2917 }
2918
2919 #[stable(feature = "rchunks", since = "1.31.0")]
2920 impl<T> ExactSizeIterator for RChunksExactMut<'_, T> {
2921 fn is_empty(&self) -> bool {
2922 self.v.is_empty()
2923 }
2924 }
2925
2926 #[unstable(feature = "trusted_len", issue = "37572")]
2927 unsafe impl<T> TrustedLen for RChunksExactMut<'_, T> {}
2928
2929 #[stable(feature = "rchunks", since = "1.31.0")]
2930 impl<T> FusedIterator for RChunksExactMut<'_, T> {}
2931
2932 #[doc(hidden)]
2933 #[unstable(feature = "trusted_random_access", issue = "none")]
2934 unsafe impl<'a, T> TrustedRandomAccess for RChunksExactMut<'a, T> {
2935 const MAY_HAVE_SIDE_EFFECT: bool = false;
2936 }
2937
2938 #[doc(hidden)]
2939 #[unstable(feature = "trusted_random_access", issue = "none")]
2940 unsafe impl<'a, T> TrustedRandomAccess for Iter<'a, T> {
2941 const MAY_HAVE_SIDE_EFFECT: bool = false;
2942 }
2943
2944 #[doc(hidden)]
2945 #[unstable(feature = "trusted_random_access", issue = "none")]
2946 unsafe impl<'a, T> TrustedRandomAccess for IterMut<'a, T> {
2947 const MAY_HAVE_SIDE_EFFECT: bool = false;
2948 }
2949
2950 /// An iterator over slice in (non-overlapping) chunks separated by a predicate.
2951 ///
2952 /// This struct is created by the [`group_by`] method on [slices].
2953 ///
2954 /// [`group_by`]: slice::group_by
2955 /// [slices]: slice
2956 #[unstable(feature = "slice_group_by", issue = "80552")]
2957 pub struct GroupBy<'a, T: 'a, P> {
2958 slice: &'a [T],
2959 predicate: P,
2960 }
2961
2962 #[unstable(feature = "slice_group_by", issue = "80552")]
2963 impl<'a, T: 'a, P> GroupBy<'a, T, P> {
2964 pub(super) fn new(slice: &'a [T], predicate: P) -> Self {
2965 GroupBy { slice, predicate }
2966 }
2967 }
2968
2969 #[unstable(feature = "slice_group_by", issue = "80552")]
2970 impl<'a, T: 'a, P> Iterator for GroupBy<'a, T, P>
2971 where
2972 P: FnMut(&T, &T) -> bool,
2973 {
2974 type Item = &'a [T];
2975
2976 #[inline]
2977 fn next(&mut self) -> Option<Self::Item> {
2978 if self.slice.is_empty() {
2979 None
2980 } else {
2981 let mut len = 1;
2982 let mut iter = self.slice.windows(2);
2983 while let Some([l, r]) = iter.next() {
2984 if (self.predicate)(l, r) { len += 1 } else { break }
2985 }
2986 let (head, tail) = self.slice.split_at(len);
2987 self.slice = tail;
2988 Some(head)
2989 }
2990 }
2991
2992 #[inline]
2993 fn size_hint(&self) -> (usize, Option<usize>) {
2994 if self.slice.is_empty() { (0, Some(0)) } else { (1, Some(self.slice.len())) }
2995 }
2996
2997 #[inline]
2998 fn last(mut self) -> Option<Self::Item> {
2999 self.next_back()
3000 }
3001 }
3002
3003 #[unstable(feature = "slice_group_by", issue = "80552")]
3004 impl<'a, T: 'a, P> DoubleEndedIterator for GroupBy<'a, T, P>
3005 where
3006 P: FnMut(&T, &T) -> bool,
3007 {
3008 #[inline]
3009 fn next_back(&mut self) -> Option<Self::Item> {
3010 if self.slice.is_empty() {
3011 None
3012 } else {
3013 let mut len = 1;
3014 let mut iter = self.slice.windows(2);
3015 while let Some([l, r]) = iter.next_back() {
3016 if (self.predicate)(l, r) { len += 1 } else { break }
3017 }
3018 let (head, tail) = self.slice.split_at(self.slice.len() - len);
3019 self.slice = head;
3020 Some(tail)
3021 }
3022 }
3023 }
3024
3025 #[unstable(feature = "slice_group_by", issue = "80552")]
3026 impl<'a, T: 'a, P> FusedIterator for GroupBy<'a, T, P> where P: FnMut(&T, &T) -> bool {}
3027
3028 #[unstable(feature = "slice_group_by", issue = "80552")]
3029 impl<'a, T: 'a + fmt::Debug, P> fmt::Debug for GroupBy<'a, T, P> {
3030 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
3031 f.debug_struct("GroupBy").field("slice", &self.slice).finish()
3032 }
3033 }
3034
3035 /// An iterator over slice in (non-overlapping) mutable chunks separated
3036 /// by a predicate.
3037 ///
3038 /// This struct is created by the [`group_by_mut`] method on [slices].
3039 ///
3040 /// [`group_by_mut`]: slice::group_by_mut
3041 /// [slices]: slice
3042 #[unstable(feature = "slice_group_by", issue = "80552")]
3043 pub struct GroupByMut<'a, T: 'a, P> {
3044 slice: &'a mut [T],
3045 predicate: P,
3046 }
3047
3048 #[unstable(feature = "slice_group_by", issue = "80552")]
3049 impl<'a, T: 'a, P> GroupByMut<'a, T, P> {
3050 pub(super) fn new(slice: &'a mut [T], predicate: P) -> Self {
3051 GroupByMut { slice, predicate }
3052 }
3053 }
3054
3055 #[unstable(feature = "slice_group_by", issue = "80552")]
3056 impl<'a, T: 'a, P> Iterator for GroupByMut<'a, T, P>
3057 where
3058 P: FnMut(&T, &T) -> bool,
3059 {
3060 type Item = &'a mut [T];
3061
3062 #[inline]
3063 fn next(&mut self) -> Option<Self::Item> {
3064 if self.slice.is_empty() {
3065 None
3066 } else {
3067 let mut len = 1;
3068 let mut iter = self.slice.windows(2);
3069 while let Some([l, r]) = iter.next() {
3070 if (self.predicate)(l, r) { len += 1 } else { break }
3071 }
3072 let slice = mem::take(&mut self.slice);
3073 let (head, tail) = slice.split_at_mut(len);
3074 self.slice = tail;
3075 Some(head)
3076 }
3077 }
3078
3079 #[inline]
3080 fn size_hint(&self) -> (usize, Option<usize>) {
3081 if self.slice.is_empty() { (0, Some(0)) } else { (1, Some(self.slice.len())) }
3082 }
3083
3084 #[inline]
3085 fn last(mut self) -> Option<Self::Item> {
3086 self.next_back()
3087 }
3088 }
3089
3090 #[unstable(feature = "slice_group_by", issue = "80552")]
3091 impl<'a, T: 'a, P> DoubleEndedIterator for GroupByMut<'a, T, P>
3092 where
3093 P: FnMut(&T, &T) -> bool,
3094 {
3095 #[inline]
3096 fn next_back(&mut self) -> Option<Self::Item> {
3097 if self.slice.is_empty() {
3098 None
3099 } else {
3100 let mut len = 1;
3101 let mut iter = self.slice.windows(2);
3102 while let Some([l, r]) = iter.next_back() {
3103 if (self.predicate)(l, r) { len += 1 } else { break }
3104 }
3105 let slice = mem::take(&mut self.slice);
3106 let (head, tail) = slice.split_at_mut(slice.len() - len);
3107 self.slice = head;
3108 Some(tail)
3109 }
3110 }
3111 }
3112
3113 #[unstable(feature = "slice_group_by", issue = "80552")]
3114 impl<'a, T: 'a, P> FusedIterator for GroupByMut<'a, T, P> where P: FnMut(&T, &T) -> bool {}
3115
3116 #[unstable(feature = "slice_group_by", issue = "80552")]
3117 impl<'a, T: 'a + fmt::Debug, P> fmt::Debug for GroupByMut<'a, T, P> {
3118 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
3119 f.debug_struct("GroupByMut").field("slice", &self.slice).finish()
3120 }
3121 }