1 // ignore-tidy-filelength
3 //! Slice management and manipulation.
5 //! For more details see [`std::slice`].
7 //! [`std::slice`]: ../../std/slice/index.html
9 #![stable(feature = "rust1", since = "1.0.0")]
11 // How this module is organized.
13 // The library infrastructure for slices is fairly messy. There's
14 // a lot of stuff defined here. Let's keep it clean.
16 // The layout of this file is thus:
18 // * Inherent methods. This is where most of the slice API resides.
19 // * Implementations of a few common traits with important slice ops.
20 // * Definitions of a bunch of iterators.
22 // * The `raw` and `bytes` submodules.
23 // * Boilerplate trait implementations.
25 use crate::cmp::Ordering::{self, Less, Equal, Greater};
28 use crate::intrinsics::{assume, exact_div, unchecked_sub};
31 use crate::ops::{FnMut, Try, self};
32 use crate::option::Option;
33 use crate::option::Option::{None, Some};
34 use crate::result::Result;
35 use crate::result::Result::{Ok, Err};
38 use crate::marker::{Copy, Send, Sync, Sized, self};
40 #[unstable(feature = "slice_internals", issue = "0",
41 reason = "exposed from core to be reused in std; use the memchr crate")]
42 /// Pure rust memchr implementation, taken from rust-memchr
55 /// Returns the number of elements in the slice.
60 /// let a = [1, 2, 3];
61 /// assert_eq!(a.len(), 3);
63 #[stable(feature = "rust1", since = "1.0.0")]
65 #[rustc_const_unstable(feature = "const_slice_len")]
66 pub const fn len(&self) -> usize {
68 crate::ptr::Repr { rust: self }.raw.len
72 /// Returns `true` if the slice has a length of 0.
77 /// let a = [1, 2, 3];
78 /// assert!(!a.is_empty());
80 #[stable(feature = "rust1", since = "1.0.0")]
82 #[rustc_const_unstable(feature = "const_slice_len")]
83 pub const fn is_empty(&self) -> bool {
87 /// Returns the first element of the slice, or `None` if it is empty.
92 /// let v = [10, 40, 30];
93 /// assert_eq!(Some(&10), v.first());
95 /// let w: &[i32] = &[];
96 /// assert_eq!(None, w.first());
98 #[stable(feature = "rust1", since = "1.0.0")]
100 pub fn first(&self) -> Option<&T> {
104 /// Returns a mutable pointer to the first element of the slice, or `None` if it is empty.
109 /// let x = &mut [0, 1, 2];
111 /// if let Some(first) = x.first_mut() {
114 /// assert_eq!(x, &[5, 1, 2]);
116 #[stable(feature = "rust1", since = "1.0.0")]
118 pub fn first_mut(&mut self) -> Option<&mut T> {
122 /// Returns the first and all the rest of the elements of the slice, or `None` if it is empty.
127 /// let x = &[0, 1, 2];
129 /// if let Some((first, elements)) = x.split_first() {
130 /// assert_eq!(first, &0);
131 /// assert_eq!(elements, &[1, 2]);
134 #[stable(feature = "slice_splits", since = "1.5.0")]
136 pub fn split_first(&self) -> Option<(&T, &[T])> {
137 if self.is_empty() { None } else { Some((&self[0], &self[1..])) }
140 /// Returns the first and all the rest of the elements of the slice, or `None` if it is empty.
145 /// let x = &mut [0, 1, 2];
147 /// if let Some((first, elements)) = x.split_first_mut() {
152 /// assert_eq!(x, &[3, 4, 5]);
154 #[stable(feature = "slice_splits", since = "1.5.0")]
156 pub fn split_first_mut(&mut self) -> Option<(&mut T, &mut [T])> {
157 if self.is_empty() { None } else {
158 let split = self.split_at_mut(1);
159 Some((&mut split.0[0], split.1))
163 /// Returns the last and all the rest of the elements of the slice, or `None` if it is empty.
168 /// let x = &[0, 1, 2];
170 /// if let Some((last, elements)) = x.split_last() {
171 /// assert_eq!(last, &2);
172 /// assert_eq!(elements, &[0, 1]);
175 #[stable(feature = "slice_splits", since = "1.5.0")]
177 pub fn split_last(&self) -> Option<(&T, &[T])> {
178 let len = self.len();
179 if len == 0 { None } else { Some((&self[len - 1], &self[..(len - 1)])) }
182 /// Returns the last and all the rest of the elements of the slice, or `None` if it is empty.
187 /// let x = &mut [0, 1, 2];
189 /// if let Some((last, elements)) = x.split_last_mut() {
194 /// assert_eq!(x, &[4, 5, 3]);
196 #[stable(feature = "slice_splits", since = "1.5.0")]
198 pub fn split_last_mut(&mut self) -> Option<(&mut T, &mut [T])> {
199 let len = self.len();
200 if len == 0 { None } else {
201 let split = self.split_at_mut(len - 1);
202 Some((&mut split.1[0], split.0))
207 /// Returns the last element of the slice, or `None` if it is empty.
212 /// let v = [10, 40, 30];
213 /// assert_eq!(Some(&30), v.last());
215 /// let w: &[i32] = &[];
216 /// assert_eq!(None, w.last());
218 #[stable(feature = "rust1", since = "1.0.0")]
220 pub fn last(&self) -> Option<&T> {
221 let last_idx = self.len().checked_sub(1)?;
225 /// Returns a mutable pointer to the last item in the slice.
230 /// let x = &mut [0, 1, 2];
232 /// if let Some(last) = x.last_mut() {
235 /// assert_eq!(x, &[0, 1, 10]);
237 #[stable(feature = "rust1", since = "1.0.0")]
239 pub fn last_mut(&mut self) -> Option<&mut T> {
240 let last_idx = self.len().checked_sub(1)?;
241 self.get_mut(last_idx)
244 /// Returns a reference to an element or subslice depending on the type of
247 /// - If given a position, returns a reference to the element at that
248 /// position or `None` if out of bounds.
249 /// - If given a range, returns the subslice corresponding to that range,
250 /// or `None` if out of bounds.
255 /// let v = [10, 40, 30];
256 /// assert_eq!(Some(&40), v.get(1));
257 /// assert_eq!(Some(&[10, 40][..]), v.get(0..2));
258 /// assert_eq!(None, v.get(3));
259 /// assert_eq!(None, v.get(0..4));
261 #[stable(feature = "rust1", since = "1.0.0")]
263 pub fn get<I>(&self, index: I) -> Option<&I::Output>
264 where I: SliceIndex<Self>
269 /// Returns a mutable reference to an element or subslice depending on the
270 /// type of index (see [`get`]) or `None` if the index is out of bounds.
272 /// [`get`]: #method.get
277 /// let x = &mut [0, 1, 2];
279 /// if let Some(elem) = x.get_mut(1) {
282 /// assert_eq!(x, &[0, 42, 2]);
284 #[stable(feature = "rust1", since = "1.0.0")]
286 pub fn get_mut<I>(&mut self, index: I) -> Option<&mut I::Output>
287 where I: SliceIndex<Self>
292 /// Returns a reference to an element or subslice, without doing bounds
295 /// This is generally not recommended, use with caution! For a safe
296 /// alternative see [`get`].
298 /// [`get`]: #method.get
303 /// let x = &[1, 2, 4];
306 /// assert_eq!(x.get_unchecked(1), &2);
309 #[stable(feature = "rust1", since = "1.0.0")]
311 pub unsafe fn get_unchecked<I>(&self, index: I) -> &I::Output
312 where I: SliceIndex<Self>
314 index.get_unchecked(self)
317 /// Returns a mutable reference to an element or subslice, without doing
320 /// This is generally not recommended, use with caution! For a safe
321 /// alternative see [`get_mut`].
323 /// [`get_mut`]: #method.get_mut
328 /// let x = &mut [1, 2, 4];
331 /// let elem = x.get_unchecked_mut(1);
334 /// assert_eq!(x, &[1, 13, 4]);
336 #[stable(feature = "rust1", since = "1.0.0")]
338 pub unsafe fn get_unchecked_mut<I>(&mut self, index: I) -> &mut I::Output
339 where I: SliceIndex<Self>
341 index.get_unchecked_mut(self)
344 /// Returns a raw pointer to the slice's buffer.
346 /// The caller must ensure that the slice outlives the pointer this
347 /// function returns, or else it will end up pointing to garbage.
349 /// The caller must also ensure that the memory the pointer (non-transitively) points to
350 /// is never written to (except inside an `UnsafeCell`) using this pointer or any pointer
351 /// derived from it. If you need to mutate the contents of the slice, use [`as_mut_ptr`].
353 /// Modifying the container referenced by this slice may cause its buffer
354 /// to be reallocated, which would also make any pointers to it invalid.
359 /// let x = &[1, 2, 4];
360 /// let x_ptr = x.as_ptr();
363 /// for i in 0..x.len() {
364 /// assert_eq!(x.get_unchecked(i), &*x_ptr.add(i));
369 /// [`as_mut_ptr`]: #method.as_mut_ptr
370 #[stable(feature = "rust1", since = "1.0.0")]
372 pub const fn as_ptr(&self) -> *const T {
373 self as *const [T] as *const T
376 /// Returns an unsafe mutable pointer to the slice's buffer.
378 /// The caller must ensure that the slice outlives the pointer this
379 /// function returns, or else it will end up pointing to garbage.
381 /// Modifying the container referenced by this slice may cause its buffer
382 /// to be reallocated, which would also make any pointers to it invalid.
387 /// let x = &mut [1, 2, 4];
388 /// let x_ptr = x.as_mut_ptr();
391 /// for i in 0..x.len() {
392 /// *x_ptr.add(i) += 2;
395 /// assert_eq!(x, &[3, 4, 6]);
397 #[stable(feature = "rust1", since = "1.0.0")]
399 pub fn as_mut_ptr(&mut self) -> *mut T {
400 self as *mut [T] as *mut T
403 /// Swaps two elements in the slice.
407 /// * a - The index of the first element
408 /// * b - The index of the second element
412 /// Panics if `a` or `b` are out of bounds.
417 /// let mut v = ["a", "b", "c", "d"];
419 /// assert!(v == ["a", "d", "c", "b"]);
421 #[stable(feature = "rust1", since = "1.0.0")]
423 pub fn swap(&mut self, a: usize, b: usize) {
425 // Can't take two mutable loans from one vector, so instead just cast
426 // them to their raw pointers to do the swap
427 let pa: *mut T = &mut self[a];
428 let pb: *mut T = &mut self[b];
433 /// Reverses the order of elements in the slice, in place.
438 /// let mut v = [1, 2, 3];
440 /// assert!(v == [3, 2, 1]);
442 #[stable(feature = "rust1", since = "1.0.0")]
444 pub fn reverse(&mut self) {
445 let mut i: usize = 0;
448 // For very small types, all the individual reads in the normal
449 // path perform poorly. We can do better, given efficient unaligned
450 // load/store, by loading a larger chunk and reversing a register.
452 // Ideally LLVM would do this for us, as it knows better than we do
453 // whether unaligned reads are efficient (since that changes between
454 // different ARM versions, for example) and what the best chunk size
455 // would be. Unfortunately, as of LLVM 4.0 (2017-05) it only unrolls
456 // the loop, so we need to do this ourselves. (Hypothesis: reverse
457 // is troublesome because the sides can be aligned differently --
458 // will be, when the length is odd -- so there's no way of emitting
459 // pre- and postludes to use fully-aligned SIMD in the middle.)
462 cfg!(any(target_arch = "x86", target_arch = "x86_64"));
464 if fast_unaligned && mem::size_of::<T>() == 1 {
465 // Use the llvm.bswap intrinsic to reverse u8s in a usize
466 let chunk = mem::size_of::<usize>();
467 while i + chunk - 1 < ln / 2 {
469 let pa: *mut T = self.get_unchecked_mut(i);
470 let pb: *mut T = self.get_unchecked_mut(ln - i - chunk);
471 let va = ptr::read_unaligned(pa as *mut usize);
472 let vb = ptr::read_unaligned(pb as *mut usize);
473 ptr::write_unaligned(pa as *mut usize, vb.swap_bytes());
474 ptr::write_unaligned(pb as *mut usize, va.swap_bytes());
480 if fast_unaligned && mem::size_of::<T>() == 2 {
481 // Use rotate-by-16 to reverse u16s in a u32
482 let chunk = mem::size_of::<u32>() / 2;
483 while i + chunk - 1 < ln / 2 {
485 let pa: *mut T = self.get_unchecked_mut(i);
486 let pb: *mut T = self.get_unchecked_mut(ln - i - chunk);
487 let va = ptr::read_unaligned(pa as *mut u32);
488 let vb = ptr::read_unaligned(pb as *mut u32);
489 ptr::write_unaligned(pa as *mut u32, vb.rotate_left(16));
490 ptr::write_unaligned(pb as *mut u32, va.rotate_left(16));
497 // Unsafe swap to avoid the bounds check in safe swap.
499 let pa: *mut T = self.get_unchecked_mut(i);
500 let pb: *mut T = self.get_unchecked_mut(ln - i - 1);
507 /// Returns an iterator over the slice.
512 /// let x = &[1, 2, 4];
513 /// let mut iterator = x.iter();
515 /// assert_eq!(iterator.next(), Some(&1));
516 /// assert_eq!(iterator.next(), Some(&2));
517 /// assert_eq!(iterator.next(), Some(&4));
518 /// assert_eq!(iterator.next(), None);
520 #[stable(feature = "rust1", since = "1.0.0")]
522 pub fn iter(&self) -> Iter<'_, T> {
524 let ptr = self.as_ptr();
525 assume(!ptr.is_null());
527 let end = if mem::size_of::<T>() == 0 {
528 (ptr as *const u8).wrapping_add(self.len()) as *const T
536 _marker: marker::PhantomData
541 /// Returns an iterator that allows modifying each value.
546 /// let x = &mut [1, 2, 4];
547 /// for elem in x.iter_mut() {
550 /// assert_eq!(x, &[3, 4, 6]);
552 #[stable(feature = "rust1", since = "1.0.0")]
554 pub fn iter_mut(&mut self) -> IterMut<'_, T> {
556 let ptr = self.as_mut_ptr();
557 assume(!ptr.is_null());
559 let end = if mem::size_of::<T>() == 0 {
560 (ptr as *mut u8).wrapping_add(self.len()) as *mut T
568 _marker: marker::PhantomData
573 /// Returns an iterator over all contiguous windows of length
574 /// `size`. The windows overlap. If the slice is shorter than
575 /// `size`, the iterator returns no values.
579 /// Panics if `size` is 0.
584 /// let slice = ['r', 'u', 's', 't'];
585 /// let mut iter = slice.windows(2);
586 /// assert_eq!(iter.next().unwrap(), &['r', 'u']);
587 /// assert_eq!(iter.next().unwrap(), &['u', 's']);
588 /// assert_eq!(iter.next().unwrap(), &['s', 't']);
589 /// assert!(iter.next().is_none());
592 /// If the slice is shorter than `size`:
595 /// let slice = ['f', 'o', 'o'];
596 /// let mut iter = slice.windows(4);
597 /// assert!(iter.next().is_none());
599 #[stable(feature = "rust1", since = "1.0.0")]
601 pub fn windows(&self, size: usize) -> Windows<'_, T> {
603 Windows { v: self, size }
606 /// Returns an iterator over `chunk_size` elements of the slice at a time, starting at the
607 /// beginning of the slice.
609 /// The chunks are slices and do not overlap. If `chunk_size` does not divide the length of the
610 /// slice, then the last chunk will not have length `chunk_size`.
612 /// See [`chunks_exact`] for a variant of this iterator that returns chunks of always exactly
613 /// `chunk_size` elements, and [`rchunks`] for the same iterator but starting at the end of the
614 /// slice of the slice.
618 /// Panics if `chunk_size` is 0.
623 /// let slice = ['l', 'o', 'r', 'e', 'm'];
624 /// let mut iter = slice.chunks(2);
625 /// assert_eq!(iter.next().unwrap(), &['l', 'o']);
626 /// assert_eq!(iter.next().unwrap(), &['r', 'e']);
627 /// assert_eq!(iter.next().unwrap(), &['m']);
628 /// assert!(iter.next().is_none());
631 /// [`chunks_exact`]: #method.chunks_exact
632 /// [`rchunks`]: #method.rchunks
633 #[stable(feature = "rust1", since = "1.0.0")]
635 pub fn chunks(&self, chunk_size: usize) -> Chunks<'_, T> {
636 assert!(chunk_size != 0);
637 Chunks { v: self, chunk_size }
640 /// Returns an iterator over `chunk_size` elements of the slice at a time, starting at the
641 /// beginning of the slice.
643 /// The chunks are mutable slices, and do not overlap. If `chunk_size` does not divide the
644 /// length of the slice, then the last chunk will not have length `chunk_size`.
646 /// See [`chunks_exact_mut`] for a variant of this iterator that returns chunks of always
647 /// exactly `chunk_size` elements, and [`rchunks_mut`] for the same iterator but starting at
648 /// the end of the slice of the slice.
652 /// Panics if `chunk_size` is 0.
657 /// let v = &mut [0, 0, 0, 0, 0];
658 /// let mut count = 1;
660 /// for chunk in v.chunks_mut(2) {
661 /// for elem in chunk.iter_mut() {
666 /// assert_eq!(v, &[1, 1, 2, 2, 3]);
669 /// [`chunks_exact_mut`]: #method.chunks_exact_mut
670 /// [`rchunks_mut`]: #method.rchunks_mut
671 #[stable(feature = "rust1", since = "1.0.0")]
673 pub fn chunks_mut(&mut self, chunk_size: usize) -> ChunksMut<'_, T> {
674 assert!(chunk_size != 0);
675 ChunksMut { v: self, chunk_size }
678 /// Returns an iterator over `chunk_size` elements of the slice at a time, starting at the
679 /// beginning of the slice.
681 /// The chunks are slices and do not overlap. If `chunk_size` does not divide the length of the
682 /// slice, then the last up to `chunk_size-1` elements will be omitted and can be retrieved
683 /// from the `remainder` function of the iterator.
685 /// Due to each chunk having exactly `chunk_size` elements, the compiler can often optimize the
686 /// resulting code better than in the case of [`chunks`].
688 /// See [`chunks`] for a variant of this iterator that also returns the remainder as a smaller
689 /// chunk, and [`rchunks_exact`] for the same iterator but starting at the end of the slice.
693 /// Panics if `chunk_size` is 0.
698 /// let slice = ['l', 'o', 'r', 'e', 'm'];
699 /// let mut iter = slice.chunks_exact(2);
700 /// assert_eq!(iter.next().unwrap(), &['l', 'o']);
701 /// assert_eq!(iter.next().unwrap(), &['r', 'e']);
702 /// assert!(iter.next().is_none());
703 /// assert_eq!(iter.remainder(), &['m']);
706 /// [`chunks`]: #method.chunks
707 /// [`rchunks_exact`]: #method.rchunks_exact
708 #[stable(feature = "chunks_exact", since = "1.31.0")]
710 pub fn chunks_exact(&self, chunk_size: usize) -> ChunksExact<'_, T> {
711 assert!(chunk_size != 0);
712 let rem = self.len() % chunk_size;
713 let len = self.len() - rem;
714 let (fst, snd) = self.split_at(len);
715 ChunksExact { v: fst, rem: snd, chunk_size }
718 /// Returns an iterator over `chunk_size` elements of the slice at a time, starting at the
719 /// beginning of the slice.
721 /// The chunks are mutable slices, and do not overlap. If `chunk_size` does not divide the
722 /// length of the slice, then the last up to `chunk_size-1` elements will be omitted and can be
723 /// retrieved from the `into_remainder` function of the iterator.
725 /// Due to each chunk having exactly `chunk_size` elements, the compiler can often optimize the
726 /// resulting code better than in the case of [`chunks_mut`].
728 /// See [`chunks_mut`] for a variant of this iterator that also returns the remainder as a
729 /// smaller chunk, and [`rchunks_exact_mut`] for the same iterator but starting at the end of
730 /// the slice of the slice.
734 /// Panics if `chunk_size` is 0.
739 /// let v = &mut [0, 0, 0, 0, 0];
740 /// let mut count = 1;
742 /// for chunk in v.chunks_exact_mut(2) {
743 /// for elem in chunk.iter_mut() {
748 /// assert_eq!(v, &[1, 1, 2, 2, 0]);
751 /// [`chunks_mut`]: #method.chunks_mut
752 /// [`rchunks_exact_mut`]: #method.rchunks_exact_mut
753 #[stable(feature = "chunks_exact", since = "1.31.0")]
755 pub fn chunks_exact_mut(&mut self, chunk_size: usize) -> ChunksExactMut<'_, T> {
756 assert!(chunk_size != 0);
757 let rem = self.len() % chunk_size;
758 let len = self.len() - rem;
759 let (fst, snd) = self.split_at_mut(len);
760 ChunksExactMut { v: fst, rem: snd, chunk_size }
763 /// Returns an iterator over `chunk_size` elements of the slice at a time, starting at the end
766 /// The chunks are slices and do not overlap. If `chunk_size` does not divide the length of the
767 /// slice, then the last chunk will not have length `chunk_size`.
769 /// See [`rchunks_exact`] for a variant of this iterator that returns chunks of always exactly
770 /// `chunk_size` elements, and [`chunks`] for the same iterator but starting at the beginning
775 /// Panics if `chunk_size` is 0.
780 /// let slice = ['l', 'o', 'r', 'e', 'm'];
781 /// let mut iter = slice.rchunks(2);
782 /// assert_eq!(iter.next().unwrap(), &['e', 'm']);
783 /// assert_eq!(iter.next().unwrap(), &['o', 'r']);
784 /// assert_eq!(iter.next().unwrap(), &['l']);
785 /// assert!(iter.next().is_none());
788 /// [`rchunks_exact`]: #method.rchunks_exact
789 /// [`chunks`]: #method.chunks
790 #[stable(feature = "rchunks", since = "1.31.0")]
792 pub fn rchunks(&self, chunk_size: usize) -> RChunks<'_, T> {
793 assert!(chunk_size != 0);
794 RChunks { v: self, chunk_size }
797 /// Returns an iterator over `chunk_size` elements of the slice at a time, starting at the end
800 /// The chunks are mutable slices, and do not overlap. If `chunk_size` does not divide the
801 /// length of the slice, then the last chunk will not have length `chunk_size`.
803 /// See [`rchunks_exact_mut`] for a variant of this iterator that returns chunks of always
804 /// exactly `chunk_size` elements, and [`chunks_mut`] for the same iterator but starting at the
805 /// beginning of the slice.
809 /// Panics if `chunk_size` is 0.
814 /// let v = &mut [0, 0, 0, 0, 0];
815 /// let mut count = 1;
817 /// for chunk in v.rchunks_mut(2) {
818 /// for elem in chunk.iter_mut() {
823 /// assert_eq!(v, &[3, 2, 2, 1, 1]);
826 /// [`rchunks_exact_mut`]: #method.rchunks_exact_mut
827 /// [`chunks_mut`]: #method.chunks_mut
828 #[stable(feature = "rchunks", since = "1.31.0")]
830 pub fn rchunks_mut(&mut self, chunk_size: usize) -> RChunksMut<'_, T> {
831 assert!(chunk_size != 0);
832 RChunksMut { v: self, chunk_size }
835 /// Returns an iterator over `chunk_size` elements of the slice at a time, starting at the
836 /// end of the slice.
838 /// The chunks are slices and do not overlap. If `chunk_size` does not divide the length of the
839 /// slice, then the last up to `chunk_size-1` elements will be omitted and can be retrieved
840 /// from the `remainder` function of the iterator.
842 /// Due to each chunk having exactly `chunk_size` elements, the compiler can often optimize the
843 /// resulting code better than in the case of [`chunks`].
845 /// See [`rchunks`] for a variant of this iterator that also returns the remainder as a smaller
846 /// chunk, and [`chunks_exact`] for the same iterator but starting at the beginning of the
851 /// Panics if `chunk_size` is 0.
856 /// let slice = ['l', 'o', 'r', 'e', 'm'];
857 /// let mut iter = slice.rchunks_exact(2);
858 /// assert_eq!(iter.next().unwrap(), &['e', 'm']);
859 /// assert_eq!(iter.next().unwrap(), &['o', 'r']);
860 /// assert!(iter.next().is_none());
861 /// assert_eq!(iter.remainder(), &['l']);
864 /// [`chunks`]: #method.chunks
865 /// [`rchunks`]: #method.rchunks
866 /// [`chunks_exact`]: #method.chunks_exact
867 #[stable(feature = "rchunks", since = "1.31.0")]
869 pub fn rchunks_exact(&self, chunk_size: usize) -> RChunksExact<'_, T> {
870 assert!(chunk_size != 0);
871 let rem = self.len() % chunk_size;
872 let (fst, snd) = self.split_at(rem);
873 RChunksExact { v: snd, rem: fst, chunk_size }
876 /// Returns an iterator over `chunk_size` elements of the slice at a time, starting at the end
879 /// The chunks are mutable slices, and do not overlap. If `chunk_size` does not divide the
880 /// length of the slice, then the last up to `chunk_size-1` elements will be omitted and can be
881 /// retrieved from the `into_remainder` function of the iterator.
883 /// Due to each chunk having exactly `chunk_size` elements, the compiler can often optimize the
884 /// resulting code better than in the case of [`chunks_mut`].
886 /// See [`rchunks_mut`] for a variant of this iterator that also returns the remainder as a
887 /// smaller chunk, and [`chunks_exact_mut`] for the same iterator but starting at the beginning
892 /// Panics if `chunk_size` is 0.
897 /// let v = &mut [0, 0, 0, 0, 0];
898 /// let mut count = 1;
900 /// for chunk in v.rchunks_exact_mut(2) {
901 /// for elem in chunk.iter_mut() {
906 /// assert_eq!(v, &[0, 2, 2, 1, 1]);
909 /// [`chunks_mut`]: #method.chunks_mut
910 /// [`rchunks_mut`]: #method.rchunks_mut
911 /// [`chunks_exact_mut`]: #method.chunks_exact_mut
912 #[stable(feature = "rchunks", since = "1.31.0")]
914 pub fn rchunks_exact_mut(&mut self, chunk_size: usize) -> RChunksExactMut<'_, T> {
915 assert!(chunk_size != 0);
916 let rem = self.len() % chunk_size;
917 let (fst, snd) = self.split_at_mut(rem);
918 RChunksExactMut { v: snd, rem: fst, chunk_size }
921 /// Divides one slice into two at an index.
923 /// The first will contain all indices from `[0, mid)` (excluding
924 /// the index `mid` itself) and the second will contain all
925 /// indices from `[mid, len)` (excluding the index `len` itself).
929 /// Panics if `mid > len`.
934 /// let v = [1, 2, 3, 4, 5, 6];
937 /// let (left, right) = v.split_at(0);
938 /// assert!(left == []);
939 /// assert!(right == [1, 2, 3, 4, 5, 6]);
943 /// let (left, right) = v.split_at(2);
944 /// assert!(left == [1, 2]);
945 /// assert!(right == [3, 4, 5, 6]);
949 /// let (left, right) = v.split_at(6);
950 /// assert!(left == [1, 2, 3, 4, 5, 6]);
951 /// assert!(right == []);
954 #[stable(feature = "rust1", since = "1.0.0")]
956 pub fn split_at(&self, mid: usize) -> (&[T], &[T]) {
957 (&self[..mid], &self[mid..])
960 /// Divides one mutable slice into two at an index.
962 /// The first will contain all indices from `[0, mid)` (excluding
963 /// the index `mid` itself) and the second will contain all
964 /// indices from `[mid, len)` (excluding the index `len` itself).
968 /// Panics if `mid > len`.
973 /// let mut v = [1, 0, 3, 0, 5, 6];
974 /// // scoped to restrict the lifetime of the borrows
976 /// let (left, right) = v.split_at_mut(2);
977 /// assert!(left == [1, 0]);
978 /// assert!(right == [3, 0, 5, 6]);
982 /// assert!(v == [1, 2, 3, 4, 5, 6]);
984 #[stable(feature = "rust1", since = "1.0.0")]
986 pub fn split_at_mut(&mut self, mid: usize) -> (&mut [T], &mut [T]) {
987 let len = self.len();
988 let ptr = self.as_mut_ptr();
993 (from_raw_parts_mut(ptr, mid),
994 from_raw_parts_mut(ptr.add(mid), len - mid))
998 /// Returns an iterator over subslices separated by elements that match
999 /// `pred`. The matched element is not contained in the subslices.
1004 /// let slice = [10, 40, 33, 20];
1005 /// let mut iter = slice.split(|num| num % 3 == 0);
1007 /// assert_eq!(iter.next().unwrap(), &[10, 40]);
1008 /// assert_eq!(iter.next().unwrap(), &[20]);
1009 /// assert!(iter.next().is_none());
1012 /// If the first element is matched, an empty slice will be the first item
1013 /// returned by the iterator. Similarly, if the last element in the slice
1014 /// is matched, an empty slice will be the last item returned by the
1018 /// let slice = [10, 40, 33];
1019 /// let mut iter = slice.split(|num| num % 3 == 0);
1021 /// assert_eq!(iter.next().unwrap(), &[10, 40]);
1022 /// assert_eq!(iter.next().unwrap(), &[]);
1023 /// assert!(iter.next().is_none());
1026 /// If two matched elements are directly adjacent, an empty slice will be
1027 /// present between them:
1030 /// let slice = [10, 6, 33, 20];
1031 /// let mut iter = slice.split(|num| num % 3 == 0);
1033 /// assert_eq!(iter.next().unwrap(), &[10]);
1034 /// assert_eq!(iter.next().unwrap(), &[]);
1035 /// assert_eq!(iter.next().unwrap(), &[20]);
1036 /// assert!(iter.next().is_none());
1038 #[stable(feature = "rust1", since = "1.0.0")]
1040 pub fn split<F>(&self, pred: F) -> Split<'_, T, F>
1041 where F: FnMut(&T) -> bool
1050 /// Returns an iterator over mutable subslices separated by elements that
1051 /// match `pred`. The matched element is not contained in the subslices.
1056 /// let mut v = [10, 40, 30, 20, 60, 50];
1058 /// for group in v.split_mut(|num| *num % 3 == 0) {
1061 /// assert_eq!(v, [1, 40, 30, 1, 60, 1]);
1063 #[stable(feature = "rust1", since = "1.0.0")]
1065 pub fn split_mut<F>(&mut self, pred: F) -> SplitMut<'_, T, F>
1066 where F: FnMut(&T) -> bool
1068 SplitMut { v: self, pred, finished: false }
1071 /// Returns an iterator over subslices separated by elements that match
1072 /// `pred`, starting at the end of the slice and working backwards.
1073 /// The matched element is not contained in the subslices.
1078 /// let slice = [11, 22, 33, 0, 44, 55];
1079 /// let mut iter = slice.rsplit(|num| *num == 0);
1081 /// assert_eq!(iter.next().unwrap(), &[44, 55]);
1082 /// assert_eq!(iter.next().unwrap(), &[11, 22, 33]);
1083 /// assert_eq!(iter.next(), None);
1086 /// As with `split()`, if the first or last element is matched, an empty
1087 /// slice will be the first (or last) item returned by the iterator.
1090 /// let v = &[0, 1, 1, 2, 3, 5, 8];
1091 /// let mut it = v.rsplit(|n| *n % 2 == 0);
1092 /// assert_eq!(it.next().unwrap(), &[]);
1093 /// assert_eq!(it.next().unwrap(), &[3, 5]);
1094 /// assert_eq!(it.next().unwrap(), &[1, 1]);
1095 /// assert_eq!(it.next().unwrap(), &[]);
1096 /// assert_eq!(it.next(), None);
1098 #[stable(feature = "slice_rsplit", since = "1.27.0")]
1100 pub fn rsplit<F>(&self, pred: F) -> RSplit<'_, T, F>
1101 where F: FnMut(&T) -> bool
1103 RSplit { inner: self.split(pred) }
1106 /// Returns an iterator over mutable subslices separated by elements that
1107 /// match `pred`, starting at the end of the slice and working
1108 /// backwards. The matched element is not contained in the subslices.
1113 /// let mut v = [100, 400, 300, 200, 600, 500];
1115 /// let mut count = 0;
1116 /// for group in v.rsplit_mut(|num| *num % 3 == 0) {
1118 /// group[0] = count;
1120 /// assert_eq!(v, [3, 400, 300, 2, 600, 1]);
1123 #[stable(feature = "slice_rsplit", since = "1.27.0")]
1125 pub fn rsplit_mut<F>(&mut self, pred: F) -> RSplitMut<'_, T, F>
1126 where F: FnMut(&T) -> bool
1128 RSplitMut { inner: self.split_mut(pred) }
1131 /// Returns an iterator over subslices separated by elements that match
1132 /// `pred`, limited to returning at most `n` items. The matched element is
1133 /// not contained in the subslices.
1135 /// The last element returned, if any, will contain the remainder of the
1140 /// Print the slice split once by numbers divisible by 3 (i.e., `[10, 40]`,
1141 /// `[20, 60, 50]`):
1144 /// let v = [10, 40, 30, 20, 60, 50];
1146 /// for group in v.splitn(2, |num| *num % 3 == 0) {
1147 /// println!("{:?}", group);
1150 #[stable(feature = "rust1", since = "1.0.0")]
1152 pub fn splitn<F>(&self, n: usize, pred: F) -> SplitN<'_, T, F>
1153 where F: FnMut(&T) -> bool
1156 inner: GenericSplitN {
1157 iter: self.split(pred),
1163 /// Returns an iterator over subslices separated by elements that match
1164 /// `pred`, limited to returning at most `n` items. The matched element is
1165 /// not contained in the subslices.
1167 /// The last element returned, if any, will contain the remainder of the
1173 /// let mut v = [10, 40, 30, 20, 60, 50];
1175 /// for group in v.splitn_mut(2, |num| *num % 3 == 0) {
1178 /// assert_eq!(v, [1, 40, 30, 1, 60, 50]);
1180 #[stable(feature = "rust1", since = "1.0.0")]
1182 pub fn splitn_mut<F>(&mut self, n: usize, pred: F) -> SplitNMut<'_, T, F>
1183 where F: FnMut(&T) -> bool
1186 inner: GenericSplitN {
1187 iter: self.split_mut(pred),
1193 /// Returns an iterator over subslices separated by elements that match
1194 /// `pred` limited to returning at most `n` items. This starts at the end of
1195 /// the slice and works backwards. The matched element is not contained in
1198 /// The last element returned, if any, will contain the remainder of the
1203 /// Print the slice split once, starting from the end, by numbers divisible
1204 /// by 3 (i.e., `[50]`, `[10, 40, 30, 20]`):
1207 /// let v = [10, 40, 30, 20, 60, 50];
1209 /// for group in v.rsplitn(2, |num| *num % 3 == 0) {
1210 /// println!("{:?}", group);
1213 #[stable(feature = "rust1", since = "1.0.0")]
1215 pub fn rsplitn<F>(&self, n: usize, pred: F) -> RSplitN<'_, T, F>
1216 where F: FnMut(&T) -> bool
1219 inner: GenericSplitN {
1220 iter: self.rsplit(pred),
1226 /// Returns an iterator over subslices separated by elements that match
1227 /// `pred` limited to returning at most `n` items. This starts at the end of
1228 /// the slice and works backwards. The matched element is not contained in
1231 /// The last element returned, if any, will contain the remainder of the
1237 /// let mut s = [10, 40, 30, 20, 60, 50];
1239 /// for group in s.rsplitn_mut(2, |num| *num % 3 == 0) {
1242 /// assert_eq!(s, [1, 40, 30, 20, 60, 1]);
1244 #[stable(feature = "rust1", since = "1.0.0")]
1246 pub fn rsplitn_mut<F>(&mut self, n: usize, pred: F) -> RSplitNMut<'_, T, F>
1247 where F: FnMut(&T) -> bool
1250 inner: GenericSplitN {
1251 iter: self.rsplit_mut(pred),
1257 /// Returns `true` if the slice contains an element with the given value.
1262 /// let v = [10, 40, 30];
1263 /// assert!(v.contains(&30));
1264 /// assert!(!v.contains(&50));
1266 #[stable(feature = "rust1", since = "1.0.0")]
1267 pub fn contains(&self, x: &T) -> bool
1270 x.slice_contains(self)
1273 /// Returns `true` if `needle` is a prefix of the slice.
1278 /// let v = [10, 40, 30];
1279 /// assert!(v.starts_with(&[10]));
1280 /// assert!(v.starts_with(&[10, 40]));
1281 /// assert!(!v.starts_with(&[50]));
1282 /// assert!(!v.starts_with(&[10, 50]));
1285 /// Always returns `true` if `needle` is an empty slice:
1288 /// let v = &[10, 40, 30];
1289 /// assert!(v.starts_with(&[]));
1290 /// let v: &[u8] = &[];
1291 /// assert!(v.starts_with(&[]));
1293 #[stable(feature = "rust1", since = "1.0.0")]
1294 pub fn starts_with(&self, needle: &[T]) -> bool
1297 let n = needle.len();
1298 self.len() >= n && needle == &self[..n]
1301 /// Returns `true` if `needle` is a suffix of the slice.
1306 /// let v = [10, 40, 30];
1307 /// assert!(v.ends_with(&[30]));
1308 /// assert!(v.ends_with(&[40, 30]));
1309 /// assert!(!v.ends_with(&[50]));
1310 /// assert!(!v.ends_with(&[50, 30]));
1313 /// Always returns `true` if `needle` is an empty slice:
1316 /// let v = &[10, 40, 30];
1317 /// assert!(v.ends_with(&[]));
1318 /// let v: &[u8] = &[];
1319 /// assert!(v.ends_with(&[]));
1321 #[stable(feature = "rust1", since = "1.0.0")]
1322 pub fn ends_with(&self, needle: &[T]) -> bool
1325 let (m, n) = (self.len(), needle.len());
1326 m >= n && needle == &self[m-n..]
1329 /// Binary searches this sorted slice for a given element.
1331 /// If the value is found then [`Result::Ok`] is returned, containing the
1332 /// index of the matching element. If there are multiple matches, then any
1333 /// one of the matches could be returned. If the value is not found then
1334 /// [`Result::Err`] is returned, containing the index where a matching
1335 /// element could be inserted while maintaining sorted order.
1339 /// Looks up a series of four elements. The first is found, with a
1340 /// uniquely determined position; the second and third are not
1341 /// found; the fourth could match any position in `[1, 4]`.
1344 /// let s = [0, 1, 1, 1, 1, 2, 3, 5, 8, 13, 21, 34, 55];
1346 /// assert_eq!(s.binary_search(&13), Ok(9));
1347 /// assert_eq!(s.binary_search(&4), Err(7));
1348 /// assert_eq!(s.binary_search(&100), Err(13));
1349 /// let r = s.binary_search(&1);
1350 /// assert!(match r { Ok(1..=4) => true, _ => false, });
1352 #[stable(feature = "rust1", since = "1.0.0")]
1353 pub fn binary_search(&self, x: &T) -> Result<usize, usize>
1356 self.binary_search_by(|p| p.cmp(x))
1359 /// Binary searches this sorted slice with a comparator function.
1361 /// The comparator function should implement an order consistent
1362 /// with the sort order of the underlying slice, returning an
1363 /// order code that indicates whether its argument is `Less`,
1364 /// `Equal` or `Greater` the desired target.
1366 /// If the value is found then [`Result::Ok`] is returned, containing the
1367 /// index of the matching element. If there are multiple matches, then any
1368 /// one of the matches could be returned. If the value is not found then
1369 /// [`Result::Err`] is returned, containing the index where a matching
1370 /// element could be inserted while maintaining sorted order.
1374 /// Looks up a series of four elements. The first is found, with a
1375 /// uniquely determined position; the second and third are not
1376 /// found; the fourth could match any position in `[1, 4]`.
1379 /// let s = [0, 1, 1, 1, 1, 2, 3, 5, 8, 13, 21, 34, 55];
1382 /// assert_eq!(s.binary_search_by(|probe| probe.cmp(&seek)), Ok(9));
1384 /// assert_eq!(s.binary_search_by(|probe| probe.cmp(&seek)), Err(7));
1386 /// assert_eq!(s.binary_search_by(|probe| probe.cmp(&seek)), Err(13));
1388 /// let r = s.binary_search_by(|probe| probe.cmp(&seek));
1389 /// assert!(match r { Ok(1..=4) => true, _ => false, });
1391 #[stable(feature = "rust1", since = "1.0.0")]
1393 pub fn binary_search_by<'a, F>(&'a self, mut f: F) -> Result<usize, usize>
1394 where F: FnMut(&'a T) -> Ordering
1397 let mut size = s.len();
1401 let mut base = 0usize;
1403 let half = size / 2;
1404 let mid = base + half;
1405 // mid is always in [0, size), that means mid is >= 0 and < size.
1406 // mid >= 0: by definition
1407 // mid < size: mid = size / 2 + size / 4 + size / 8 ...
1408 let cmp = f(unsafe { s.get_unchecked(mid) });
1409 base = if cmp == Greater { base } else { mid };
1412 // base is always in [0, size) because base <= mid.
1413 let cmp = f(unsafe { s.get_unchecked(base) });
1414 if cmp == Equal { Ok(base) } else { Err(base + (cmp == Less) as usize) }
1418 /// Binary searches this sorted slice with a key extraction function.
1420 /// Assumes that the slice is sorted by the key, for instance with
1421 /// [`sort_by_key`] using the same key extraction function.
1423 /// If the value is found then [`Result::Ok`] is returned, containing the
1424 /// index of the matching element. If there are multiple matches, then any
1425 /// one of the matches could be returned. If the value is not found then
1426 /// [`Result::Err`] is returned, containing the index where a matching
1427 /// element could be inserted while maintaining sorted order.
1429 /// [`sort_by_key`]: #method.sort_by_key
1433 /// Looks up a series of four elements in a slice of pairs sorted by
1434 /// their second elements. The first is found, with a uniquely
1435 /// determined position; the second and third are not found; the
1436 /// fourth could match any position in `[1, 4]`.
1439 /// let s = [(0, 0), (2, 1), (4, 1), (5, 1), (3, 1),
1440 /// (1, 2), (2, 3), (4, 5), (5, 8), (3, 13),
1441 /// (1, 21), (2, 34), (4, 55)];
1443 /// assert_eq!(s.binary_search_by_key(&13, |&(a,b)| b), Ok(9));
1444 /// assert_eq!(s.binary_search_by_key(&4, |&(a,b)| b), Err(7));
1445 /// assert_eq!(s.binary_search_by_key(&100, |&(a,b)| b), Err(13));
1446 /// let r = s.binary_search_by_key(&1, |&(a,b)| b);
1447 /// assert!(match r { Ok(1..=4) => true, _ => false, });
1449 #[stable(feature = "slice_binary_search_by_key", since = "1.10.0")]
1451 pub fn binary_search_by_key<'a, B, F>(&'a self, b: &B, mut f: F) -> Result<usize, usize>
1452 where F: FnMut(&'a T) -> B,
1455 self.binary_search_by(|k| f(k).cmp(b))
1458 /// Sorts the slice, but may not preserve the order of equal elements.
1460 /// This sort is unstable (i.e., may reorder equal elements), in-place
1461 /// (i.e., does not allocate), and `O(n log n)` worst-case.
1463 /// # Current implementation
1465 /// The current algorithm is based on [pattern-defeating quicksort][pdqsort] by Orson Peters,
1466 /// which combines the fast average case of randomized quicksort with the fast worst case of
1467 /// heapsort, while achieving linear time on slices with certain patterns. It uses some
1468 /// randomization to avoid degenerate cases, but with a fixed seed to always provide
1469 /// deterministic behavior.
1471 /// It is typically faster than stable sorting, except in a few special cases, e.g., when the
1472 /// slice consists of several concatenated sorted sequences.
1477 /// let mut v = [-5, 4, 1, -3, 2];
1479 /// v.sort_unstable();
1480 /// assert!(v == [-5, -3, 1, 2, 4]);
1483 /// [pdqsort]: https://github.com/orlp/pdqsort
1484 #[stable(feature = "sort_unstable", since = "1.20.0")]
1486 pub fn sort_unstable(&mut self)
1489 sort::quicksort(self, |a, b| a.lt(b));
1492 /// Sorts the slice with a comparator function, but may not preserve the order of equal
1495 /// This sort is unstable (i.e., may reorder equal elements), in-place
1496 /// (i.e., does not allocate), and `O(n log n)` worst-case.
1498 /// The comparator function must define a total ordering for the elements in the slice. If
1499 /// the ordering is not total, the order of the elements is unspecified. An order is a
1500 /// total order if it is (for all a, b and c):
1502 /// * total and antisymmetric: exactly one of a < b, a == b or a > b is true; and
1503 /// * transitive, a < b and b < c implies a < c. The same must hold for both == and >.
1505 /// For example, while [`f64`] doesn't implement [`Ord`] because `NaN != NaN`, we can use
1506 /// `partial_cmp` as our sort function when we know the slice doesn't contain a `NaN`.
1509 /// let mut floats = [5f64, 4.0, 1.0, 3.0, 2.0];
1510 /// floats.sort_by(|a, b| a.partial_cmp(b).unwrap());
1511 /// assert_eq!(floats, [1.0, 2.0, 3.0, 4.0, 5.0]);
1514 /// # Current implementation
1516 /// The current algorithm is based on [pattern-defeating quicksort][pdqsort] by Orson Peters,
1517 /// which combines the fast average case of randomized quicksort with the fast worst case of
1518 /// heapsort, while achieving linear time on slices with certain patterns. It uses some
1519 /// randomization to avoid degenerate cases, but with a fixed seed to always provide
1520 /// deterministic behavior.
1522 /// It is typically faster than stable sorting, except in a few special cases, e.g., when the
1523 /// slice consists of several concatenated sorted sequences.
1528 /// let mut v = [5, 4, 1, 3, 2];
1529 /// v.sort_unstable_by(|a, b| a.cmp(b));
1530 /// assert!(v == [1, 2, 3, 4, 5]);
1532 /// // reverse sorting
1533 /// v.sort_unstable_by(|a, b| b.cmp(a));
1534 /// assert!(v == [5, 4, 3, 2, 1]);
1537 /// [pdqsort]: https://github.com/orlp/pdqsort
1538 #[stable(feature = "sort_unstable", since = "1.20.0")]
1540 pub fn sort_unstable_by<F>(&mut self, mut compare: F)
1541 where F: FnMut(&T, &T) -> Ordering
1543 sort::quicksort(self, |a, b| compare(a, b) == Ordering::Less);
1546 /// Sorts the slice with a key extraction function, but may not preserve the order of equal
1549 /// This sort is unstable (i.e., may reorder equal elements), in-place
1550 /// (i.e., does not allocate), and `O(m n log(m n))` worst-case, where the key function is
1553 /// # Current implementation
1555 /// The current algorithm is based on [pattern-defeating quicksort][pdqsort] by Orson Peters,
1556 /// which combines the fast average case of randomized quicksort with the fast worst case of
1557 /// heapsort, while achieving linear time on slices with certain patterns. It uses some
1558 /// randomization to avoid degenerate cases, but with a fixed seed to always provide
1559 /// deterministic behavior.
1561 /// Due to its key calling strategy, [`sort_unstable_by_key`](#method.sort_unstable_by_key)
1562 /// is likely to be slower than [`sort_by_cached_key`](#method.sort_by_cached_key) in
1563 /// cases where the key function is expensive.
1568 /// let mut v = [-5i32, 4, 1, -3, 2];
1570 /// v.sort_unstable_by_key(|k| k.abs());
1571 /// assert!(v == [1, 2, -3, 4, -5]);
1574 /// [pdqsort]: https://github.com/orlp/pdqsort
1575 #[stable(feature = "sort_unstable", since = "1.20.0")]
1577 pub fn sort_unstable_by_key<K, F>(&mut self, mut f: F)
1578 where F: FnMut(&T) -> K, K: Ord
1580 sort::quicksort(self, |a, b| f(a).lt(&f(b)));
1583 /// Reorder the slice such that the element at `index` is at its final sorted position.
1585 /// This reordering has the additional property that any value at position `i < index` will be
1586 /// less than or equal to any value at a position `j > index`. Additionally, this reordering is
1587 /// unstable (i.e. any number of equal elements may end up at position `index`), in-place
1588 /// (i.e. does not allocate), and `O(n)` worst-case. This function is also/ known as "kth
1589 /// element" in other libraries. It returns a triplet of the following values: all elements less
1590 /// than the one at the given index, the value at the given index, and all elements greater than
1591 /// the one at the given index.
1593 /// # Current implementation
1595 /// The current algorithm is based on the quickselect portion of the same quicksort algorithm
1596 /// used for [`sort_unstable`].
1598 /// [`sort_unstable`]: #method.sort_unstable
1602 /// Panics when `index >= len()`, meaning it always panics on empty slices.
1607 /// #![feature(slice_partition_at_index)]
1609 /// let mut v = [-5i32, 4, 1, -3, 2];
1611 /// // Find the median
1612 /// v.partition_at_index(2);
1614 /// // We are only guaranteed the slice will be one of the following, based on the way we sort
1615 /// // about the specified index.
1616 /// assert!(v == [-3, -5, 1, 2, 4] ||
1617 /// v == [-5, -3, 1, 2, 4] ||
1618 /// v == [-3, -5, 1, 4, 2] ||
1619 /// v == [-5, -3, 1, 4, 2]);
1621 #[unstable(feature = "slice_partition_at_index", issue = "55300")]
1623 pub fn partition_at_index(&mut self, index: usize) -> (&mut [T], &mut T, &mut [T])
1626 let mut f = |a: &T, b: &T| a.lt(b);
1627 sort::partition_at_index(self, index, &mut f)
1630 /// Reorder the slice with a comparator function such that the element at `index` is at its
1631 /// final sorted position.
1633 /// This reordering has the additional property that any value at position `i < index` will be
1634 /// less than or equal to any value at a position `j > index` using the comparator function.
1635 /// Additionally, this reordering is unstable (i.e. any number of equal elements may end up at
1636 /// position `index`), in-place (i.e. does not allocate), and `O(n)` worst-case. This function
1637 /// is also known as "kth element" in other libraries. It returns a triplet of the following
1638 /// values: all elements less than the one at the given index, the value at the given index,
1639 /// and all elements greater than the one at the given index, using the provided comparator
1642 /// # Current implementation
1644 /// The current algorithm is based on the quickselect portion of the same quicksort algorithm
1645 /// used for [`sort_unstable`].
1647 /// [`sort_unstable`]: #method.sort_unstable
1651 /// Panics when `index >= len()`, meaning it always panics on empty slices.
1656 /// #![feature(slice_partition_at_index)]
1658 /// let mut v = [-5i32, 4, 1, -3, 2];
1660 /// // Find the median as if the slice were sorted in descending order.
1661 /// v.partition_at_index_by(2, |a, b| b.cmp(a));
1663 /// // We are only guaranteed the slice will be one of the following, based on the way we sort
1664 /// // about the specified index.
1665 /// assert!(v == [2, 4, 1, -5, -3] ||
1666 /// v == [2, 4, 1, -3, -5] ||
1667 /// v == [4, 2, 1, -5, -3] ||
1668 /// v == [4, 2, 1, -3, -5]);
1670 #[unstable(feature = "slice_partition_at_index", issue = "55300")]
1672 pub fn partition_at_index_by<F>(&mut self, index: usize, mut compare: F)
1673 -> (&mut [T], &mut T, &mut [T])
1674 where F: FnMut(&T, &T) -> Ordering
1676 let mut f = |a: &T, b: &T| compare(a, b) == Less;
1677 sort::partition_at_index(self, index, &mut f)
1680 /// Reorder the slice with a key extraction function such that the element at `index` is at its
1681 /// final sorted position.
1683 /// This reordering has the additional property that any value at position `i < index` will be
1684 /// less than or equal to any value at a position `j > index` using the key extraction function.
1685 /// Additionally, this reordering is unstable (i.e. any number of equal elements may end up at
1686 /// position `index`), in-place (i.e. does not allocate), and `O(n)` worst-case. This function
1687 /// is also known as "kth element" in other libraries. It returns a triplet of the following
1688 /// values: all elements less than the one at the given index, the value at the given index, and
1689 /// all elements greater than the one at the given index, using the provided key extraction
1692 /// # Current implementation
1694 /// The current algorithm is based on the quickselect portion of the same quicksort algorithm
1695 /// used for [`sort_unstable`].
1697 /// [`sort_unstable`]: #method.sort_unstable
1701 /// Panics when `index >= len()`, meaning it always panics on empty slices.
1706 /// #![feature(slice_partition_at_index)]
1708 /// let mut v = [-5i32, 4, 1, -3, 2];
1710 /// // Return the median as if the array were sorted according to absolute value.
1711 /// v.partition_at_index_by_key(2, |a| a.abs());
1713 /// // We are only guaranteed the slice will be one of the following, based on the way we sort
1714 /// // about the specified index.
1715 /// assert!(v == [1, 2, -3, 4, -5] ||
1716 /// v == [1, 2, -3, -5, 4] ||
1717 /// v == [2, 1, -3, 4, -5] ||
1718 /// v == [2, 1, -3, -5, 4]);
1720 #[unstable(feature = "slice_partition_at_index", issue = "55300")]
1722 pub fn partition_at_index_by_key<K, F>(&mut self, index: usize, mut f: F)
1723 -> (&mut [T], &mut T, &mut [T])
1724 where F: FnMut(&T) -> K, K: Ord
1726 let mut g = |a: &T, b: &T| f(a).lt(&f(b));
1727 sort::partition_at_index(self, index, &mut g)
1730 /// Moves all consecutive repeated elements to the end of the slice according to the
1731 /// [`PartialEq`] trait implementation.
1733 /// Returns two slices. The first contains no consecutive repeated elements.
1734 /// The second contains all the duplicates in no specified order.
1736 /// If the slice is sorted, the first returned slice contains no duplicates.
1741 /// #![feature(slice_partition_dedup)]
1743 /// let mut slice = [1, 2, 2, 3, 3, 2, 1, 1];
1745 /// let (dedup, duplicates) = slice.partition_dedup();
1747 /// assert_eq!(dedup, [1, 2, 3, 2, 1]);
1748 /// assert_eq!(duplicates, [2, 3, 1]);
1750 #[unstable(feature = "slice_partition_dedup", issue = "54279")]
1752 pub fn partition_dedup(&mut self) -> (&mut [T], &mut [T])
1755 self.partition_dedup_by(|a, b| a == b)
1758 /// Moves all but the first of consecutive elements to the end of the slice satisfying
1759 /// a given equality relation.
1761 /// Returns two slices. The first contains no consecutive repeated elements.
1762 /// The second contains all the duplicates in no specified order.
1764 /// The `same_bucket` function is passed references to two elements from the slice and
1765 /// must determine if the elements compare equal. The elements are passed in opposite order
1766 /// from their order in the slice, so if `same_bucket(a, b)` returns `true`, `a` is moved
1767 /// at the end of the slice.
1769 /// If the slice is sorted, the first returned slice contains no duplicates.
1774 /// #![feature(slice_partition_dedup)]
1776 /// let mut slice = ["foo", "Foo", "BAZ", "Bar", "bar", "baz", "BAZ"];
1778 /// let (dedup, duplicates) = slice.partition_dedup_by(|a, b| a.eq_ignore_ascii_case(b));
1780 /// assert_eq!(dedup, ["foo", "BAZ", "Bar", "baz"]);
1781 /// assert_eq!(duplicates, ["bar", "Foo", "BAZ"]);
1783 #[unstable(feature = "slice_partition_dedup", issue = "54279")]
1785 pub fn partition_dedup_by<F>(&mut self, mut same_bucket: F) -> (&mut [T], &mut [T])
1786 where F: FnMut(&mut T, &mut T) -> bool
1788 // Although we have a mutable reference to `self`, we cannot make
1789 // *arbitrary* changes. The `same_bucket` calls could panic, so we
1790 // must ensure that the slice is in a valid state at all times.
1792 // The way that we handle this is by using swaps; we iterate
1793 // over all the elements, swapping as we go so that at the end
1794 // the elements we wish to keep are in the front, and those we
1795 // wish to reject are at the back. We can then split the slice.
1796 // This operation is still O(n).
1798 // Example: We start in this state, where `r` represents "next
1799 // read" and `w` represents "next_write`.
1802 // +---+---+---+---+---+---+
1803 // | 0 | 1 | 1 | 2 | 3 | 3 |
1804 // +---+---+---+---+---+---+
1807 // Comparing self[r] against self[w-1], this is not a duplicate, so
1808 // we swap self[r] and self[w] (no effect as r==w) and then increment both
1809 // r and w, leaving us with:
1812 // +---+---+---+---+---+---+
1813 // | 0 | 1 | 1 | 2 | 3 | 3 |
1814 // +---+---+---+---+---+---+
1817 // Comparing self[r] against self[w-1], this value is a duplicate,
1818 // so we increment `r` but leave everything else unchanged:
1821 // +---+---+---+---+---+---+
1822 // | 0 | 1 | 1 | 2 | 3 | 3 |
1823 // +---+---+---+---+---+---+
1826 // Comparing self[r] against self[w-1], this is not a duplicate,
1827 // so swap self[r] and self[w] and advance r and w:
1830 // +---+---+---+---+---+---+
1831 // | 0 | 1 | 2 | 1 | 3 | 3 |
1832 // +---+---+---+---+---+---+
1835 // Not a duplicate, repeat:
1838 // +---+---+---+---+---+---+
1839 // | 0 | 1 | 2 | 3 | 1 | 3 |
1840 // +---+---+---+---+---+---+
1843 // Duplicate, advance r. End of slice. Split at w.
1845 let len = self.len();
1847 return (self, &mut [])
1850 let ptr = self.as_mut_ptr();
1851 let mut next_read: usize = 1;
1852 let mut next_write: usize = 1;
1855 // Avoid bounds checks by using raw pointers.
1856 while next_read < len {
1857 let ptr_read = ptr.add(next_read);
1858 let prev_ptr_write = ptr.add(next_write - 1);
1859 if !same_bucket(&mut *ptr_read, &mut *prev_ptr_write) {
1860 if next_read != next_write {
1861 let ptr_write = prev_ptr_write.offset(1);
1862 mem::swap(&mut *ptr_read, &mut *ptr_write);
1870 self.split_at_mut(next_write)
1873 /// Moves all but the first of consecutive elements to the end of the slice that resolve
1874 /// to the same key.
1876 /// Returns two slices. The first contains no consecutive repeated elements.
1877 /// The second contains all the duplicates in no specified order.
1879 /// If the slice is sorted, the first returned slice contains no duplicates.
1884 /// #![feature(slice_partition_dedup)]
1886 /// let mut slice = [10, 20, 21, 30, 30, 20, 11, 13];
1888 /// let (dedup, duplicates) = slice.partition_dedup_by_key(|i| *i / 10);
1890 /// assert_eq!(dedup, [10, 20, 30, 20, 11]);
1891 /// assert_eq!(duplicates, [21, 30, 13]);
1893 #[unstable(feature = "slice_partition_dedup", issue = "54279")]
1895 pub fn partition_dedup_by_key<K, F>(&mut self, mut key: F) -> (&mut [T], &mut [T])
1896 where F: FnMut(&mut T) -> K,
1899 self.partition_dedup_by(|a, b| key(a) == key(b))
1902 /// Rotates the slice in-place such that the first `mid` elements of the
1903 /// slice move to the end while the last `self.len() - mid` elements move to
1904 /// the front. After calling `rotate_left`, the element previously at index
1905 /// `mid` will become the first element in the slice.
1909 /// This function will panic if `mid` is greater than the length of the
1910 /// slice. Note that `mid == self.len()` does _not_ panic and is a no-op
1915 /// Takes linear (in `self.len()`) time.
1920 /// let mut a = ['a', 'b', 'c', 'd', 'e', 'f'];
1921 /// a.rotate_left(2);
1922 /// assert_eq!(a, ['c', 'd', 'e', 'f', 'a', 'b']);
1925 /// Rotating a subslice:
1928 /// let mut a = ['a', 'b', 'c', 'd', 'e', 'f'];
1929 /// a[1..5].rotate_left(1);
1930 /// assert_eq!(a, ['a', 'c', 'd', 'e', 'b', 'f']);
1932 #[stable(feature = "slice_rotate", since = "1.26.0")]
1933 pub fn rotate_left(&mut self, mid: usize) {
1934 assert!(mid <= self.len());
1935 let k = self.len() - mid;
1938 let p = self.as_mut_ptr();
1939 rotate::ptr_rotate(mid, p.add(mid), k);
1943 /// Rotates the slice in-place such that the first `self.len() - k`
1944 /// elements of the slice move to the end while the last `k` elements move
1945 /// to the front. After calling `rotate_right`, the element previously at
1946 /// index `self.len() - k` will become the first element in the slice.
1950 /// This function will panic if `k` is greater than the length of the
1951 /// slice. Note that `k == self.len()` does _not_ panic and is a no-op
1956 /// Takes linear (in `self.len()`) time.
1961 /// let mut a = ['a', 'b', 'c', 'd', 'e', 'f'];
1962 /// a.rotate_right(2);
1963 /// assert_eq!(a, ['e', 'f', 'a', 'b', 'c', 'd']);
1966 /// Rotate a subslice:
1969 /// let mut a = ['a', 'b', 'c', 'd', 'e', 'f'];
1970 /// a[1..5].rotate_right(1);
1971 /// assert_eq!(a, ['a', 'e', 'b', 'c', 'd', 'f']);
1973 #[stable(feature = "slice_rotate", since = "1.26.0")]
1974 pub fn rotate_right(&mut self, k: usize) {
1975 assert!(k <= self.len());
1976 let mid = self.len() - k;
1979 let p = self.as_mut_ptr();
1980 rotate::ptr_rotate(mid, p.add(mid), k);
1984 /// Copies the elements from `src` into `self`.
1986 /// The length of `src` must be the same as `self`.
1988 /// If `src` implements `Copy`, it can be more performant to use
1989 /// [`copy_from_slice`].
1993 /// This function will panic if the two slices have different lengths.
1997 /// Cloning two elements from a slice into another:
2000 /// let src = [1, 2, 3, 4];
2001 /// let mut dst = [0, 0];
2003 /// // Because the slices have to be the same length,
2004 /// // we slice the source slice from four elements
2005 /// // to two. It will panic if we don't do this.
2006 /// dst.clone_from_slice(&src[2..]);
2008 /// assert_eq!(src, [1, 2, 3, 4]);
2009 /// assert_eq!(dst, [3, 4]);
2012 /// Rust enforces that there can only be one mutable reference with no
2013 /// immutable references to a particular piece of data in a particular
2014 /// scope. Because of this, attempting to use `clone_from_slice` on a
2015 /// single slice will result in a compile failure:
2018 /// let mut slice = [1, 2, 3, 4, 5];
2020 /// slice[..2].clone_from_slice(&slice[3..]); // compile fail!
2023 /// To work around this, we can use [`split_at_mut`] to create two distinct
2024 /// sub-slices from a slice:
2027 /// let mut slice = [1, 2, 3, 4, 5];
2030 /// let (left, right) = slice.split_at_mut(2);
2031 /// left.clone_from_slice(&right[1..]);
2034 /// assert_eq!(slice, [4, 5, 3, 4, 5]);
2037 /// [`copy_from_slice`]: #method.copy_from_slice
2038 /// [`split_at_mut`]: #method.split_at_mut
2039 #[stable(feature = "clone_from_slice", since = "1.7.0")]
2040 pub fn clone_from_slice(&mut self, src: &[T]) where T: Clone {
2041 assert!(self.len() == src.len(),
2042 "destination and source slices have different lengths");
2043 // NOTE: We need to explicitly slice them to the same length
2044 // for bounds checking to be elided, and the optimizer will
2045 // generate memcpy for simple cases (for example T = u8).
2046 let len = self.len();
2047 let src = &src[..len];
2049 self[i].clone_from(&src[i]);
2054 /// Copies all elements from `src` into `self`, using a memcpy.
2056 /// The length of `src` must be the same as `self`.
2058 /// If `src` does not implement `Copy`, use [`clone_from_slice`].
2062 /// This function will panic if the two slices have different lengths.
2066 /// Copying two elements from a slice into another:
2069 /// let src = [1, 2, 3, 4];
2070 /// let mut dst = [0, 0];
2072 /// // Because the slices have to be the same length,
2073 /// // we slice the source slice from four elements
2074 /// // to two. It will panic if we don't do this.
2075 /// dst.copy_from_slice(&src[2..]);
2077 /// assert_eq!(src, [1, 2, 3, 4]);
2078 /// assert_eq!(dst, [3, 4]);
2081 /// Rust enforces that there can only be one mutable reference with no
2082 /// immutable references to a particular piece of data in a particular
2083 /// scope. Because of this, attempting to use `copy_from_slice` on a
2084 /// single slice will result in a compile failure:
2087 /// let mut slice = [1, 2, 3, 4, 5];
2089 /// slice[..2].copy_from_slice(&slice[3..]); // compile fail!
2092 /// To work around this, we can use [`split_at_mut`] to create two distinct
2093 /// sub-slices from a slice:
2096 /// let mut slice = [1, 2, 3, 4, 5];
2099 /// let (left, right) = slice.split_at_mut(2);
2100 /// left.copy_from_slice(&right[1..]);
2103 /// assert_eq!(slice, [4, 5, 3, 4, 5]);
2106 /// [`clone_from_slice`]: #method.clone_from_slice
2107 /// [`split_at_mut`]: #method.split_at_mut
2108 #[stable(feature = "copy_from_slice", since = "1.9.0")]
2109 pub fn copy_from_slice(&mut self, src: &[T]) where T: Copy {
2110 assert_eq!(self.len(), src.len(),
2111 "destination and source slices have different lengths");
2113 ptr::copy_nonoverlapping(
2114 src.as_ptr(), self.as_mut_ptr(), self.len());
2118 /// Copies elements from one part of the slice to another part of itself,
2119 /// using a memmove.
2121 /// `src` is the range within `self` to copy from. `dest` is the starting
2122 /// index of the range within `self` to copy to, which will have the same
2123 /// length as `src`. The two ranges may overlap. The ends of the two ranges
2124 /// must be less than or equal to `self.len()`.
2128 /// This function will panic if either range exceeds the end of the slice,
2129 /// or if the end of `src` is before the start.
2133 /// Copying four bytes within a slice:
2136 /// let mut bytes = *b"Hello, World!";
2138 /// bytes.copy_within(1..5, 8);
2140 /// assert_eq!(&bytes, b"Hello, Wello!");
2142 #[stable(feature = "copy_within", since = "1.37.0")]
2143 pub fn copy_within<R: ops::RangeBounds<usize>>(&mut self, src: R, dest: usize)
2147 let src_start = match src.start_bound() {
2148 ops::Bound::Included(&n) => n,
2149 ops::Bound::Excluded(&n) => n
2151 .unwrap_or_else(|| slice_index_overflow_fail()),
2152 ops::Bound::Unbounded => 0,
2154 let src_end = match src.end_bound() {
2155 ops::Bound::Included(&n) => n
2157 .unwrap_or_else(|| slice_index_overflow_fail()),
2158 ops::Bound::Excluded(&n) => n,
2159 ops::Bound::Unbounded => self.len(),
2161 assert!(src_start <= src_end, "src end is before src start");
2162 assert!(src_end <= self.len(), "src is out of bounds");
2163 let count = src_end - src_start;
2164 assert!(dest <= self.len() - count, "dest is out of bounds");
2167 self.as_ptr().add(src_start),
2168 self.as_mut_ptr().add(dest),
2174 /// Swaps all elements in `self` with those in `other`.
2176 /// The length of `other` must be the same as `self`.
2180 /// This function will panic if the two slices have different lengths.
2184 /// Swapping two elements across slices:
2187 /// let mut slice1 = [0, 0];
2188 /// let mut slice2 = [1, 2, 3, 4];
2190 /// slice1.swap_with_slice(&mut slice2[2..]);
2192 /// assert_eq!(slice1, [3, 4]);
2193 /// assert_eq!(slice2, [1, 2, 0, 0]);
2196 /// Rust enforces that there can only be one mutable reference to a
2197 /// particular piece of data in a particular scope. Because of this,
2198 /// attempting to use `swap_with_slice` on a single slice will result in
2199 /// a compile failure:
2202 /// let mut slice = [1, 2, 3, 4, 5];
2203 /// slice[..2].swap_with_slice(&mut slice[3..]); // compile fail!
2206 /// To work around this, we can use [`split_at_mut`] to create two distinct
2207 /// mutable sub-slices from a slice:
2210 /// let mut slice = [1, 2, 3, 4, 5];
2213 /// let (left, right) = slice.split_at_mut(2);
2214 /// left.swap_with_slice(&mut right[1..]);
2217 /// assert_eq!(slice, [4, 5, 3, 1, 2]);
2220 /// [`split_at_mut`]: #method.split_at_mut
2221 #[stable(feature = "swap_with_slice", since = "1.27.0")]
2222 pub fn swap_with_slice(&mut self, other: &mut [T]) {
2223 assert!(self.len() == other.len(),
2224 "destination and source slices have different lengths");
2226 ptr::swap_nonoverlapping(
2227 self.as_mut_ptr(), other.as_mut_ptr(), self.len());
2231 /// Function to calculate lengths of the middle and trailing slice for `align_to{,_mut}`.
2232 fn align_to_offsets<U>(&self) -> (usize, usize) {
2233 // What we gonna do about `rest` is figure out what multiple of `U`s we can put in a
2234 // lowest number of `T`s. And how many `T`s we need for each such "multiple".
2236 // Consider for example T=u8 U=u16. Then we can put 1 U in 2 Ts. Simple. Now, consider
2237 // for example a case where size_of::<T> = 16, size_of::<U> = 24. We can put 2 Us in
2238 // place of every 3 Ts in the `rest` slice. A bit more complicated.
2240 // Formula to calculate this is:
2242 // Us = lcm(size_of::<T>, size_of::<U>) / size_of::<U>
2243 // Ts = lcm(size_of::<T>, size_of::<U>) / size_of::<T>
2245 // Expanded and simplified:
2247 // Us = size_of::<T> / gcd(size_of::<T>, size_of::<U>)
2248 // Ts = size_of::<U> / gcd(size_of::<T>, size_of::<U>)
2250 // Luckily since all this is constant-evaluated... performance here matters not!
2252 fn gcd(a: usize, b: usize) -> usize {
2253 use crate::intrinsics;
2254 // iterative stein’s algorithm
2255 // We should still make this `const fn` (and revert to recursive algorithm if we do)
2256 // because relying on llvm to consteval all this is… well, it makes me uncomfortable.
2257 let (ctz_a, mut ctz_b) = unsafe {
2258 if a == 0 { return b; }
2259 if b == 0 { return a; }
2260 (intrinsics::cttz_nonzero(a), intrinsics::cttz_nonzero(b))
2262 let k = ctz_a.min(ctz_b);
2263 let mut a = a >> ctz_a;
2266 // remove all factors of 2 from b
2269 mem::swap(&mut a, &mut b);
2276 ctz_b = intrinsics::cttz_nonzero(b);
2281 let gcd: usize = gcd(mem::size_of::<T>(), mem::size_of::<U>());
2282 let ts: usize = mem::size_of::<U>() / gcd;
2283 let us: usize = mem::size_of::<T>() / gcd;
2285 // Armed with this knowledge, we can find how many `U`s we can fit!
2286 let us_len = self.len() / ts * us;
2287 // And how many `T`s will be in the trailing slice!
2288 let ts_len = self.len() % ts;
2292 /// Transmute the slice to a slice of another type, ensuring alignment of the types is
2295 /// This method splits the slice into three distinct slices: prefix, correctly aligned middle
2296 /// slice of a new type, and the suffix slice. The method does a best effort to make the
2297 /// middle slice the greatest length possible for a given type and input slice, but only
2298 /// your algorithm's performance should depend on that, not its correctness.
2300 /// This method has no purpose when either input element `T` or output element `U` are
2301 /// zero-sized and will return the original slice without splitting anything.
2305 /// This method is essentially a `transmute` with respect to the elements in the returned
2306 /// middle slice, so all the usual caveats pertaining to `transmute::<T, U>` also apply here.
2314 /// let bytes: [u8; 7] = [1, 2, 3, 4, 5, 6, 7];
2315 /// let (prefix, shorts, suffix) = bytes.align_to::<u16>();
2316 /// // less_efficient_algorithm_for_bytes(prefix);
2317 /// // more_efficient_algorithm_for_aligned_shorts(shorts);
2318 /// // less_efficient_algorithm_for_bytes(suffix);
2321 #[stable(feature = "slice_align_to", since = "1.30.0")]
2322 pub unsafe fn align_to<U>(&self) -> (&[T], &[U], &[T]) {
2323 // Note that most of this function will be constant-evaluated,
2324 if mem::size_of::<U>() == 0 || mem::size_of::<T>() == 0 {
2325 // handle ZSTs specially, which is – don't handle them at all.
2326 return (self, &[], &[]);
2329 // First, find at what point do we split between the first and 2nd slice. Easy with
2330 // ptr.align_offset.
2331 let ptr = self.as_ptr();
2332 let offset = crate::ptr::align_offset(ptr, mem::align_of::<U>());
2333 if offset > self.len() {
2336 let (left, rest) = self.split_at(offset);
2337 // now `rest` is definitely aligned, so `from_raw_parts_mut` below is okay
2338 let (us_len, ts_len) = rest.align_to_offsets::<U>();
2340 from_raw_parts(rest.as_ptr() as *const U, us_len),
2341 from_raw_parts(rest.as_ptr().add(rest.len() - ts_len), ts_len))
2345 /// Transmute the slice to a slice of another type, ensuring alignment of the types is
2348 /// This method splits the slice into three distinct slices: prefix, correctly aligned middle
2349 /// slice of a new type, and the suffix slice. The method does a best effort to make the
2350 /// middle slice the greatest length possible for a given type and input slice, but only
2351 /// your algorithm's performance should depend on that, not its correctness.
2353 /// This method has no purpose when either input element `T` or output element `U` are
2354 /// zero-sized and will return the original slice without splitting anything.
2358 /// This method is essentially a `transmute` with respect to the elements in the returned
2359 /// middle slice, so all the usual caveats pertaining to `transmute::<T, U>` also apply here.
2367 /// let mut bytes: [u8; 7] = [1, 2, 3, 4, 5, 6, 7];
2368 /// let (prefix, shorts, suffix) = bytes.align_to_mut::<u16>();
2369 /// // less_efficient_algorithm_for_bytes(prefix);
2370 /// // more_efficient_algorithm_for_aligned_shorts(shorts);
2371 /// // less_efficient_algorithm_for_bytes(suffix);
2374 #[stable(feature = "slice_align_to", since = "1.30.0")]
2375 pub unsafe fn align_to_mut<U>(&mut self) -> (&mut [T], &mut [U], &mut [T]) {
2376 // Note that most of this function will be constant-evaluated,
2377 if mem::size_of::<U>() == 0 || mem::size_of::<T>() == 0 {
2378 // handle ZSTs specially, which is – don't handle them at all.
2379 return (self, &mut [], &mut []);
2382 // First, find at what point do we split between the first and 2nd slice. Easy with
2383 // ptr.align_offset.
2384 let ptr = self.as_ptr();
2385 let offset = crate::ptr::align_offset(ptr, mem::align_of::<U>());
2386 if offset > self.len() {
2387 (self, &mut [], &mut [])
2389 let (left, rest) = self.split_at_mut(offset);
2390 // now `rest` is definitely aligned, so `from_raw_parts_mut` below is okay
2391 let (us_len, ts_len) = rest.align_to_offsets::<U>();
2392 let mut_ptr = rest.as_mut_ptr();
2394 from_raw_parts_mut(mut_ptr as *mut U, us_len),
2395 from_raw_parts_mut(mut_ptr.add(rest.len() - ts_len), ts_len))
2399 /// Checks if the elements of this slice are sorted.
2401 /// That is, for each element `a` and its following element `b`, `a <= b` must hold. If the
2402 /// slice yields exactly zero or one element, `true` is returned.
2404 /// Note that if `Self::Item` is only `PartialOrd`, but not `Ord`, the above definition
2405 /// implies that this function returns `false` if any two consecutive items are not
2411 /// #![feature(is_sorted)]
2412 /// let empty: [i32; 0] = [];
2414 /// assert!([1, 2, 2, 9].is_sorted());
2415 /// assert!(![1, 3, 2, 4].is_sorted());
2416 /// assert!([0].is_sorted());
2417 /// assert!(empty.is_sorted());
2418 /// assert!(![0.0, 1.0, std::f32::NAN].is_sorted());
2421 #[unstable(feature = "is_sorted", reason = "new API", issue = "53485")]
2422 pub fn is_sorted(&self) -> bool
2426 self.is_sorted_by(|a, b| a.partial_cmp(b))
2429 /// Checks if the elements of this slice are sorted using the given comparator function.
2431 /// Instead of using `PartialOrd::partial_cmp`, this function uses the given `compare`
2432 /// function to determine the ordering of two elements. Apart from that, it's equivalent to
2433 /// [`is_sorted`]; see its documentation for more information.
2435 /// [`is_sorted`]: #method.is_sorted
2436 #[unstable(feature = "is_sorted", reason = "new API", issue = "53485")]
2437 pub fn is_sorted_by<F>(&self, mut compare: F) -> bool
2439 F: FnMut(&T, &T) -> Option<Ordering>
2441 self.iter().is_sorted_by(|a, b| compare(*a, *b))
2444 /// Checks if the elements of this slice are sorted using the given key extraction function.
2446 /// Instead of comparing the slice's elements directly, this function compares the keys of the
2447 /// elements, as determined by `f`. Apart from that, it's equivalent to [`is_sorted`]; see its
2448 /// documentation for more information.
2450 /// [`is_sorted`]: #method.is_sorted
2455 /// #![feature(is_sorted)]
2457 /// assert!(["c", "bb", "aaa"].is_sorted_by_key(|s| s.len()));
2458 /// assert!(![-2i32, -1, 0, 3].is_sorted_by_key(|n| n.abs()));
2461 #[unstable(feature = "is_sorted", reason = "new API", issue = "53485")]
2462 pub fn is_sorted_by_key<F, K>(&self, mut f: F) -> bool
2467 self.is_sorted_by(|a, b| f(a).partial_cmp(&f(b)))
2471 #[lang = "slice_u8"]
2474 /// Checks if all bytes in this slice are within the ASCII range.
2475 #[stable(feature = "ascii_methods_on_intrinsics", since = "1.23.0")]
2477 pub fn is_ascii(&self) -> bool {
2478 self.iter().all(|b| b.is_ascii())
2481 /// Checks that two slices are an ASCII case-insensitive match.
2483 /// Same as `to_ascii_lowercase(a) == to_ascii_lowercase(b)`,
2484 /// but without allocating and copying temporaries.
2485 #[stable(feature = "ascii_methods_on_intrinsics", since = "1.23.0")]
2487 pub fn eq_ignore_ascii_case(&self, other: &[u8]) -> bool {
2488 self.len() == other.len() &&
2489 self.iter().zip(other).all(|(a, b)| {
2490 a.eq_ignore_ascii_case(b)
2494 /// Converts this slice to its ASCII upper case equivalent in-place.
2496 /// ASCII letters 'a' to 'z' are mapped to 'A' to 'Z',
2497 /// but non-ASCII letters are unchanged.
2499 /// To return a new uppercased value without modifying the existing one, use
2500 /// [`to_ascii_uppercase`].
2502 /// [`to_ascii_uppercase`]: #method.to_ascii_uppercase
2503 #[stable(feature = "ascii_methods_on_intrinsics", since = "1.23.0")]
2505 pub fn make_ascii_uppercase(&mut self) {
2507 byte.make_ascii_uppercase();
2511 /// Converts this slice to its ASCII lower case equivalent in-place.
2513 /// ASCII letters 'A' to 'Z' are mapped to 'a' to 'z',
2514 /// but non-ASCII letters are unchanged.
2516 /// To return a new lowercased value without modifying the existing one, use
2517 /// [`to_ascii_lowercase`].
2519 /// [`to_ascii_lowercase`]: #method.to_ascii_lowercase
2520 #[stable(feature = "ascii_methods_on_intrinsics", since = "1.23.0")]
2522 pub fn make_ascii_lowercase(&mut self) {
2524 byte.make_ascii_lowercase();
2530 #[stable(feature = "rust1", since = "1.0.0")]
2531 impl<T, I> ops::Index<I> for [T]
2532 where I: SliceIndex<[T]>
2534 type Output = I::Output;
2537 fn index(&self, index: I) -> &I::Output {
2542 #[stable(feature = "rust1", since = "1.0.0")]
2543 impl<T, I> ops::IndexMut<I> for [T]
2544 where I: SliceIndex<[T]>
2547 fn index_mut(&mut self, index: I) -> &mut I::Output {
2548 index.index_mut(self)
2554 fn slice_index_len_fail(index: usize, len: usize) -> ! {
2555 panic!("index {} out of range for slice of length {}", index, len);
2560 fn slice_index_order_fail(index: usize, end: usize) -> ! {
2561 panic!("slice index starts at {} but ends at {}", index, end);
2566 fn slice_index_overflow_fail() -> ! {
2567 panic!("attempted to index slice up to maximum usize");
2570 mod private_slice_index {
2572 #[stable(feature = "slice_get_slice", since = "1.28.0")]
2575 #[stable(feature = "slice_get_slice", since = "1.28.0")]
2576 impl Sealed for usize {}
2577 #[stable(feature = "slice_get_slice", since = "1.28.0")]
2578 impl Sealed for ops::Range<usize> {}
2579 #[stable(feature = "slice_get_slice", since = "1.28.0")]
2580 impl Sealed for ops::RangeTo<usize> {}
2581 #[stable(feature = "slice_get_slice", since = "1.28.0")]
2582 impl Sealed for ops::RangeFrom<usize> {}
2583 #[stable(feature = "slice_get_slice", since = "1.28.0")]
2584 impl Sealed for ops::RangeFull {}
2585 #[stable(feature = "slice_get_slice", since = "1.28.0")]
2586 impl Sealed for ops::RangeInclusive<usize> {}
2587 #[stable(feature = "slice_get_slice", since = "1.28.0")]
2588 impl Sealed for ops::RangeToInclusive<usize> {}
2591 /// A helper trait used for indexing operations.
2592 #[stable(feature = "slice_get_slice", since = "1.28.0")]
2593 #[rustc_on_unimplemented(
2596 label = "string indices are ranges of `usize`",
2599 all(any(T = "str", T = "&str", T = "std::string::String"), _Self="{integer}"),
2600 note="you can use `.chars().nth()` or `.bytes().nth()`
2601 see chapter in The Book <https://doc.rust-lang.org/book/ch08-02-strings.html#indexing-into-strings>"
2603 message = "the type `{T}` cannot be indexed by `{Self}`",
2604 label = "slice indices are of type `usize` or ranges of `usize`",
2606 pub trait SliceIndex<T: ?Sized>: private_slice_index::Sealed {
2607 /// The output type returned by methods.
2608 #[stable(feature = "slice_get_slice", since = "1.28.0")]
2609 type Output: ?Sized;
2611 /// Returns a shared reference to the output at this location, if in
2613 #[unstable(feature = "slice_index_methods", issue = "0")]
2614 fn get(self, slice: &T) -> Option<&Self::Output>;
2616 /// Returns a mutable reference to the output at this location, if in
2618 #[unstable(feature = "slice_index_methods", issue = "0")]
2619 fn get_mut(self, slice: &mut T) -> Option<&mut Self::Output>;
2621 /// Returns a shared reference to the output at this location, without
2622 /// performing any bounds checking.
2623 #[unstable(feature = "slice_index_methods", issue = "0")]
2624 unsafe fn get_unchecked(self, slice: &T) -> &Self::Output;
2626 /// Returns a mutable reference to the output at this location, without
2627 /// performing any bounds checking.
2628 #[unstable(feature = "slice_index_methods", issue = "0")]
2629 unsafe fn get_unchecked_mut(self, slice: &mut T) -> &mut Self::Output;
2631 /// Returns a shared reference to the output at this location, panicking
2632 /// if out of bounds.
2633 #[unstable(feature = "slice_index_methods", issue = "0")]
2634 fn index(self, slice: &T) -> &Self::Output;
2636 /// Returns a mutable reference to the output at this location, panicking
2637 /// if out of bounds.
2638 #[unstable(feature = "slice_index_methods", issue = "0")]
2639 fn index_mut(self, slice: &mut T) -> &mut Self::Output;
2642 #[stable(feature = "slice_get_slice_impls", since = "1.15.0")]
2643 impl<T> SliceIndex<[T]> for usize {
2647 fn get(self, slice: &[T]) -> Option<&T> {
2648 if self < slice.len() {
2650 Some(self.get_unchecked(slice))
2658 fn get_mut(self, slice: &mut [T]) -> Option<&mut T> {
2659 if self < slice.len() {
2661 Some(self.get_unchecked_mut(slice))
2669 unsafe fn get_unchecked(self, slice: &[T]) -> &T {
2670 &*slice.as_ptr().add(self)
2674 unsafe fn get_unchecked_mut(self, slice: &mut [T]) -> &mut T {
2675 &mut *slice.as_mut_ptr().add(self)
2679 fn index(self, slice: &[T]) -> &T {
2680 // N.B., use intrinsic indexing
2685 fn index_mut(self, slice: &mut [T]) -> &mut T {
2686 // N.B., use intrinsic indexing
2691 #[stable(feature = "slice_get_slice_impls", since = "1.15.0")]
2692 impl<T> SliceIndex<[T]> for ops::Range<usize> {
2696 fn get(self, slice: &[T]) -> Option<&[T]> {
2697 if self.start > self.end || self.end > slice.len() {
2701 Some(self.get_unchecked(slice))
2707 fn get_mut(self, slice: &mut [T]) -> Option<&mut [T]> {
2708 if self.start > self.end || self.end > slice.len() {
2712 Some(self.get_unchecked_mut(slice))
2718 unsafe fn get_unchecked(self, slice: &[T]) -> &[T] {
2719 from_raw_parts(slice.as_ptr().add(self.start), self.end - self.start)
2723 unsafe fn get_unchecked_mut(self, slice: &mut [T]) -> &mut [T] {
2724 from_raw_parts_mut(slice.as_mut_ptr().add(self.start), self.end - self.start)
2728 fn index(self, slice: &[T]) -> &[T] {
2729 if self.start > self.end {
2730 slice_index_order_fail(self.start, self.end);
2731 } else if self.end > slice.len() {
2732 slice_index_len_fail(self.end, slice.len());
2735 self.get_unchecked(slice)
2740 fn index_mut(self, slice: &mut [T]) -> &mut [T] {
2741 if self.start > self.end {
2742 slice_index_order_fail(self.start, self.end);
2743 } else if self.end > slice.len() {
2744 slice_index_len_fail(self.end, slice.len());
2747 self.get_unchecked_mut(slice)
2752 #[stable(feature = "slice_get_slice_impls", since = "1.15.0")]
2753 impl<T> SliceIndex<[T]> for ops::RangeTo<usize> {
2757 fn get(self, slice: &[T]) -> Option<&[T]> {
2758 (0..self.end).get(slice)
2762 fn get_mut(self, slice: &mut [T]) -> Option<&mut [T]> {
2763 (0..self.end).get_mut(slice)
2767 unsafe fn get_unchecked(self, slice: &[T]) -> &[T] {
2768 (0..self.end).get_unchecked(slice)
2772 unsafe fn get_unchecked_mut(self, slice: &mut [T]) -> &mut [T] {
2773 (0..self.end).get_unchecked_mut(slice)
2777 fn index(self, slice: &[T]) -> &[T] {
2778 (0..self.end).index(slice)
2782 fn index_mut(self, slice: &mut [T]) -> &mut [T] {
2783 (0..self.end).index_mut(slice)
2787 #[stable(feature = "slice_get_slice_impls", since = "1.15.0")]
2788 impl<T> SliceIndex<[T]> for ops::RangeFrom<usize> {
2792 fn get(self, slice: &[T]) -> Option<&[T]> {
2793 (self.start..slice.len()).get(slice)
2797 fn get_mut(self, slice: &mut [T]) -> Option<&mut [T]> {
2798 (self.start..slice.len()).get_mut(slice)
2802 unsafe fn get_unchecked(self, slice: &[T]) -> &[T] {
2803 (self.start..slice.len()).get_unchecked(slice)
2807 unsafe fn get_unchecked_mut(self, slice: &mut [T]) -> &mut [T] {
2808 (self.start..slice.len()).get_unchecked_mut(slice)
2812 fn index(self, slice: &[T]) -> &[T] {
2813 (self.start..slice.len()).index(slice)
2817 fn index_mut(self, slice: &mut [T]) -> &mut [T] {
2818 (self.start..slice.len()).index_mut(slice)
2822 #[stable(feature = "slice_get_slice_impls", since = "1.15.0")]
2823 impl<T> SliceIndex<[T]> for ops::RangeFull {
2827 fn get(self, slice: &[T]) -> Option<&[T]> {
2832 fn get_mut(self, slice: &mut [T]) -> Option<&mut [T]> {
2837 unsafe fn get_unchecked(self, slice: &[T]) -> &[T] {
2842 unsafe fn get_unchecked_mut(self, slice: &mut [T]) -> &mut [T] {
2847 fn index(self, slice: &[T]) -> &[T] {
2852 fn index_mut(self, slice: &mut [T]) -> &mut [T] {
2858 #[stable(feature = "inclusive_range", since = "1.26.0")]
2859 impl<T> SliceIndex<[T]> for ops::RangeInclusive<usize> {
2863 fn get(self, slice: &[T]) -> Option<&[T]> {
2864 if *self.end() == usize::max_value() { None }
2865 else { (*self.start()..self.end() + 1).get(slice) }
2869 fn get_mut(self, slice: &mut [T]) -> Option<&mut [T]> {
2870 if *self.end() == usize::max_value() { None }
2871 else { (*self.start()..self.end() + 1).get_mut(slice) }
2875 unsafe fn get_unchecked(self, slice: &[T]) -> &[T] {
2876 (*self.start()..self.end() + 1).get_unchecked(slice)
2880 unsafe fn get_unchecked_mut(self, slice: &mut [T]) -> &mut [T] {
2881 (*self.start()..self.end() + 1).get_unchecked_mut(slice)
2885 fn index(self, slice: &[T]) -> &[T] {
2886 if *self.end() == usize::max_value() { slice_index_overflow_fail(); }
2887 (*self.start()..self.end() + 1).index(slice)
2891 fn index_mut(self, slice: &mut [T]) -> &mut [T] {
2892 if *self.end() == usize::max_value() { slice_index_overflow_fail(); }
2893 (*self.start()..self.end() + 1).index_mut(slice)
2897 #[stable(feature = "inclusive_range", since = "1.26.0")]
2898 impl<T> SliceIndex<[T]> for ops::RangeToInclusive<usize> {
2902 fn get(self, slice: &[T]) -> Option<&[T]> {
2903 (0..=self.end).get(slice)
2907 fn get_mut(self, slice: &mut [T]) -> Option<&mut [T]> {
2908 (0..=self.end).get_mut(slice)
2912 unsafe fn get_unchecked(self, slice: &[T]) -> &[T] {
2913 (0..=self.end).get_unchecked(slice)
2917 unsafe fn get_unchecked_mut(self, slice: &mut [T]) -> &mut [T] {
2918 (0..=self.end).get_unchecked_mut(slice)
2922 fn index(self, slice: &[T]) -> &[T] {
2923 (0..=self.end).index(slice)
2927 fn index_mut(self, slice: &mut [T]) -> &mut [T] {
2928 (0..=self.end).index_mut(slice)
2932 ////////////////////////////////////////////////////////////////////////////////
2934 ////////////////////////////////////////////////////////////////////////////////
2936 #[stable(feature = "rust1", since = "1.0.0")]
2937 impl<T> Default for &[T] {
2938 /// Creates an empty slice.
2939 fn default() -> Self { &[] }
2942 #[stable(feature = "mut_slice_default", since = "1.5.0")]
2943 impl<T> Default for &mut [T] {
2944 /// Creates a mutable empty slice.
2945 fn default() -> Self { &mut [] }
2952 #[stable(feature = "rust1", since = "1.0.0")]
2953 impl<'a, T> IntoIterator for &'a [T] {
2955 type IntoIter = Iter<'a, T>;
2957 fn into_iter(self) -> Iter<'a, T> {
2962 #[stable(feature = "rust1", since = "1.0.0")]
2963 impl<'a, T> IntoIterator for &'a mut [T] {
2964 type Item = &'a mut T;
2965 type IntoIter = IterMut<'a, T>;
2967 fn into_iter(self) -> IterMut<'a, T> {
2972 // Macro helper functions
2974 fn size_from_ptr<T>(_: *const T) -> usize {
2978 // Inlining is_empty and len makes a huge performance difference
2979 macro_rules! is_empty {
2980 // The way we encode the length of a ZST iterator, this works both for ZST
2982 ($self: ident) => {$self.ptr == $self.end}
2984 // To get rid of some bounds checks (see `position`), we compute the length in a somewhat
2985 // unexpected way. (Tested by `codegen/slice-position-bounds-check`.)
2987 ($self: ident) => {{
2988 #![allow(unused_unsafe)] // we're sometimes used within an unsafe block
2990 let start = $self.ptr;
2991 let size = size_from_ptr(start);
2993 // This _cannot_ use `unchecked_sub` because we depend on wrapping
2994 // to represent the length of long ZST slice iterators.
2995 let diff = ($self.end as usize).wrapping_sub(start as usize);
2998 // We know that `start <= end`, so can do better than `offset_from`,
2999 // which needs to deal in signed. By setting appropriate flags here
3000 // we can tell LLVM this, which helps it remove bounds checks.
3001 // SAFETY: By the type invariant, `start <= end`
3002 let diff = unsafe { unchecked_sub($self.end as usize, start as usize) };
3003 // By also telling LLVM that the pointers are apart by an exact
3004 // multiple of the type size, it can optimize `len() == 0` down to
3005 // `start == end` instead of `(end - start) < size`.
3006 // SAFETY: By the type invariant, the pointers are aligned so the
3007 // distance between them must be a multiple of pointee size
3008 unsafe { exact_div(diff, size) }
3013 // The shared definition of the `Iter` and `IterMut` iterators
3014 macro_rules! iterator {
3016 struct $name:ident -> $ptr:ty,
3022 // Returns the first element and moves the start of the iterator forwards by 1.
3023 // Greatly improves performance compared to an inlined function. The iterator
3024 // must not be empty.
3025 macro_rules! next_unchecked {
3026 ($self: ident) => {& $( $mut_ )* *$self.post_inc_start(1)}
3029 // Returns the last element and moves the end of the iterator backwards by 1.
3030 // Greatly improves performance compared to an inlined function. The iterator
3031 // must not be empty.
3032 macro_rules! next_back_unchecked {
3033 ($self: ident) => {& $( $mut_ )* *$self.pre_dec_end(1)}
3036 // Shrinks the iterator when T is a ZST, by moving the end of the iterator
3037 // backwards by `n`. `n` must not exceed `self.len()`.
3038 macro_rules! zst_shrink {
3039 ($self: ident, $n: ident) => {
3040 $self.end = ($self.end as * $raw_mut u8).wrapping_offset(-$n) as * $raw_mut T;
3044 impl<'a, T> $name<'a, T> {
3045 // Helper function for creating a slice from the iterator.
3047 fn make_slice(&self) -> &'a [T] {
3048 unsafe { from_raw_parts(self.ptr, len!(self)) }
3051 // Helper function for moving the start of the iterator forwards by `offset` elements,
3052 // returning the old start.
3053 // Unsafe because the offset must not exceed `self.len()`.
3055 unsafe fn post_inc_start(&mut self, offset: isize) -> * $raw_mut T {
3056 if mem::size_of::<T>() == 0 {
3057 zst_shrink!(self, offset);
3061 self.ptr = self.ptr.offset(offset);
3066 // Helper function for moving the end of the iterator backwards by `offset` elements,
3067 // returning the new end.
3068 // Unsafe because the offset must not exceed `self.len()`.
3070 unsafe fn pre_dec_end(&mut self, offset: isize) -> * $raw_mut T {
3071 if mem::size_of::<T>() == 0 {
3072 zst_shrink!(self, offset);
3075 self.end = self.end.offset(-offset);
3081 #[stable(feature = "rust1", since = "1.0.0")]
3082 impl<T> ExactSizeIterator for $name<'_, T> {
3084 fn len(&self) -> usize {
3089 fn is_empty(&self) -> bool {
3094 #[stable(feature = "rust1", since = "1.0.0")]
3095 impl<'a, T> Iterator for $name<'a, T> {
3099 fn next(&mut self) -> Option<$elem> {
3100 // could be implemented with slices, but this avoids bounds checks
3102 assume(!self.ptr.is_null());
3103 if mem::size_of::<T>() != 0 {
3104 assume(!self.end.is_null());
3106 if is_empty!(self) {
3109 Some(next_unchecked!(self))
3115 fn size_hint(&self) -> (usize, Option<usize>) {
3116 let exact = len!(self);
3117 (exact, Some(exact))
3121 fn count(self) -> usize {
3126 fn nth(&mut self, n: usize) -> Option<$elem> {
3127 if n >= len!(self) {
3128 // This iterator is now empty.
3129 if mem::size_of::<T>() == 0 {
3130 // We have to do it this way as `ptr` may never be 0, but `end`
3131 // could be (due to wrapping).
3132 self.end = self.ptr;
3134 self.ptr = self.end;
3138 // We are in bounds. `post_inc_start` does the right thing even for ZSTs.
3140 self.post_inc_start(n as isize);
3141 Some(next_unchecked!(self))
3146 fn last(mut self) -> Option<$elem> {
3151 fn try_fold<B, F, R>(&mut self, init: B, mut f: F) -> R where
3152 Self: Sized, F: FnMut(B, Self::Item) -> R, R: Try<Ok=B>
3154 // manual unrolling is needed when there are conditional exits from the loop
3155 let mut accum = init;
3157 while len!(self) >= 4 {
3158 accum = f(accum, next_unchecked!(self))?;
3159 accum = f(accum, next_unchecked!(self))?;
3160 accum = f(accum, next_unchecked!(self))?;
3161 accum = f(accum, next_unchecked!(self))?;
3163 while !is_empty!(self) {
3164 accum = f(accum, next_unchecked!(self))?;
3171 fn fold<Acc, Fold>(mut self, init: Acc, mut f: Fold) -> Acc
3172 where Fold: FnMut(Acc, Self::Item) -> Acc,
3174 // Let LLVM unroll this, rather than using the default
3175 // impl that would force the manual unrolling above
3176 let mut accum = init;
3177 while let Some(x) = self.next() {
3178 accum = f(accum, x);
3184 #[rustc_inherit_overflow_checks]
3185 fn position<P>(&mut self, mut predicate: P) -> Option<usize> where
3187 P: FnMut(Self::Item) -> bool,
3189 // The addition might panic on overflow.
3191 self.try_fold(0, move |i, x| {
3192 if predicate(x) { Err(i) }
3196 unsafe { assume(i < n) };
3202 fn rposition<P>(&mut self, mut predicate: P) -> Option<usize> where
3203 P: FnMut(Self::Item) -> bool,
3204 Self: Sized + ExactSizeIterator + DoubleEndedIterator
3206 // No need for an overflow check here, because `ExactSizeIterator`
3208 self.try_rfold(n, move |i, x| {
3210 if predicate(x) { Err(i) }
3214 unsafe { assume(i < n) };
3222 #[stable(feature = "rust1", since = "1.0.0")]
3223 impl<'a, T> DoubleEndedIterator for $name<'a, T> {
3225 fn next_back(&mut self) -> Option<$elem> {
3226 // could be implemented with slices, but this avoids bounds checks
3228 assume(!self.ptr.is_null());
3229 if mem::size_of::<T>() != 0 {
3230 assume(!self.end.is_null());
3232 if is_empty!(self) {
3235 Some(next_back_unchecked!(self))
3241 fn nth_back(&mut self, n: usize) -> Option<$elem> {
3242 if n >= len!(self) {
3243 // This iterator is now empty.
3244 self.end = self.ptr;
3247 // We are in bounds. `pre_dec_end` does the right thing even for ZSTs.
3249 self.pre_dec_end(n as isize);
3250 Some(next_back_unchecked!(self))
3255 fn try_rfold<B, F, R>(&mut self, init: B, mut f: F) -> R where
3256 Self: Sized, F: FnMut(B, Self::Item) -> R, R: Try<Ok=B>
3258 // manual unrolling is needed when there are conditional exits from the loop
3259 let mut accum = init;
3261 while len!(self) >= 4 {
3262 accum = f(accum, next_back_unchecked!(self))?;
3263 accum = f(accum, next_back_unchecked!(self))?;
3264 accum = f(accum, next_back_unchecked!(self))?;
3265 accum = f(accum, next_back_unchecked!(self))?;
3267 // inlining is_empty everywhere makes a huge performance difference
3268 while !is_empty!(self) {
3269 accum = f(accum, next_back_unchecked!(self))?;
3276 fn rfold<Acc, Fold>(mut self, init: Acc, mut f: Fold) -> Acc
3277 where Fold: FnMut(Acc, Self::Item) -> Acc,
3279 // Let LLVM unroll this, rather than using the default
3280 // impl that would force the manual unrolling above
3281 let mut accum = init;
3282 while let Some(x) = self.next_back() {
3283 accum = f(accum, x);
3289 #[stable(feature = "fused", since = "1.26.0")]
3290 impl<T> FusedIterator for $name<'_, T> {}
3292 #[unstable(feature = "trusted_len", issue = "37572")]
3293 unsafe impl<T> TrustedLen for $name<'_, T> {}
3297 /// Immutable slice iterator
3299 /// This struct is created by the [`iter`] method on [slices].
3306 /// // First, we declare a type which has `iter` method to get the `Iter` struct (&[usize here]):
3307 /// let slice = &[1, 2, 3];
3309 /// // Then, we iterate over it:
3310 /// for element in slice.iter() {
3311 /// println!("{}", element);
3315 /// [`iter`]: ../../std/primitive.slice.html#method.iter
3316 /// [slices]: ../../std/primitive.slice.html
3317 #[stable(feature = "rust1", since = "1.0.0")]
3318 pub struct Iter<'a, T: 'a> {
3320 end: *const T, // If T is a ZST, this is actually ptr+len. This encoding is picked so that
3321 // ptr == end is a quick test for the Iterator being empty, that works
3322 // for both ZST and non-ZST.
3323 _marker: marker::PhantomData<&'a T>,
3326 #[stable(feature = "core_impl_debug", since = "1.9.0")]
3327 impl<T: fmt::Debug> fmt::Debug for Iter<'_, T> {
3328 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
3329 f.debug_tuple("Iter")
3330 .field(&self.as_slice())
3335 #[stable(feature = "rust1", since = "1.0.0")]
3336 unsafe impl<T: Sync> Sync for Iter<'_, T> {}
3337 #[stable(feature = "rust1", since = "1.0.0")]
3338 unsafe impl<T: Sync> Send for Iter<'_, T> {}
3340 impl<'a, T> Iter<'a, T> {
3341 /// Views the underlying data as a subslice of the original data.
3343 /// This has the same lifetime as the original slice, and so the
3344 /// iterator can continue to be used while this exists.
3351 /// // First, we declare a type which has the `iter` method to get the `Iter`
3352 /// // struct (&[usize here]):
3353 /// let slice = &[1, 2, 3];
3355 /// // Then, we get the iterator:
3356 /// let mut iter = slice.iter();
3357 /// // So if we print what `as_slice` method returns here, we have "[1, 2, 3]":
3358 /// println!("{:?}", iter.as_slice());
3360 /// // Next, we move to the second element of the slice:
3362 /// // Now `as_slice` returns "[2, 3]":
3363 /// println!("{:?}", iter.as_slice());
3365 #[stable(feature = "iter_to_slice", since = "1.4.0")]
3366 pub fn as_slice(&self) -> &'a [T] {
3371 iterator!{struct Iter -> *const T, &'a T, const, {/* no mut */}, {
3372 fn is_sorted_by<F>(self, mut compare: F) -> bool
3375 F: FnMut(&Self::Item, &Self::Item) -> Option<Ordering>,
3377 self.as_slice().windows(2).all(|w| {
3378 compare(&&w[0], &&w[1]).map(|o| o != Ordering::Greater).unwrap_or(false)
3383 #[stable(feature = "rust1", since = "1.0.0")]
3384 impl<T> Clone for Iter<'_, T> {
3385 fn clone(&self) -> Self { Iter { ptr: self.ptr, end: self.end, _marker: self._marker } }
3388 #[stable(feature = "slice_iter_as_ref", since = "1.13.0")]
3389 impl<T> AsRef<[T]> for Iter<'_, T> {
3390 fn as_ref(&self) -> &[T] {
3395 /// Mutable slice iterator.
3397 /// This struct is created by the [`iter_mut`] method on [slices].
3404 /// // First, we declare a type which has `iter_mut` method to get the `IterMut`
3405 /// // struct (&[usize here]):
3406 /// let mut slice = &mut [1, 2, 3];
3408 /// // Then, we iterate over it and increment each element value:
3409 /// for element in slice.iter_mut() {
3413 /// // We now have "[2, 3, 4]":
3414 /// println!("{:?}", slice);
3417 /// [`iter_mut`]: ../../std/primitive.slice.html#method.iter_mut
3418 /// [slices]: ../../std/primitive.slice.html
3419 #[stable(feature = "rust1", since = "1.0.0")]
3420 pub struct IterMut<'a, T: 'a> {
3422 end: *mut T, // If T is a ZST, this is actually ptr+len. This encoding is picked so that
3423 // ptr == end is a quick test for the Iterator being empty, that works
3424 // for both ZST and non-ZST.
3425 _marker: marker::PhantomData<&'a mut T>,
3428 #[stable(feature = "core_impl_debug", since = "1.9.0")]
3429 impl<T: fmt::Debug> fmt::Debug for IterMut<'_, T> {
3430 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
3431 f.debug_tuple("IterMut")
3432 .field(&self.make_slice())
3437 #[stable(feature = "rust1", since = "1.0.0")]
3438 unsafe impl<T: Sync> Sync for IterMut<'_, T> {}
3439 #[stable(feature = "rust1", since = "1.0.0")]
3440 unsafe impl<T: Send> Send for IterMut<'_, T> {}
3442 impl<'a, T> IterMut<'a, T> {
3443 /// Views the underlying data as a subslice of the original data.
3445 /// To avoid creating `&mut` references that alias, this is forced
3446 /// to consume the iterator.
3453 /// // First, we declare a type which has `iter_mut` method to get the `IterMut`
3454 /// // struct (&[usize here]):
3455 /// let mut slice = &mut [1, 2, 3];
3458 /// // Then, we get the iterator:
3459 /// let mut iter = slice.iter_mut();
3460 /// // We move to next element:
3462 /// // So if we print what `into_slice` method returns here, we have "[2, 3]":
3463 /// println!("{:?}", iter.into_slice());
3466 /// // Now let's modify a value of the slice:
3468 /// // First we get back the iterator:
3469 /// let mut iter = slice.iter_mut();
3470 /// // We change the value of the first element of the slice returned by the `next` method:
3471 /// *iter.next().unwrap() += 1;
3473 /// // Now slice is "[2, 2, 3]":
3474 /// println!("{:?}", slice);
3476 #[stable(feature = "iter_to_slice", since = "1.4.0")]
3477 pub fn into_slice(self) -> &'a mut [T] {
3478 unsafe { from_raw_parts_mut(self.ptr, len!(self)) }
3481 /// Views the underlying data as a subslice of the original data.
3483 /// To avoid creating `&mut [T]` references that alias, the returned slice
3484 /// borrows its lifetime from the iterator the method is applied on.
3491 /// # #![feature(slice_iter_mut_as_slice)]
3492 /// let mut slice: &mut [usize] = &mut [1, 2, 3];
3494 /// // First, we get the iterator:
3495 /// let mut iter = slice.iter_mut();
3496 /// // So if we check what the `as_slice` method returns here, we have "[1, 2, 3]":
3497 /// assert_eq!(iter.as_slice(), &[1, 2, 3]);
3499 /// // Next, we move to the second element of the slice:
3501 /// // Now `as_slice` returns "[2, 3]":
3502 /// assert_eq!(iter.as_slice(), &[2, 3]);
3504 #[unstable(feature = "slice_iter_mut_as_slice", reason = "recently added", issue = "58957")]
3505 pub fn as_slice(&self) -> &[T] {
3510 iterator!{struct IterMut -> *mut T, &'a mut T, mut, {mut}, {}}
3512 /// An internal abstraction over the splitting iterators, so that
3513 /// splitn, splitn_mut etc can be implemented once.
3515 trait SplitIter: DoubleEndedIterator {
3516 /// Marks the underlying iterator as complete, extracting the remaining
3517 /// portion of the slice.
3518 fn finish(&mut self) -> Option<Self::Item>;
3521 /// An iterator over subslices separated by elements that match a predicate
3524 /// This struct is created by the [`split`] method on [slices].
3526 /// [`split`]: ../../std/primitive.slice.html#method.split
3527 /// [slices]: ../../std/primitive.slice.html
3528 #[stable(feature = "rust1", since = "1.0.0")]
3529 pub struct Split<'a, T:'a, P> where P: FnMut(&T) -> bool {
3535 #[stable(feature = "core_impl_debug", since = "1.9.0")]
3536 impl<T: fmt::Debug, P> fmt::Debug for Split<'_, T, P> where P: FnMut(&T) -> bool {
3537 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
3538 f.debug_struct("Split")
3539 .field("v", &self.v)
3540 .field("finished", &self.finished)
3545 // FIXME(#26925) Remove in favor of `#[derive(Clone)]`
3546 #[stable(feature = "rust1", since = "1.0.0")]
3547 impl<T, P> Clone for Split<'_, T, P> where P: Clone + FnMut(&T) -> bool {
3548 fn clone(&self) -> Self {
3551 pred: self.pred.clone(),
3552 finished: self.finished,
3557 #[stable(feature = "rust1", since = "1.0.0")]
3558 impl<'a, T, P> Iterator for Split<'a, T, P> where P: FnMut(&T) -> bool {
3559 type Item = &'a [T];
3562 fn next(&mut self) -> Option<&'a [T]> {
3563 if self.finished { return None; }
3565 match self.v.iter().position(|x| (self.pred)(x)) {
3566 None => self.finish(),
3568 let ret = Some(&self.v[..idx]);
3569 self.v = &self.v[idx + 1..];
3576 fn size_hint(&self) -> (usize, Option<usize>) {
3580 (1, Some(self.v.len() + 1))
3585 #[stable(feature = "rust1", since = "1.0.0")]
3586 impl<'a, T, P> DoubleEndedIterator for Split<'a, T, P> where P: FnMut(&T) -> bool {
3588 fn next_back(&mut self) -> Option<&'a [T]> {
3589 if self.finished { return None; }
3591 match self.v.iter().rposition(|x| (self.pred)(x)) {
3592 None => self.finish(),
3594 let ret = Some(&self.v[idx + 1..]);
3595 self.v = &self.v[..idx];
3602 impl<'a, T, P> SplitIter for Split<'a, T, P> where P: FnMut(&T) -> bool {
3604 fn finish(&mut self) -> Option<&'a [T]> {
3605 if self.finished { None } else { self.finished = true; Some(self.v) }
3609 #[stable(feature = "fused", since = "1.26.0")]
3610 impl<T, P> FusedIterator for Split<'_, T, P> where P: FnMut(&T) -> bool {}
3612 /// An iterator over the subslices of the vector which are separated
3613 /// by elements that match `pred`.
3615 /// This struct is created by the [`split_mut`] method on [slices].
3617 /// [`split_mut`]: ../../std/primitive.slice.html#method.split_mut
3618 /// [slices]: ../../std/primitive.slice.html
3619 #[stable(feature = "rust1", since = "1.0.0")]
3620 pub struct SplitMut<'a, T:'a, P> where P: FnMut(&T) -> bool {
3626 #[stable(feature = "core_impl_debug", since = "1.9.0")]
3627 impl<T: fmt::Debug, P> fmt::Debug for SplitMut<'_, T, P> where P: FnMut(&T) -> bool {
3628 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
3629 f.debug_struct("SplitMut")
3630 .field("v", &self.v)
3631 .field("finished", &self.finished)
3636 impl<'a, T, P> SplitIter for SplitMut<'a, T, P> where P: FnMut(&T) -> bool {
3638 fn finish(&mut self) -> Option<&'a mut [T]> {
3642 self.finished = true;
3643 Some(mem::replace(&mut self.v, &mut []))
3648 #[stable(feature = "rust1", since = "1.0.0")]
3649 impl<'a, T, P> Iterator for SplitMut<'a, T, P> where P: FnMut(&T) -> bool {
3650 type Item = &'a mut [T];
3653 fn next(&mut self) -> Option<&'a mut [T]> {
3654 if self.finished { return None; }
3656 let idx_opt = { // work around borrowck limitations
3657 let pred = &mut self.pred;
3658 self.v.iter().position(|x| (*pred)(x))
3661 None => self.finish(),
3663 let tmp = mem::replace(&mut self.v, &mut []);
3664 let (head, tail) = tmp.split_at_mut(idx);
3665 self.v = &mut tail[1..];
3672 fn size_hint(&self) -> (usize, Option<usize>) {
3676 // if the predicate doesn't match anything, we yield one slice
3677 // if it matches every element, we yield len+1 empty slices.
3678 (1, Some(self.v.len() + 1))
3683 #[stable(feature = "rust1", since = "1.0.0")]
3684 impl<'a, T, P> DoubleEndedIterator for SplitMut<'a, T, P> where
3685 P: FnMut(&T) -> bool,
3688 fn next_back(&mut self) -> Option<&'a mut [T]> {
3689 if self.finished { return None; }
3691 let idx_opt = { // work around borrowck limitations
3692 let pred = &mut self.pred;
3693 self.v.iter().rposition(|x| (*pred)(x))
3696 None => self.finish(),
3698 let tmp = mem::replace(&mut self.v, &mut []);
3699 let (head, tail) = tmp.split_at_mut(idx);
3701 Some(&mut tail[1..])
3707 #[stable(feature = "fused", since = "1.26.0")]
3708 impl<T, P> FusedIterator for SplitMut<'_, T, P> where P: FnMut(&T) -> bool {}
3710 /// An iterator over subslices separated by elements that match a predicate
3711 /// function, starting from the end of the slice.
3713 /// This struct is created by the [`rsplit`] method on [slices].
3715 /// [`rsplit`]: ../../std/primitive.slice.html#method.rsplit
3716 /// [slices]: ../../std/primitive.slice.html
3717 #[stable(feature = "slice_rsplit", since = "1.27.0")]
3718 #[derive(Clone)] // Is this correct, or does it incorrectly require `T: Clone`?
3719 pub struct RSplit<'a, T:'a, P> where P: FnMut(&T) -> bool {
3720 inner: Split<'a, T, P>
3723 #[stable(feature = "slice_rsplit", since = "1.27.0")]
3724 impl<T: fmt::Debug, P> fmt::Debug for RSplit<'_, T, P> where P: FnMut(&T) -> bool {
3725 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
3726 f.debug_struct("RSplit")
3727 .field("v", &self.inner.v)
3728 .field("finished", &self.inner.finished)
3733 #[stable(feature = "slice_rsplit", since = "1.27.0")]
3734 impl<'a, T, P> Iterator for RSplit<'a, T, P> where P: FnMut(&T) -> bool {
3735 type Item = &'a [T];
3738 fn next(&mut self) -> Option<&'a [T]> {
3739 self.inner.next_back()
3743 fn size_hint(&self) -> (usize, Option<usize>) {
3744 self.inner.size_hint()
3748 #[stable(feature = "slice_rsplit", since = "1.27.0")]
3749 impl<'a, T, P> DoubleEndedIterator for RSplit<'a, T, P> where P: FnMut(&T) -> bool {
3751 fn next_back(&mut self) -> Option<&'a [T]> {
3756 #[stable(feature = "slice_rsplit", since = "1.27.0")]
3757 impl<'a, T, P> SplitIter for RSplit<'a, T, P> where P: FnMut(&T) -> bool {
3759 fn finish(&mut self) -> Option<&'a [T]> {
3764 #[stable(feature = "slice_rsplit", since = "1.27.0")]
3765 impl<T, P> FusedIterator for RSplit<'_, T, P> where P: FnMut(&T) -> bool {}
3767 /// An iterator over the subslices of the vector which are separated
3768 /// by elements that match `pred`, starting from the end of the slice.
3770 /// This struct is created by the [`rsplit_mut`] method on [slices].
3772 /// [`rsplit_mut`]: ../../std/primitive.slice.html#method.rsplit_mut
3773 /// [slices]: ../../std/primitive.slice.html
3774 #[stable(feature = "slice_rsplit", since = "1.27.0")]
3775 pub struct RSplitMut<'a, T:'a, P> where P: FnMut(&T) -> bool {
3776 inner: SplitMut<'a, T, P>
3779 #[stable(feature = "slice_rsplit", since = "1.27.0")]
3780 impl<T: fmt::Debug, P> fmt::Debug for RSplitMut<'_, T, P> where P: FnMut(&T) -> bool {
3781 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
3782 f.debug_struct("RSplitMut")
3783 .field("v", &self.inner.v)
3784 .field("finished", &self.inner.finished)
3789 #[stable(feature = "slice_rsplit", since = "1.27.0")]
3790 impl<'a, T, P> SplitIter for RSplitMut<'a, T, P> where P: FnMut(&T) -> bool {
3792 fn finish(&mut self) -> Option<&'a mut [T]> {
3797 #[stable(feature = "slice_rsplit", since = "1.27.0")]
3798 impl<'a, T, P> Iterator for RSplitMut<'a, T, P> where P: FnMut(&T) -> bool {
3799 type Item = &'a mut [T];
3802 fn next(&mut self) -> Option<&'a mut [T]> {
3803 self.inner.next_back()
3807 fn size_hint(&self) -> (usize, Option<usize>) {
3808 self.inner.size_hint()
3812 #[stable(feature = "slice_rsplit", since = "1.27.0")]
3813 impl<'a, T, P> DoubleEndedIterator for RSplitMut<'a, T, P> where
3814 P: FnMut(&T) -> bool,
3817 fn next_back(&mut self) -> Option<&'a mut [T]> {
3822 #[stable(feature = "slice_rsplit", since = "1.27.0")]
3823 impl<T, P> FusedIterator for RSplitMut<'_, T, P> where P: FnMut(&T) -> bool {}
3825 /// An private iterator over subslices separated by elements that
3826 /// match a predicate function, splitting at most a fixed number of
3829 struct GenericSplitN<I> {
3834 impl<T, I: SplitIter<Item=T>> Iterator for GenericSplitN<I> {
3838 fn next(&mut self) -> Option<T> {
3841 1 => { self.count -= 1; self.iter.finish() }
3842 _ => { self.count -= 1; self.iter.next() }
3847 fn size_hint(&self) -> (usize, Option<usize>) {
3848 let (lower, upper_opt) = self.iter.size_hint();
3849 (lower, upper_opt.map(|upper| cmp::min(self.count, upper)))
3853 /// An iterator over subslices separated by elements that match a predicate
3854 /// function, limited to a given number of splits.
3856 /// This struct is created by the [`splitn`] method on [slices].
3858 /// [`splitn`]: ../../std/primitive.slice.html#method.splitn
3859 /// [slices]: ../../std/primitive.slice.html
3860 #[stable(feature = "rust1", since = "1.0.0")]
3861 pub struct SplitN<'a, T: 'a, P> where P: FnMut(&T) -> bool {
3862 inner: GenericSplitN<Split<'a, T, P>>
3865 #[stable(feature = "core_impl_debug", since = "1.9.0")]
3866 impl<T: fmt::Debug, P> fmt::Debug for SplitN<'_, T, P> where P: FnMut(&T) -> bool {
3867 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
3868 f.debug_struct("SplitN")
3869 .field("inner", &self.inner)
3874 /// An iterator over subslices separated by elements that match a
3875 /// predicate function, limited to a given number of splits, starting
3876 /// from the end of the slice.
3878 /// This struct is created by the [`rsplitn`] method on [slices].
3880 /// [`rsplitn`]: ../../std/primitive.slice.html#method.rsplitn
3881 /// [slices]: ../../std/primitive.slice.html
3882 #[stable(feature = "rust1", since = "1.0.0")]
3883 pub struct RSplitN<'a, T: 'a, P> where P: FnMut(&T) -> bool {
3884 inner: GenericSplitN<RSplit<'a, T, P>>
3887 #[stable(feature = "core_impl_debug", since = "1.9.0")]
3888 impl<T: fmt::Debug, P> fmt::Debug for RSplitN<'_, T, P> where P: FnMut(&T) -> bool {
3889 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
3890 f.debug_struct("RSplitN")
3891 .field("inner", &self.inner)
3896 /// An iterator over subslices separated by elements that match a predicate
3897 /// function, limited to a given number of splits.
3899 /// This struct is created by the [`splitn_mut`] method on [slices].
3901 /// [`splitn_mut`]: ../../std/primitive.slice.html#method.splitn_mut
3902 /// [slices]: ../../std/primitive.slice.html
3903 #[stable(feature = "rust1", since = "1.0.0")]
3904 pub struct SplitNMut<'a, T: 'a, P> where P: FnMut(&T) -> bool {
3905 inner: GenericSplitN<SplitMut<'a, T, P>>
3908 #[stable(feature = "core_impl_debug", since = "1.9.0")]
3909 impl<T: fmt::Debug, P> fmt::Debug for SplitNMut<'_, T, P> where P: FnMut(&T) -> bool {
3910 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
3911 f.debug_struct("SplitNMut")
3912 .field("inner", &self.inner)
3917 /// An iterator over subslices separated by elements that match a
3918 /// predicate function, limited to a given number of splits, starting
3919 /// from the end of the slice.
3921 /// This struct is created by the [`rsplitn_mut`] method on [slices].
3923 /// [`rsplitn_mut`]: ../../std/primitive.slice.html#method.rsplitn_mut
3924 /// [slices]: ../../std/primitive.slice.html
3925 #[stable(feature = "rust1", since = "1.0.0")]
3926 pub struct RSplitNMut<'a, T: 'a, P> where P: FnMut(&T) -> bool {
3927 inner: GenericSplitN<RSplitMut<'a, T, P>>
3930 #[stable(feature = "core_impl_debug", since = "1.9.0")]
3931 impl<T: fmt::Debug, P> fmt::Debug for RSplitNMut<'_, T, P> where P: FnMut(&T) -> bool {
3932 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
3933 f.debug_struct("RSplitNMut")
3934 .field("inner", &self.inner)
3939 macro_rules! forward_iterator {
3940 ($name:ident: $elem:ident, $iter_of:ty) => {
3941 #[stable(feature = "rust1", since = "1.0.0")]
3942 impl<'a, $elem, P> Iterator for $name<'a, $elem, P> where
3943 P: FnMut(&T) -> bool
3945 type Item = $iter_of;
3948 fn next(&mut self) -> Option<$iter_of> {
3953 fn size_hint(&self) -> (usize, Option<usize>) {
3954 self.inner.size_hint()
3958 #[stable(feature = "fused", since = "1.26.0")]
3959 impl<'a, $elem, P> FusedIterator for $name<'a, $elem, P>
3960 where P: FnMut(&T) -> bool {}
3964 forward_iterator! { SplitN: T, &'a [T] }
3965 forward_iterator! { RSplitN: T, &'a [T] }
3966 forward_iterator! { SplitNMut: T, &'a mut [T] }
3967 forward_iterator! { RSplitNMut: T, &'a mut [T] }
3969 /// An iterator over overlapping subslices of length `size`.
3971 /// This struct is created by the [`windows`] method on [slices].
3973 /// [`windows`]: ../../std/primitive.slice.html#method.windows
3974 /// [slices]: ../../std/primitive.slice.html
3976 #[stable(feature = "rust1", since = "1.0.0")]
3977 pub struct Windows<'a, T:'a> {
3982 // FIXME(#26925) Remove in favor of `#[derive(Clone)]`
3983 #[stable(feature = "rust1", since = "1.0.0")]
3984 impl<T> Clone for Windows<'_, T> {
3985 fn clone(&self) -> Self {
3993 #[stable(feature = "rust1", since = "1.0.0")]
3994 impl<'a, T> Iterator for Windows<'a, T> {
3995 type Item = &'a [T];
3998 fn next(&mut self) -> Option<&'a [T]> {
3999 if self.size > self.v.len() {
4002 let ret = Some(&self.v[..self.size]);
4003 self.v = &self.v[1..];
4009 fn size_hint(&self) -> (usize, Option<usize>) {
4010 if self.size > self.v.len() {
4013 let size = self.v.len() - self.size + 1;
4019 fn count(self) -> usize {
4024 fn nth(&mut self, n: usize) -> Option<Self::Item> {
4025 let (end, overflow) = self.size.overflowing_add(n);
4026 if end > self.v.len() || overflow {
4030 let nth = &self.v[n..end];
4031 self.v = &self.v[n+1..];
4037 fn last(self) -> Option<Self::Item> {
4038 if self.size > self.v.len() {
4041 let start = self.v.len() - self.size;
4042 Some(&self.v[start..])
4047 #[stable(feature = "rust1", since = "1.0.0")]
4048 impl<'a, T> DoubleEndedIterator for Windows<'a, T> {
4050 fn next_back(&mut self) -> Option<&'a [T]> {
4051 if self.size > self.v.len() {
4054 let ret = Some(&self.v[self.v.len()-self.size..]);
4055 self.v = &self.v[..self.v.len()-1];
4061 fn nth_back(&mut self, n: usize) -> Option<Self::Item> {
4062 let (end, overflow) = self.v.len().overflowing_sub(n);
4063 if end < self.size || overflow {
4067 let ret = &self.v[end-self.size..end];
4068 self.v = &self.v[..end-1];
4074 #[stable(feature = "rust1", since = "1.0.0")]
4075 impl<T> ExactSizeIterator for Windows<'_, T> {}
4077 #[unstable(feature = "trusted_len", issue = "37572")]
4078 unsafe impl<T> TrustedLen for Windows<'_, T> {}
4080 #[stable(feature = "fused", since = "1.26.0")]
4081 impl<T> FusedIterator for Windows<'_, T> {}
4084 unsafe impl<'a, T> TrustedRandomAccess for Windows<'a, T> {
4085 unsafe fn get_unchecked(&mut self, i: usize) -> &'a [T] {
4086 from_raw_parts(self.v.as_ptr().add(i), self.size)
4088 fn may_have_side_effect() -> bool { false }
4091 /// An iterator over a slice in (non-overlapping) chunks (`chunk_size` elements at a
4092 /// time), starting at the beginning of the slice.
4094 /// When the slice len is not evenly divided by the chunk size, the last slice
4095 /// of the iteration will be the remainder.
4097 /// This struct is created by the [`chunks`] method on [slices].
4099 /// [`chunks`]: ../../std/primitive.slice.html#method.chunks
4100 /// [slices]: ../../std/primitive.slice.html
4102 #[stable(feature = "rust1", since = "1.0.0")]
4103 pub struct Chunks<'a, T:'a> {
4108 // FIXME(#26925) Remove in favor of `#[derive(Clone)]`
4109 #[stable(feature = "rust1", since = "1.0.0")]
4110 impl<T> Clone for Chunks<'_, T> {
4111 fn clone(&self) -> Self {
4114 chunk_size: self.chunk_size,
4119 #[stable(feature = "rust1", since = "1.0.0")]
4120 impl<'a, T> Iterator for Chunks<'a, T> {
4121 type Item = &'a [T];
4124 fn next(&mut self) -> Option<&'a [T]> {
4125 if self.v.is_empty() {
4128 let chunksz = cmp::min(self.v.len(), self.chunk_size);
4129 let (fst, snd) = self.v.split_at(chunksz);
4136 fn size_hint(&self) -> (usize, Option<usize>) {
4137 if self.v.is_empty() {
4140 let n = self.v.len() / self.chunk_size;
4141 let rem = self.v.len() % self.chunk_size;
4142 let n = if rem > 0 { n+1 } else { n };
4148 fn count(self) -> usize {
4153 fn nth(&mut self, n: usize) -> Option<Self::Item> {
4154 let (start, overflow) = n.overflowing_mul(self.chunk_size);
4155 if start >= self.v.len() || overflow {
4159 let end = match start.checked_add(self.chunk_size) {
4160 Some(sum) => cmp::min(self.v.len(), sum),
4161 None => self.v.len(),
4163 let nth = &self.v[start..end];
4164 self.v = &self.v[end..];
4170 fn last(self) -> Option<Self::Item> {
4171 if self.v.is_empty() {
4174 let start = (self.v.len() - 1) / self.chunk_size * self.chunk_size;
4175 Some(&self.v[start..])
4180 #[stable(feature = "rust1", since = "1.0.0")]
4181 impl<'a, T> DoubleEndedIterator for Chunks<'a, T> {
4183 fn next_back(&mut self) -> Option<&'a [T]> {
4184 if self.v.is_empty() {
4187 let remainder = self.v.len() % self.chunk_size;
4188 let chunksz = if remainder != 0 { remainder } else { self.chunk_size };
4189 let (fst, snd) = self.v.split_at(self.v.len() - chunksz);
4196 fn nth_back(&mut self, n: usize) -> Option<Self::Item> {
4197 let len = self.len();
4202 let start = (len - 1 - n) * self.chunk_size;
4203 let end = match start.checked_add(self.chunk_size) {
4204 Some(res) => cmp::min(res, self.v.len()),
4205 None => self.v.len(),
4207 let nth_back = &self.v[start..end];
4208 self.v = &self.v[..start];
4214 #[stable(feature = "rust1", since = "1.0.0")]
4215 impl<T> ExactSizeIterator for Chunks<'_, T> {}
4217 #[unstable(feature = "trusted_len", issue = "37572")]
4218 unsafe impl<T> TrustedLen for Chunks<'_, T> {}
4220 #[stable(feature = "fused", since = "1.26.0")]
4221 impl<T> FusedIterator for Chunks<'_, T> {}
4224 unsafe impl<'a, T> TrustedRandomAccess for Chunks<'a, T> {
4225 unsafe fn get_unchecked(&mut self, i: usize) -> &'a [T] {
4226 let start = i * self.chunk_size;
4227 let end = match start.checked_add(self.chunk_size) {
4228 None => self.v.len(),
4229 Some(end) => cmp::min(end, self.v.len()),
4231 from_raw_parts(self.v.as_ptr().add(start), end - start)
4233 fn may_have_side_effect() -> bool { false }
4236 /// An iterator over a slice in (non-overlapping) mutable chunks (`chunk_size`
4237 /// elements at a time), starting at the beginning of the slice.
4239 /// When the slice len is not evenly divided by the chunk size, the last slice
4240 /// of the iteration will be the remainder.
4242 /// This struct is created by the [`chunks_mut`] method on [slices].
4244 /// [`chunks_mut`]: ../../std/primitive.slice.html#method.chunks_mut
4245 /// [slices]: ../../std/primitive.slice.html
4247 #[stable(feature = "rust1", since = "1.0.0")]
4248 pub struct ChunksMut<'a, T:'a> {
4253 #[stable(feature = "rust1", since = "1.0.0")]
4254 impl<'a, T> Iterator for ChunksMut<'a, T> {
4255 type Item = &'a mut [T];
4258 fn next(&mut self) -> Option<&'a mut [T]> {
4259 if self.v.is_empty() {
4262 let sz = cmp::min(self.v.len(), self.chunk_size);
4263 let tmp = mem::replace(&mut self.v, &mut []);
4264 let (head, tail) = tmp.split_at_mut(sz);
4271 fn size_hint(&self) -> (usize, Option<usize>) {
4272 if self.v.is_empty() {
4275 let n = self.v.len() / self.chunk_size;
4276 let rem = self.v.len() % self.chunk_size;
4277 let n = if rem > 0 { n + 1 } else { n };
4283 fn count(self) -> usize {
4288 fn nth(&mut self, n: usize) -> Option<&'a mut [T]> {
4289 let (start, overflow) = n.overflowing_mul(self.chunk_size);
4290 if start >= self.v.len() || overflow {
4294 let end = match start.checked_add(self.chunk_size) {
4295 Some(sum) => cmp::min(self.v.len(), sum),
4296 None => self.v.len(),
4298 let tmp = mem::replace(&mut self.v, &mut []);
4299 let (head, tail) = tmp.split_at_mut(end);
4300 let (_, nth) = head.split_at_mut(start);
4307 fn last(self) -> Option<Self::Item> {
4308 if self.v.is_empty() {
4311 let start = (self.v.len() - 1) / self.chunk_size * self.chunk_size;
4312 Some(&mut self.v[start..])
4317 #[stable(feature = "rust1", since = "1.0.0")]
4318 impl<'a, T> DoubleEndedIterator for ChunksMut<'a, T> {
4320 fn next_back(&mut self) -> Option<&'a mut [T]> {
4321 if self.v.is_empty() {
4324 let remainder = self.v.len() % self.chunk_size;
4325 let sz = if remainder != 0 { remainder } else { self.chunk_size };
4326 let tmp = mem::replace(&mut self.v, &mut []);
4327 let tmp_len = tmp.len();
4328 let (head, tail) = tmp.split_at_mut(tmp_len - sz);
4335 fn nth_back(&mut self, n: usize) -> Option<Self::Item> {
4336 let len = self.len();
4341 let start = (len - 1 - n) * self.chunk_size;
4342 let end = match start.checked_add(self.chunk_size) {
4343 Some(res) => cmp::min(res, self.v.len()),
4344 None => self.v.len(),
4346 let (temp, _tail) = mem::replace(&mut self.v, &mut []).split_at_mut(end);
4347 let (head, nth_back) = temp.split_at_mut(start);
4354 #[stable(feature = "rust1", since = "1.0.0")]
4355 impl<T> ExactSizeIterator for ChunksMut<'_, T> {}
4357 #[unstable(feature = "trusted_len", issue = "37572")]
4358 unsafe impl<T> TrustedLen for ChunksMut<'_, T> {}
4360 #[stable(feature = "fused", since = "1.26.0")]
4361 impl<T> FusedIterator for ChunksMut<'_, T> {}
4364 unsafe impl<'a, T> TrustedRandomAccess for ChunksMut<'a, T> {
4365 unsafe fn get_unchecked(&mut self, i: usize) -> &'a mut [T] {
4366 let start = i * self.chunk_size;
4367 let end = match start.checked_add(self.chunk_size) {
4368 None => self.v.len(),
4369 Some(end) => cmp::min(end, self.v.len()),
4371 from_raw_parts_mut(self.v.as_mut_ptr().add(start), end - start)
4373 fn may_have_side_effect() -> bool { false }
4376 /// An iterator over a slice in (non-overlapping) chunks (`chunk_size` elements at a
4377 /// time), starting at the beginning of the slice.
4379 /// When the slice len is not evenly divided by the chunk size, the last
4380 /// up to `chunk_size-1` elements will be omitted but can be retrieved from
4381 /// the [`remainder`] function from the iterator.
4383 /// This struct is created by the [`chunks_exact`] method on [slices].
4385 /// [`chunks_exact`]: ../../std/primitive.slice.html#method.chunks_exact
4386 /// [`remainder`]: ../../std/slice/struct.ChunksExact.html#method.remainder
4387 /// [slices]: ../../std/primitive.slice.html
4389 #[stable(feature = "chunks_exact", since = "1.31.0")]
4390 pub struct ChunksExact<'a, T:'a> {
4396 impl<'a, T> ChunksExact<'a, T> {
4397 /// Returns the remainder of the original slice that is not going to be
4398 /// returned by the iterator. The returned slice has at most `chunk_size-1`
4400 #[stable(feature = "chunks_exact", since = "1.31.0")]
4401 pub fn remainder(&self) -> &'a [T] {
4406 // FIXME(#26925) Remove in favor of `#[derive(Clone)]`
4407 #[stable(feature = "chunks_exact", since = "1.31.0")]
4408 impl<T> Clone for ChunksExact<'_, T> {
4409 fn clone(&self) -> Self {
4413 chunk_size: self.chunk_size,
4418 #[stable(feature = "chunks_exact", since = "1.31.0")]
4419 impl<'a, T> Iterator for ChunksExact<'a, T> {
4420 type Item = &'a [T];
4423 fn next(&mut self) -> Option<&'a [T]> {
4424 if self.v.len() < self.chunk_size {
4427 let (fst, snd) = self.v.split_at(self.chunk_size);
4434 fn size_hint(&self) -> (usize, Option<usize>) {
4435 let n = self.v.len() / self.chunk_size;
4440 fn count(self) -> usize {
4445 fn nth(&mut self, n: usize) -> Option<Self::Item> {
4446 let (start, overflow) = n.overflowing_mul(self.chunk_size);
4447 if start >= self.v.len() || overflow {
4451 let (_, snd) = self.v.split_at(start);
4458 fn last(mut self) -> Option<Self::Item> {
4463 #[stable(feature = "chunks_exact", since = "1.31.0")]
4464 impl<'a, T> DoubleEndedIterator for ChunksExact<'a, T> {
4466 fn next_back(&mut self) -> Option<&'a [T]> {
4467 if self.v.len() < self.chunk_size {
4470 let (fst, snd) = self.v.split_at(self.v.len() - self.chunk_size);
4477 #[stable(feature = "chunks_exact", since = "1.31.0")]
4478 impl<T> ExactSizeIterator for ChunksExact<'_, T> {
4479 fn is_empty(&self) -> bool {
4484 #[unstable(feature = "trusted_len", issue = "37572")]
4485 unsafe impl<T> TrustedLen for ChunksExact<'_, T> {}
4487 #[stable(feature = "chunks_exact", since = "1.31.0")]
4488 impl<T> FusedIterator for ChunksExact<'_, T> {}
4491 #[stable(feature = "chunks_exact", since = "1.31.0")]
4492 unsafe impl<'a, T> TrustedRandomAccess for ChunksExact<'a, T> {
4493 unsafe fn get_unchecked(&mut self, i: usize) -> &'a [T] {
4494 let start = i * self.chunk_size;
4495 from_raw_parts(self.v.as_ptr().add(start), self.chunk_size)
4497 fn may_have_side_effect() -> bool { false }
4500 /// An iterator over a slice in (non-overlapping) mutable chunks (`chunk_size`
4501 /// elements at a time), starting at the beginning of the slice.
4503 /// When the slice len is not evenly divided by the chunk size, the last up to
4504 /// `chunk_size-1` elements will be omitted but can be retrieved from the
4505 /// [`into_remainder`] function from the iterator.
4507 /// This struct is created by the [`chunks_exact_mut`] method on [slices].
4509 /// [`chunks_exact_mut`]: ../../std/primitive.slice.html#method.chunks_exact_mut
4510 /// [`into_remainder`]: ../../std/slice/struct.ChunksExactMut.html#method.into_remainder
4511 /// [slices]: ../../std/primitive.slice.html
4513 #[stable(feature = "chunks_exact", since = "1.31.0")]
4514 pub struct ChunksExactMut<'a, T:'a> {
4520 impl<'a, T> ChunksExactMut<'a, T> {
4521 /// Returns the remainder of the original slice that is not going to be
4522 /// returned by the iterator. The returned slice has at most `chunk_size-1`
4524 #[stable(feature = "chunks_exact", since = "1.31.0")]
4525 pub fn into_remainder(self) -> &'a mut [T] {
4530 #[stable(feature = "chunks_exact", since = "1.31.0")]
4531 impl<'a, T> Iterator for ChunksExactMut<'a, T> {
4532 type Item = &'a mut [T];
4535 fn next(&mut self) -> Option<&'a mut [T]> {
4536 if self.v.len() < self.chunk_size {
4539 let tmp = mem::replace(&mut self.v, &mut []);
4540 let (head, tail) = tmp.split_at_mut(self.chunk_size);
4547 fn size_hint(&self) -> (usize, Option<usize>) {
4548 let n = self.v.len() / self.chunk_size;
4553 fn count(self) -> usize {
4558 fn nth(&mut self, n: usize) -> Option<&'a mut [T]> {
4559 let (start, overflow) = n.overflowing_mul(self.chunk_size);
4560 if start >= self.v.len() || overflow {
4564 let tmp = mem::replace(&mut self.v, &mut []);
4565 let (_, snd) = tmp.split_at_mut(start);
4572 fn last(mut self) -> Option<Self::Item> {
4577 #[stable(feature = "chunks_exact", since = "1.31.0")]
4578 impl<'a, T> DoubleEndedIterator for ChunksExactMut<'a, T> {
4580 fn next_back(&mut self) -> Option<&'a mut [T]> {
4581 if self.v.len() < self.chunk_size {
4584 let tmp = mem::replace(&mut self.v, &mut []);
4585 let tmp_len = tmp.len();
4586 let (head, tail) = tmp.split_at_mut(tmp_len - self.chunk_size);
4593 #[stable(feature = "chunks_exact", since = "1.31.0")]
4594 impl<T> ExactSizeIterator for ChunksExactMut<'_, T> {
4595 fn is_empty(&self) -> bool {
4600 #[unstable(feature = "trusted_len", issue = "37572")]
4601 unsafe impl<T> TrustedLen for ChunksExactMut<'_, T> {}
4603 #[stable(feature = "chunks_exact", since = "1.31.0")]
4604 impl<T> FusedIterator for ChunksExactMut<'_, T> {}
4607 #[stable(feature = "chunks_exact", since = "1.31.0")]
4608 unsafe impl<'a, T> TrustedRandomAccess for ChunksExactMut<'a, T> {
4609 unsafe fn get_unchecked(&mut self, i: usize) -> &'a mut [T] {
4610 let start = i * self.chunk_size;
4611 from_raw_parts_mut(self.v.as_mut_ptr().add(start), self.chunk_size)
4613 fn may_have_side_effect() -> bool { false }
4616 /// An iterator over a slice in (non-overlapping) chunks (`chunk_size` elements at a
4617 /// time), starting at the end of the slice.
4619 /// When the slice len is not evenly divided by the chunk size, the last slice
4620 /// of the iteration will be the remainder.
4622 /// This struct is created by the [`rchunks`] method on [slices].
4624 /// [`rchunks`]: ../../std/primitive.slice.html#method.rchunks
4625 /// [slices]: ../../std/primitive.slice.html
4627 #[stable(feature = "rchunks", since = "1.31.0")]
4628 pub struct RChunks<'a, T:'a> {
4633 // FIXME(#26925) Remove in favor of `#[derive(Clone)]`
4634 #[stable(feature = "rchunks", since = "1.31.0")]
4635 impl<T> Clone for RChunks<'_, T> {
4636 fn clone(&self) -> Self {
4639 chunk_size: self.chunk_size,
4644 #[stable(feature = "rchunks", since = "1.31.0")]
4645 impl<'a, T> Iterator for RChunks<'a, T> {
4646 type Item = &'a [T];
4649 fn next(&mut self) -> Option<&'a [T]> {
4650 if self.v.is_empty() {
4653 let chunksz = cmp::min(self.v.len(), self.chunk_size);
4654 let (fst, snd) = self.v.split_at(self.v.len() - chunksz);
4661 fn size_hint(&self) -> (usize, Option<usize>) {
4662 if self.v.is_empty() {
4665 let n = self.v.len() / self.chunk_size;
4666 let rem = self.v.len() % self.chunk_size;
4667 let n = if rem > 0 { n+1 } else { n };
4673 fn count(self) -> usize {
4678 fn nth(&mut self, n: usize) -> Option<Self::Item> {
4679 let (end, overflow) = n.overflowing_mul(self.chunk_size);
4680 if end >= self.v.len() || overflow {
4684 // Can't underflow because of the check above
4685 let end = self.v.len() - end;
4686 let start = match end.checked_sub(self.chunk_size) {
4690 let nth = &self.v[start..end];
4691 self.v = &self.v[0..start];
4697 fn last(self) -> Option<Self::Item> {
4698 if self.v.is_empty() {
4701 let rem = self.v.len() % self.chunk_size;
4702 let end = if rem == 0 { self.chunk_size } else { rem };
4703 Some(&self.v[0..end])
4708 #[stable(feature = "rchunks", since = "1.31.0")]
4709 impl<'a, T> DoubleEndedIterator for RChunks<'a, T> {
4711 fn next_back(&mut self) -> Option<&'a [T]> {
4712 if self.v.is_empty() {
4715 let remainder = self.v.len() % self.chunk_size;
4716 let chunksz = if remainder != 0 { remainder } else { self.chunk_size };
4717 let (fst, snd) = self.v.split_at(chunksz);
4724 fn nth_back(&mut self, n: usize) -> Option<Self::Item> {
4725 let len = self.len();
4730 // can't underflow because `n < len`
4731 let offset_from_end = (len - 1 - n) * self.chunk_size;
4732 let end = self.v.len() - offset_from_end;
4733 let start = end.saturating_sub(self.chunk_size);
4734 let nth_back = &self.v[start..end];
4735 self.v = &self.v[end..];
4741 #[stable(feature = "rchunks", since = "1.31.0")]
4742 impl<T> ExactSizeIterator for RChunks<'_, T> {}
4744 #[unstable(feature = "trusted_len", issue = "37572")]
4745 unsafe impl<T> TrustedLen for RChunks<'_, T> {}
4747 #[stable(feature = "rchunks", since = "1.31.0")]
4748 impl<T> FusedIterator for RChunks<'_, T> {}
4751 #[stable(feature = "rchunks", since = "1.31.0")]
4752 unsafe impl<'a, T> TrustedRandomAccess for RChunks<'a, T> {
4753 unsafe fn get_unchecked(&mut self, i: usize) -> &'a [T] {
4754 let end = self.v.len() - i * self.chunk_size;
4755 let start = match end.checked_sub(self.chunk_size) {
4757 Some(start) => start,
4759 from_raw_parts(self.v.as_ptr().add(start), end - start)
4761 fn may_have_side_effect() -> bool { false }
4764 /// An iterator over a slice in (non-overlapping) mutable chunks (`chunk_size`
4765 /// elements at a time), starting at the end of the slice.
4767 /// When the slice len is not evenly divided by the chunk size, the last slice
4768 /// of the iteration will be the remainder.
4770 /// This struct is created by the [`rchunks_mut`] method on [slices].
4772 /// [`rchunks_mut`]: ../../std/primitive.slice.html#method.rchunks_mut
4773 /// [slices]: ../../std/primitive.slice.html
4775 #[stable(feature = "rchunks", since = "1.31.0")]
4776 pub struct RChunksMut<'a, T:'a> {
4781 #[stable(feature = "rchunks", since = "1.31.0")]
4782 impl<'a, T> Iterator for RChunksMut<'a, T> {
4783 type Item = &'a mut [T];
4786 fn next(&mut self) -> Option<&'a mut [T]> {
4787 if self.v.is_empty() {
4790 let sz = cmp::min(self.v.len(), self.chunk_size);
4791 let tmp = mem::replace(&mut self.v, &mut []);
4792 let tmp_len = tmp.len();
4793 let (head, tail) = tmp.split_at_mut(tmp_len - sz);
4800 fn size_hint(&self) -> (usize, Option<usize>) {
4801 if self.v.is_empty() {
4804 let n = self.v.len() / self.chunk_size;
4805 let rem = self.v.len() % self.chunk_size;
4806 let n = if rem > 0 { n + 1 } else { n };
4812 fn count(self) -> usize {
4817 fn nth(&mut self, n: usize) -> Option<&'a mut [T]> {
4818 let (end, overflow) = n.overflowing_mul(self.chunk_size);
4819 if end >= self.v.len() || overflow {
4823 // Can't underflow because of the check above
4824 let end = self.v.len() - end;
4825 let start = match end.checked_sub(self.chunk_size) {
4829 let tmp = mem::replace(&mut self.v, &mut []);
4830 let (head, tail) = tmp.split_at_mut(start);
4831 let (nth, _) = tail.split_at_mut(end - start);
4838 fn last(self) -> Option<Self::Item> {
4839 if self.v.is_empty() {
4842 let rem = self.v.len() % self.chunk_size;
4843 let end = if rem == 0 { self.chunk_size } else { rem };
4844 Some(&mut self.v[0..end])
4849 #[stable(feature = "rchunks", since = "1.31.0")]
4850 impl<'a, T> DoubleEndedIterator for RChunksMut<'a, T> {
4852 fn next_back(&mut self) -> Option<&'a mut [T]> {
4853 if self.v.is_empty() {
4856 let remainder = self.v.len() % self.chunk_size;
4857 let sz = if remainder != 0 { remainder } else { self.chunk_size };
4858 let tmp = mem::replace(&mut self.v, &mut []);
4859 let (head, tail) = tmp.split_at_mut(sz);
4866 fn nth_back(&mut self, n: usize) -> Option<Self::Item> {
4867 let len = self.len();
4872 // can't underflow because `n < len`
4873 let offset_from_end = (len - 1 - n) * self.chunk_size;
4874 let end = self.v.len() - offset_from_end;
4875 let start = end.saturating_sub(self.chunk_size);
4876 let (tmp, tail) = mem::replace(&mut self.v, &mut []).split_at_mut(end);
4877 let (_, nth_back) = tmp.split_at_mut(start);
4884 #[stable(feature = "rchunks", since = "1.31.0")]
4885 impl<T> ExactSizeIterator for RChunksMut<'_, T> {}
4887 #[unstable(feature = "trusted_len", issue = "37572")]
4888 unsafe impl<T> TrustedLen for RChunksMut<'_, T> {}
4890 #[stable(feature = "rchunks", since = "1.31.0")]
4891 impl<T> FusedIterator for RChunksMut<'_, T> {}
4894 #[stable(feature = "rchunks", since = "1.31.0")]
4895 unsafe impl<'a, T> TrustedRandomAccess for RChunksMut<'a, T> {
4896 unsafe fn get_unchecked(&mut self, i: usize) -> &'a mut [T] {
4897 let end = self.v.len() - i * self.chunk_size;
4898 let start = match end.checked_sub(self.chunk_size) {
4900 Some(start) => start,
4902 from_raw_parts_mut(self.v.as_mut_ptr().add(start), end - start)
4904 fn may_have_side_effect() -> bool { false }
4907 /// An iterator over a slice in (non-overlapping) chunks (`chunk_size` elements at a
4908 /// time), starting at the end of the slice.
4910 /// When the slice len is not evenly divided by the chunk size, the last
4911 /// up to `chunk_size-1` elements will be omitted but can be retrieved from
4912 /// the [`remainder`] function from the iterator.
4914 /// This struct is created by the [`rchunks_exact`] method on [slices].
4916 /// [`rchunks_exact`]: ../../std/primitive.slice.html#method.rchunks_exact
4917 /// [`remainder`]: ../../std/slice/struct.ChunksExact.html#method.remainder
4918 /// [slices]: ../../std/primitive.slice.html
4920 #[stable(feature = "rchunks", since = "1.31.0")]
4921 pub struct RChunksExact<'a, T:'a> {
4927 impl<'a, T> RChunksExact<'a, T> {
4928 /// Returns the remainder of the original slice that is not going to be
4929 /// returned by the iterator. The returned slice has at most `chunk_size-1`
4931 #[stable(feature = "rchunks", since = "1.31.0")]
4932 pub fn remainder(&self) -> &'a [T] {
4937 // FIXME(#26925) Remove in favor of `#[derive(Clone)]`
4938 #[stable(feature = "rchunks", since = "1.31.0")]
4939 impl<'a, T> Clone for RChunksExact<'a, T> {
4940 fn clone(&self) -> RChunksExact<'a, T> {
4944 chunk_size: self.chunk_size,
4949 #[stable(feature = "rchunks", since = "1.31.0")]
4950 impl<'a, T> Iterator for RChunksExact<'a, T> {
4951 type Item = &'a [T];
4954 fn next(&mut self) -> Option<&'a [T]> {
4955 if self.v.len() < self.chunk_size {
4958 let (fst, snd) = self.v.split_at(self.v.len() - self.chunk_size);
4965 fn size_hint(&self) -> (usize, Option<usize>) {
4966 let n = self.v.len() / self.chunk_size;
4971 fn count(self) -> usize {
4976 fn nth(&mut self, n: usize) -> Option<Self::Item> {
4977 let (end, overflow) = n.overflowing_mul(self.chunk_size);
4978 if end >= self.v.len() || overflow {
4982 let (fst, _) = self.v.split_at(self.v.len() - end);
4989 fn last(mut self) -> Option<Self::Item> {
4994 #[stable(feature = "rchunks", since = "1.31.0")]
4995 impl<'a, T> DoubleEndedIterator for RChunksExact<'a, T> {
4997 fn next_back(&mut self) -> Option<&'a [T]> {
4998 if self.v.len() < self.chunk_size {
5001 let (fst, snd) = self.v.split_at(self.chunk_size);
5008 fn nth_back(&mut self, n: usize) -> Option<Self::Item> {
5009 let len = self.len();
5014 // now that we know that `n` corresponds to a chunk,
5015 // none of these operations can underflow/overflow
5016 let offset = (len - n) * self.chunk_size;
5017 let start = self.v.len() - offset;
5018 let end = start + self.chunk_size;
5019 let nth_back = &self.v[start..end];
5020 self.v = &self.v[end..];
5026 #[stable(feature = "rchunks", since = "1.31.0")]
5027 impl<'a, T> ExactSizeIterator for RChunksExact<'a, T> {
5028 fn is_empty(&self) -> bool {
5033 #[unstable(feature = "trusted_len", issue = "37572")]
5034 unsafe impl<T> TrustedLen for RChunksExact<'_, T> {}
5036 #[stable(feature = "rchunks", since = "1.31.0")]
5037 impl<T> FusedIterator for RChunksExact<'_, T> {}
5040 #[stable(feature = "rchunks", since = "1.31.0")]
5041 unsafe impl<'a, T> TrustedRandomAccess for RChunksExact<'a, T> {
5042 unsafe fn get_unchecked(&mut self, i: usize) -> &'a [T] {
5043 let end = self.v.len() - i * self.chunk_size;
5044 let start = end - self.chunk_size;
5045 from_raw_parts(self.v.as_ptr().add(start), self.chunk_size)
5047 fn may_have_side_effect() -> bool { false }
5050 /// An iterator over a slice in (non-overlapping) mutable chunks (`chunk_size`
5051 /// elements at a time), starting at the end of the slice.
5053 /// When the slice len is not evenly divided by the chunk size, the last up to
5054 /// `chunk_size-1` elements will be omitted but can be retrieved from the
5055 /// [`into_remainder`] function from the iterator.
5057 /// This struct is created by the [`rchunks_exact_mut`] method on [slices].
5059 /// [`rchunks_exact_mut`]: ../../std/primitive.slice.html#method.rchunks_exact_mut
5060 /// [`into_remainder`]: ../../std/slice/struct.ChunksExactMut.html#method.into_remainder
5061 /// [slices]: ../../std/primitive.slice.html
5063 #[stable(feature = "rchunks", since = "1.31.0")]
5064 pub struct RChunksExactMut<'a, T:'a> {
5070 impl<'a, T> RChunksExactMut<'a, T> {
5071 /// Returns the remainder of the original slice that is not going to be
5072 /// returned by the iterator. The returned slice has at most `chunk_size-1`
5074 #[stable(feature = "rchunks", since = "1.31.0")]
5075 pub fn into_remainder(self) -> &'a mut [T] {
5080 #[stable(feature = "rchunks", since = "1.31.0")]
5081 impl<'a, T> Iterator for RChunksExactMut<'a, T> {
5082 type Item = &'a mut [T];
5085 fn next(&mut self) -> Option<&'a mut [T]> {
5086 if self.v.len() < self.chunk_size {
5089 let tmp = mem::replace(&mut self.v, &mut []);
5090 let tmp_len = tmp.len();
5091 let (head, tail) = tmp.split_at_mut(tmp_len - self.chunk_size);
5098 fn size_hint(&self) -> (usize, Option<usize>) {
5099 let n = self.v.len() / self.chunk_size;
5104 fn count(self) -> usize {
5109 fn nth(&mut self, n: usize) -> Option<&'a mut [T]> {
5110 let (end, overflow) = n.overflowing_mul(self.chunk_size);
5111 if end >= self.v.len() || overflow {
5115 let tmp = mem::replace(&mut self.v, &mut []);
5116 let tmp_len = tmp.len();
5117 let (fst, _) = tmp.split_at_mut(tmp_len - end);
5124 fn last(mut self) -> Option<Self::Item> {
5129 #[stable(feature = "rchunks", since = "1.31.0")]
5130 impl<'a, T> DoubleEndedIterator for RChunksExactMut<'a, T> {
5132 fn next_back(&mut self) -> Option<&'a mut [T]> {
5133 if self.v.len() < self.chunk_size {
5136 let tmp = mem::replace(&mut self.v, &mut []);
5137 let (head, tail) = tmp.split_at_mut(self.chunk_size);
5144 fn nth_back(&mut self, n: usize) -> Option<Self::Item> {
5145 let len = self.len();
5150 // now that we know that `n` corresponds to a chunk,
5151 // none of these operations can underflow/overflow
5152 let offset = (len - n) * self.chunk_size;
5153 let start = self.v.len() - offset;
5154 let end = start + self.chunk_size;
5155 let (tmp, tail) = mem::replace(&mut self.v, &mut []).split_at_mut(end);
5156 let (_, nth_back) = tmp.split_at_mut(start);
5163 #[stable(feature = "rchunks", since = "1.31.0")]
5164 impl<T> ExactSizeIterator for RChunksExactMut<'_, T> {
5165 fn is_empty(&self) -> bool {
5170 #[unstable(feature = "trusted_len", issue = "37572")]
5171 unsafe impl<T> TrustedLen for RChunksExactMut<'_, T> {}
5173 #[stable(feature = "rchunks", since = "1.31.0")]
5174 impl<T> FusedIterator for RChunksExactMut<'_, T> {}
5177 #[stable(feature = "rchunks", since = "1.31.0")]
5178 unsafe impl<'a, T> TrustedRandomAccess for RChunksExactMut<'a, T> {
5179 unsafe fn get_unchecked(&mut self, i: usize) -> &'a mut [T] {
5180 let end = self.v.len() - i * self.chunk_size;
5181 let start = end - self.chunk_size;
5182 from_raw_parts_mut(self.v.as_mut_ptr().add(start), self.chunk_size)
5184 fn may_have_side_effect() -> bool { false }
5191 /// Forms a slice from a pointer and a length.
5193 /// The `len` argument is the number of **elements**, not the number of bytes.
5197 /// This function is unsafe as there is no guarantee that the given pointer is
5198 /// valid for `len` elements, nor whether the lifetime inferred is a suitable
5199 /// lifetime for the returned slice.
5201 /// `data` must be non-null and aligned, even for zero-length slices. One
5202 /// reason for this is that enum layout optimizations may rely on references
5203 /// (including slices of any length) being aligned and non-null to distinguish
5204 /// them from other data. You can obtain a pointer that is usable as `data`
5205 /// for zero-length slices using [`NonNull::dangling()`].
5207 /// The total size of the slice must be no larger than `isize::MAX` **bytes**
5208 /// in memory. See the safety documentation of [`pointer::offset`].
5212 /// The lifetime for the returned slice is inferred from its usage. To
5213 /// prevent accidental misuse, it's suggested to tie the lifetime to whichever
5214 /// source lifetime is safe in the context, such as by providing a helper
5215 /// function taking the lifetime of a host value for the slice, or by explicit
5223 /// // manifest a slice for a single element
5225 /// let ptr = &x as *const _;
5226 /// let slice = unsafe { slice::from_raw_parts(ptr, 1) };
5227 /// assert_eq!(slice[0], 42);
5230 /// [`NonNull::dangling()`]: ../../std/ptr/struct.NonNull.html#method.dangling
5231 /// [`pointer::offset`]: ../../std/primitive.pointer.html#method.offset
5233 #[stable(feature = "rust1", since = "1.0.0")]
5234 pub unsafe fn from_raw_parts<'a, T>(data: *const T, len: usize) -> &'a [T] {
5235 debug_assert!(data as usize % mem::align_of::<T>() == 0, "attempt to create unaligned slice");
5236 debug_assert!(mem::size_of::<T>().saturating_mul(len) <= isize::MAX as usize,
5237 "attempt to create slice covering half the address space");
5238 &*ptr::slice_from_raw_parts(data, len)
5241 /// Performs the same functionality as [`from_raw_parts`], except that a
5242 /// mutable slice is returned.
5244 /// This function is unsafe for the same reasons as [`from_raw_parts`], as well
5245 /// as not being able to provide a non-aliasing guarantee of the returned
5246 /// mutable slice. `data` must be non-null and aligned even for zero-length
5247 /// slices as with [`from_raw_parts`]. The total size of the slice must be no
5248 /// larger than `isize::MAX` **bytes** in memory.
5250 /// See the documentation of [`from_raw_parts`] for more details.
5252 /// [`from_raw_parts`]: ../../std/slice/fn.from_raw_parts.html
5254 #[stable(feature = "rust1", since = "1.0.0")]
5255 pub unsafe fn from_raw_parts_mut<'a, T>(data: *mut T, len: usize) -> &'a mut [T] {
5256 debug_assert!(data as usize % mem::align_of::<T>() == 0, "attempt to create unaligned slice");
5257 debug_assert!(mem::size_of::<T>().saturating_mul(len) <= isize::MAX as usize,
5258 "attempt to create slice covering half the address space");
5259 &mut *ptr::slice_from_raw_parts_mut(data, len)
5262 /// Converts a reference to T into a slice of length 1 (without copying).
5263 #[stable(feature = "from_ref", since = "1.28.0")]
5264 pub fn from_ref<T>(s: &T) -> &[T] {
5266 from_raw_parts(s, 1)
5270 /// Converts a reference to T into a slice of length 1 (without copying).
5271 #[stable(feature = "from_ref", since = "1.28.0")]
5272 pub fn from_mut<T>(s: &mut T) -> &mut [T] {
5274 from_raw_parts_mut(s, 1)
5278 // This function is public only because there is no other way to unit test heapsort.
5279 #[unstable(feature = "sort_internals", reason = "internal to sort module", issue = "0")]
5281 pub fn heapsort<T, F>(v: &mut [T], mut is_less: F)
5282 where F: FnMut(&T, &T) -> bool
5284 sort::heapsort(v, &mut is_less);
5288 // Comparison traits
5292 /// Calls implementation provided memcmp.
5294 /// Interprets the data as u8.
5296 /// Returns 0 for equal, < 0 for less than and > 0 for greater
5298 // FIXME(#32610): Return type should be c_int
5299 fn memcmp(s1: *const u8, s2: *const u8, n: usize) -> i32;
5302 #[stable(feature = "rust1", since = "1.0.0")]
5303 impl<A, B> PartialEq<[B]> for [A] where A: PartialEq<B> {
5304 fn eq(&self, other: &[B]) -> bool {
5305 SlicePartialEq::equal(self, other)
5308 fn ne(&self, other: &[B]) -> bool {
5309 SlicePartialEq::not_equal(self, other)
5313 #[stable(feature = "rust1", since = "1.0.0")]
5314 impl<T: Eq> Eq for [T] {}
5316 /// Implements comparison of vectors lexicographically.
5317 #[stable(feature = "rust1", since = "1.0.0")]
5318 impl<T: Ord> Ord for [T] {
5319 fn cmp(&self, other: &[T]) -> Ordering {
5320 SliceOrd::compare(self, other)
5324 /// Implements comparison of vectors lexicographically.
5325 #[stable(feature = "rust1", since = "1.0.0")]
5326 impl<T: PartialOrd> PartialOrd for [T] {
5327 fn partial_cmp(&self, other: &[T]) -> Option<Ordering> {
5328 SlicePartialOrd::partial_compare(self, other)
5333 // intermediate trait for specialization of slice's PartialEq
5334 trait SlicePartialEq<B> {
5335 fn equal(&self, other: &[B]) -> bool;
5337 fn not_equal(&self, other: &[B]) -> bool { !self.equal(other) }
5340 // Generic slice equality
5341 impl<A, B> SlicePartialEq<B> for [A]
5342 where A: PartialEq<B>
5344 default fn equal(&self, other: &[B]) -> bool {
5345 if self.len() != other.len() {
5349 for i in 0..self.len() {
5350 if !self[i].eq(&other[i]) {
5359 // Use memcmp for bytewise equality when the types allow
5360 impl<A> SlicePartialEq<A> for [A]
5361 where A: PartialEq<A> + BytewiseEquality
5363 fn equal(&self, other: &[A]) -> bool {
5364 if self.len() != other.len() {
5367 if self.as_ptr() == other.as_ptr() {
5371 let size = mem::size_of_val(self);
5372 memcmp(self.as_ptr() as *const u8,
5373 other.as_ptr() as *const u8, size) == 0
5379 // intermediate trait for specialization of slice's PartialOrd
5380 trait SlicePartialOrd<B> {
5381 fn partial_compare(&self, other: &[B]) -> Option<Ordering>;
5384 impl<A> SlicePartialOrd<A> for [A]
5387 default fn partial_compare(&self, other: &[A]) -> Option<Ordering> {
5388 let l = cmp::min(self.len(), other.len());
5390 // Slice to the loop iteration range to enable bound check
5391 // elimination in the compiler
5392 let lhs = &self[..l];
5393 let rhs = &other[..l];
5396 match lhs[i].partial_cmp(&rhs[i]) {
5397 Some(Ordering::Equal) => (),
5398 non_eq => return non_eq,
5402 self.len().partial_cmp(&other.len())
5406 impl<A> SlicePartialOrd<A> for [A]
5409 default fn partial_compare(&self, other: &[A]) -> Option<Ordering> {
5410 Some(SliceOrd::compare(self, other))
5415 // intermediate trait for specialization of slice's Ord
5417 fn compare(&self, other: &[B]) -> Ordering;
5420 impl<A> SliceOrd<A> for [A]
5423 default fn compare(&self, other: &[A]) -> Ordering {
5424 let l = cmp::min(self.len(), other.len());
5426 // Slice to the loop iteration range to enable bound check
5427 // elimination in the compiler
5428 let lhs = &self[..l];
5429 let rhs = &other[..l];
5432 match lhs[i].cmp(&rhs[i]) {
5433 Ordering::Equal => (),
5434 non_eq => return non_eq,
5438 self.len().cmp(&other.len())
5442 // memcmp compares a sequence of unsigned bytes lexicographically.
5443 // this matches the order we want for [u8], but no others (not even [i8]).
5444 impl SliceOrd<u8> for [u8] {
5446 fn compare(&self, other: &[u8]) -> Ordering {
5447 let order = unsafe {
5448 memcmp(self.as_ptr(), other.as_ptr(),
5449 cmp::min(self.len(), other.len()))
5452 self.len().cmp(&other.len())
5453 } else if order < 0 {
5462 /// Trait implemented for types that can be compared for equality using
5463 /// their bytewise representation
5464 trait BytewiseEquality { }
5466 macro_rules! impl_marker_for {
5467 ($traitname:ident, $($ty:ty)*) => {
5469 impl $traitname for $ty { }
5474 impl_marker_for!(BytewiseEquality,
5475 u8 i8 u16 i16 u32 i32 u64 i64 u128 i128 usize isize char bool);
5478 unsafe impl<'a, T> TrustedRandomAccess for Iter<'a, T> {
5479 unsafe fn get_unchecked(&mut self, i: usize) -> &'a T {
5482 fn may_have_side_effect() -> bool { false }
5486 unsafe impl<'a, T> TrustedRandomAccess for IterMut<'a, T> {
5487 unsafe fn get_unchecked(&mut self, i: usize) -> &'a mut T {
5488 &mut *self.ptr.add(i)
5490 fn may_have_side_effect() -> bool { false }
5493 trait SliceContains: Sized {
5494 fn slice_contains(&self, x: &[Self]) -> bool;
5497 impl<T> SliceContains for T where T: PartialEq {
5498 default fn slice_contains(&self, x: &[Self]) -> bool {
5499 x.iter().any(|y| *y == *self)
5503 impl SliceContains for u8 {
5504 fn slice_contains(&self, x: &[Self]) -> bool {
5505 memchr::memchr(*self, x).is_some()
5509 impl SliceContains for i8 {
5510 fn slice_contains(&self, x: &[Self]) -> bool {
5511 let byte = *self as u8;
5512 let bytes: &[u8] = unsafe { from_raw_parts(x.as_ptr() as *const u8, x.len()) };
5513 memchr::memchr(byte, bytes).is_some()