1 // ignore-tidy-filelength
2 // ignore-tidy-undocumented-unsafe
4 //! Slice management and manipulation.
6 //! For more details see [`std::slice`].
8 //! [`std::slice`]: ../../std/slice/index.html
10 #![stable(feature = "rust1", since = "1.0.0")]
12 // How this module is organized.
14 // The library infrastructure for slices is fairly messy. There's
15 // a lot of stuff defined here. Let's keep it clean.
17 // The layout of this file is thus:
19 // * Inherent methods. This is where most of the slice API resides.
20 // * Implementations of a few common traits with important slice ops.
21 // * Definitions of a bunch of iterators.
23 // * The `raw` and `bytes` submodules.
24 // * Boilerplate trait implementations.
26 use crate::borrow::Borrow;
28 use crate::cmp::Ordering::{self, Equal, Greater, Less};
30 use crate::intrinsics::{assume, exact_div, is_aligned_and_not_null, unchecked_sub};
33 use crate::marker::{self, Copy, Send, Sized, Sync};
35 use crate::ops::{self, FnMut, Range};
36 use crate::option::Option;
37 use crate::option::Option::{None, Some};
38 use crate::ptr::{self, NonNull};
39 use crate::result::Result;
40 use crate::result::Result::{Err, Ok};
43 feature = "slice_internals",
45 reason = "exposed from core to be reused in std; use the memchr crate"
47 /// Pure rust memchr implementation, taken from rust-memchr
60 /// Returns the number of elements in the slice.
65 /// let a = [1, 2, 3];
66 /// assert_eq!(a.len(), 3);
68 #[stable(feature = "rust1", since = "1.0.0")]
69 #[rustc_const_stable(feature = "const_slice_len", since = "1.32.0")]
71 // SAFETY: const sound because we transmute out the length field as a usize (which it must be)
72 #[allow(unused_attributes)]
73 #[allow_internal_unstable(const_fn_union)]
74 pub const fn len(&self) -> usize {
75 unsafe { crate::ptr::Repr { rust: self }.raw.len }
78 /// Returns `true` if the slice has a length of 0.
83 /// let a = [1, 2, 3];
84 /// assert!(!a.is_empty());
86 #[stable(feature = "rust1", since = "1.0.0")]
87 #[rustc_const_stable(feature = "const_slice_is_empty", since = "1.32.0")]
89 pub const fn is_empty(&self) -> bool {
93 /// Returns the first element of the slice, or `None` if it is empty.
98 /// let v = [10, 40, 30];
99 /// assert_eq!(Some(&10), v.first());
101 /// let w: &[i32] = &[];
102 /// assert_eq!(None, w.first());
104 #[stable(feature = "rust1", since = "1.0.0")]
106 pub fn first(&self) -> Option<&T> {
107 if let [first, ..] = self { Some(first) } else { None }
110 /// Returns a mutable pointer to the first element of the slice, or `None` if it is empty.
115 /// let x = &mut [0, 1, 2];
117 /// if let Some(first) = x.first_mut() {
120 /// assert_eq!(x, &[5, 1, 2]);
122 #[stable(feature = "rust1", since = "1.0.0")]
124 pub fn first_mut(&mut self) -> Option<&mut T> {
125 if let [first, ..] = self { Some(first) } else { None }
128 /// Returns the first and all the rest of the elements of the slice, or `None` if it is empty.
133 /// let x = &[0, 1, 2];
135 /// if let Some((first, elements)) = x.split_first() {
136 /// assert_eq!(first, &0);
137 /// assert_eq!(elements, &[1, 2]);
140 #[stable(feature = "slice_splits", since = "1.5.0")]
142 pub fn split_first(&self) -> Option<(&T, &[T])> {
143 if let [first, tail @ ..] = self { Some((first, tail)) } else { None }
146 /// Returns the first and all the rest of the elements of the slice, or `None` if it is empty.
151 /// let x = &mut [0, 1, 2];
153 /// if let Some((first, elements)) = x.split_first_mut() {
158 /// assert_eq!(x, &[3, 4, 5]);
160 #[stable(feature = "slice_splits", since = "1.5.0")]
162 pub fn split_first_mut(&mut self) -> Option<(&mut T, &mut [T])> {
163 if let [first, tail @ ..] = self { Some((first, tail)) } else { None }
166 /// Returns the last and all the rest of the elements of the slice, or `None` if it is empty.
171 /// let x = &[0, 1, 2];
173 /// if let Some((last, elements)) = x.split_last() {
174 /// assert_eq!(last, &2);
175 /// assert_eq!(elements, &[0, 1]);
178 #[stable(feature = "slice_splits", since = "1.5.0")]
180 pub fn split_last(&self) -> Option<(&T, &[T])> {
181 if let [init @ .., last] = self { Some((last, init)) } else { None }
184 /// Returns the last and all the rest of the elements of the slice, or `None` if it is empty.
189 /// let x = &mut [0, 1, 2];
191 /// if let Some((last, elements)) = x.split_last_mut() {
196 /// assert_eq!(x, &[4, 5, 3]);
198 #[stable(feature = "slice_splits", since = "1.5.0")]
200 pub fn split_last_mut(&mut self) -> Option<(&mut T, &mut [T])> {
201 if let [init @ .., last] = self { Some((last, init)) } else { None }
204 /// Returns the last element of the slice, or `None` if it is empty.
209 /// let v = [10, 40, 30];
210 /// assert_eq!(Some(&30), v.last());
212 /// let w: &[i32] = &[];
213 /// assert_eq!(None, w.last());
215 #[stable(feature = "rust1", since = "1.0.0")]
217 pub fn last(&self) -> Option<&T> {
218 if let [.., last] = self { Some(last) } else { None }
221 /// Returns a mutable pointer to the last item in the slice.
226 /// let x = &mut [0, 1, 2];
228 /// if let Some(last) = x.last_mut() {
231 /// assert_eq!(x, &[0, 1, 10]);
233 #[stable(feature = "rust1", since = "1.0.0")]
235 pub fn last_mut(&mut self) -> Option<&mut T> {
236 if let [.., last] = self { Some(last) } else { None }
239 /// Returns a reference to an element or subslice depending on the type of
242 /// - If given a position, returns a reference to the element at that
243 /// position or `None` if out of bounds.
244 /// - If given a range, returns the subslice corresponding to that range,
245 /// or `None` if out of bounds.
250 /// let v = [10, 40, 30];
251 /// assert_eq!(Some(&40), v.get(1));
252 /// assert_eq!(Some(&[10, 40][..]), v.get(0..2));
253 /// assert_eq!(None, v.get(3));
254 /// assert_eq!(None, v.get(0..4));
256 #[stable(feature = "rust1", since = "1.0.0")]
258 pub fn get<I>(&self, index: I) -> Option<&I::Output>
265 /// Returns a mutable reference to an element or subslice depending on the
266 /// type of index (see [`get`]) or `None` if the index is out of bounds.
268 /// [`get`]: #method.get
273 /// let x = &mut [0, 1, 2];
275 /// if let Some(elem) = x.get_mut(1) {
278 /// assert_eq!(x, &[0, 42, 2]);
280 #[stable(feature = "rust1", since = "1.0.0")]
282 pub fn get_mut<I>(&mut self, index: I) -> Option<&mut I::Output>
289 /// Returns a reference to an element or subslice, without doing bounds
292 /// This is generally not recommended, use with caution!
293 /// Calling this method with an out-of-bounds index is *[undefined behavior]*
294 /// even if the resulting reference is not used.
295 /// For a safe alternative see [`get`].
297 /// [`get`]: #method.get
298 /// [undefined behavior]: https://doc.rust-lang.org/reference/behavior-considered-undefined.html
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
315 index.get_unchecked(self)
318 /// Returns a mutable reference to an element or subslice, without doing
321 /// This is generally not recommended, use with caution!
322 /// Calling this method with an out-of-bounds index is *[undefined behavior]*
323 /// even if the resulting reference is not used.
324 /// For a safe alternative see [`get_mut`].
326 /// [`get_mut`]: #method.get_mut
327 /// [undefined behavior]: https://doc.rust-lang.org/reference/behavior-considered-undefined.html
332 /// let x = &mut [1, 2, 4];
335 /// let elem = x.get_unchecked_mut(1);
338 /// assert_eq!(x, &[1, 13, 4]);
340 #[stable(feature = "rust1", since = "1.0.0")]
342 pub unsafe fn get_unchecked_mut<I>(&mut self, index: I) -> &mut I::Output
346 index.get_unchecked_mut(self)
349 /// Returns a raw pointer to the slice's buffer.
351 /// The caller must ensure that the slice outlives the pointer this
352 /// function returns, or else it will end up pointing to garbage.
354 /// The caller must also ensure that the memory the pointer (non-transitively) points to
355 /// is never written to (except inside an `UnsafeCell`) using this pointer or any pointer
356 /// derived from it. If you need to mutate the contents of the slice, use [`as_mut_ptr`].
358 /// Modifying the container referenced by this slice may cause its buffer
359 /// to be reallocated, which would also make any pointers to it invalid.
364 /// let x = &[1, 2, 4];
365 /// let x_ptr = x.as_ptr();
368 /// for i in 0..x.len() {
369 /// assert_eq!(x.get_unchecked(i), &*x_ptr.add(i));
374 /// [`as_mut_ptr`]: #method.as_mut_ptr
375 #[stable(feature = "rust1", since = "1.0.0")]
376 #[rustc_const_stable(feature = "const_slice_as_ptr", since = "1.32.0")]
378 pub const fn as_ptr(&self) -> *const T {
379 self as *const [T] as *const T
382 /// Returns an unsafe mutable pointer to the slice's buffer.
384 /// The caller must ensure that the slice outlives the pointer this
385 /// function returns, or else it will end up pointing to garbage.
387 /// Modifying the container referenced by this slice may cause its buffer
388 /// to be reallocated, which would also make any pointers to it invalid.
393 /// let x = &mut [1, 2, 4];
394 /// let x_ptr = x.as_mut_ptr();
397 /// for i in 0..x.len() {
398 /// *x_ptr.add(i) += 2;
401 /// assert_eq!(x, &[3, 4, 6]);
403 #[stable(feature = "rust1", since = "1.0.0")]
405 pub fn as_mut_ptr(&mut self) -> *mut T {
406 self as *mut [T] as *mut T
409 /// Returns the two raw pointers spanning the slice.
411 /// The returned range is half-open, which means that the end pointer
412 /// points *one past* the last element of the slice. This way, an empty
413 /// slice is represented by two equal pointers, and the difference between
414 /// the two pointers represents the size of the size.
416 /// See [`as_ptr`] for warnings on using these pointers. The end pointer
417 /// requires extra caution, as it does not point to a valid element in the
420 /// This function is useful for interacting with foreign interfaces which
421 /// use two pointers to refer to a range of elements in memory, as is
424 /// It can also be useful to check if a pointer to an element refers to an
425 /// element of this slice:
428 /// #![feature(slice_ptr_range)]
430 /// let a = [1, 2, 3];
431 /// let x = &a[1] as *const _;
432 /// let y = &5 as *const _;
434 /// assert!(a.as_ptr_range().contains(&x));
435 /// assert!(!a.as_ptr_range().contains(&y));
438 /// [`as_ptr`]: #method.as_ptr
439 #[unstable(feature = "slice_ptr_range", issue = "65807")]
441 pub fn as_ptr_range(&self) -> Range<*const T> {
442 // The `add` here is safe, because:
444 // - Both pointers are part of the same object, as pointing directly
445 // past the object also counts.
447 // - The size of the slice is never larger than isize::MAX bytes, as
449 // - https://github.com/rust-lang/unsafe-code-guidelines/issues/102#issuecomment-473340447
450 // - https://doc.rust-lang.org/reference/behavior-considered-undefined.html
451 // - https://doc.rust-lang.org/core/slice/fn.from_raw_parts.html#safety
452 // (This doesn't seem normative yet, but the very same assumption is
453 // made in many places, including the Index implementation of slices.)
455 // - There is no wrapping around involved, as slices do not wrap past
456 // the end of the address space.
458 // See the documentation of pointer::add.
459 let start = self.as_ptr();
460 let end = unsafe { start.add(self.len()) };
464 /// Returns the two unsafe mutable pointers spanning the slice.
466 /// The returned range is half-open, which means that the end pointer
467 /// points *one past* the last element of the slice. This way, an empty
468 /// slice is represented by two equal pointers, and the difference between
469 /// the two pointers represents the size of the size.
471 /// See [`as_mut_ptr`] for warnings on using these pointers. The end
472 /// pointer requires extra caution, as it does not point to a valid element
475 /// This function is useful for interacting with foreign interfaces which
476 /// use two pointers to refer to a range of elements in memory, as is
479 /// [`as_mut_ptr`]: #method.as_mut_ptr
480 #[unstable(feature = "slice_ptr_range", issue = "65807")]
482 pub fn as_mut_ptr_range(&mut self) -> Range<*mut T> {
483 // See as_ptr_range() above for why `add` here is safe.
484 let start = self.as_mut_ptr();
485 let end = unsafe { start.add(self.len()) };
489 /// Swaps two elements in the slice.
493 /// * a - The index of the first element
494 /// * b - The index of the second element
498 /// Panics if `a` or `b` are out of bounds.
503 /// let mut v = ["a", "b", "c", "d"];
505 /// assert!(v == ["a", "d", "c", "b"]);
507 #[stable(feature = "rust1", since = "1.0.0")]
509 pub fn swap(&mut self, a: usize, b: usize) {
511 // Can't take two mutable loans from one vector, so instead just cast
512 // them to their raw pointers to do the swap
513 let pa: *mut T = &mut self[a];
514 let pb: *mut T = &mut self[b];
519 /// Reverses the order of elements in the slice, in place.
524 /// let mut v = [1, 2, 3];
526 /// assert!(v == [3, 2, 1]);
528 #[stable(feature = "rust1", since = "1.0.0")]
530 pub fn reverse(&mut self) {
531 let mut i: usize = 0;
534 // For very small types, all the individual reads in the normal
535 // path perform poorly. We can do better, given efficient unaligned
536 // load/store, by loading a larger chunk and reversing a register.
538 // Ideally LLVM would do this for us, as it knows better than we do
539 // whether unaligned reads are efficient (since that changes between
540 // different ARM versions, for example) and what the best chunk size
541 // would be. Unfortunately, as of LLVM 4.0 (2017-05) it only unrolls
542 // the loop, so we need to do this ourselves. (Hypothesis: reverse
543 // is troublesome because the sides can be aligned differently --
544 // will be, when the length is odd -- so there's no way of emitting
545 // pre- and postludes to use fully-aligned SIMD in the middle.)
547 let fast_unaligned = cfg!(any(target_arch = "x86", target_arch = "x86_64"));
549 if fast_unaligned && mem::size_of::<T>() == 1 {
550 // Use the llvm.bswap intrinsic to reverse u8s in a usize
551 let chunk = mem::size_of::<usize>();
552 while i + chunk - 1 < ln / 2 {
554 let pa: *mut T = self.get_unchecked_mut(i);
555 let pb: *mut T = self.get_unchecked_mut(ln - i - chunk);
556 let va = ptr::read_unaligned(pa as *mut usize);
557 let vb = ptr::read_unaligned(pb as *mut usize);
558 ptr::write_unaligned(pa as *mut usize, vb.swap_bytes());
559 ptr::write_unaligned(pb as *mut usize, va.swap_bytes());
565 if fast_unaligned && mem::size_of::<T>() == 2 {
566 // Use rotate-by-16 to reverse u16s in a u32
567 let chunk = mem::size_of::<u32>() / 2;
568 while i + chunk - 1 < ln / 2 {
570 let pa: *mut T = self.get_unchecked_mut(i);
571 let pb: *mut T = self.get_unchecked_mut(ln - i - chunk);
572 let va = ptr::read_unaligned(pa as *mut u32);
573 let vb = ptr::read_unaligned(pb as *mut u32);
574 ptr::write_unaligned(pa as *mut u32, vb.rotate_left(16));
575 ptr::write_unaligned(pb as *mut u32, va.rotate_left(16));
582 // Unsafe swap to avoid the bounds check in safe swap.
584 let pa: *mut T = self.get_unchecked_mut(i);
585 let pb: *mut T = self.get_unchecked_mut(ln - i - 1);
592 /// Returns an iterator over the slice.
597 /// let x = &[1, 2, 4];
598 /// let mut iterator = x.iter();
600 /// assert_eq!(iterator.next(), Some(&1));
601 /// assert_eq!(iterator.next(), Some(&2));
602 /// assert_eq!(iterator.next(), Some(&4));
603 /// assert_eq!(iterator.next(), None);
605 #[stable(feature = "rust1", since = "1.0.0")]
607 pub fn iter(&self) -> Iter<'_, T> {
609 let ptr = self.as_ptr();
610 assume(!ptr.is_null());
612 let end = if mem::size_of::<T>() == 0 {
613 (ptr as *const u8).wrapping_add(self.len()) as *const T
618 Iter { ptr: NonNull::new_unchecked(ptr as *mut T), end, _marker: marker::PhantomData }
622 /// Returns an iterator that allows modifying each value.
627 /// let x = &mut [1, 2, 4];
628 /// for elem in x.iter_mut() {
631 /// assert_eq!(x, &[3, 4, 6]);
633 #[stable(feature = "rust1", since = "1.0.0")]
635 pub fn iter_mut(&mut self) -> IterMut<'_, T> {
637 let ptr = self.as_mut_ptr();
638 assume(!ptr.is_null());
640 let end = if mem::size_of::<T>() == 0 {
641 (ptr as *mut u8).wrapping_add(self.len()) as *mut T
646 IterMut { ptr: NonNull::new_unchecked(ptr), end, _marker: marker::PhantomData }
650 /// Returns an iterator over all contiguous windows of length
651 /// `size`. The windows overlap. If the slice is shorter than
652 /// `size`, the iterator returns no values.
656 /// Panics if `size` is 0.
661 /// let slice = ['r', 'u', 's', 't'];
662 /// let mut iter = slice.windows(2);
663 /// assert_eq!(iter.next().unwrap(), &['r', 'u']);
664 /// assert_eq!(iter.next().unwrap(), &['u', 's']);
665 /// assert_eq!(iter.next().unwrap(), &['s', 't']);
666 /// assert!(iter.next().is_none());
669 /// If the slice is shorter than `size`:
672 /// let slice = ['f', 'o', 'o'];
673 /// let mut iter = slice.windows(4);
674 /// assert!(iter.next().is_none());
676 #[stable(feature = "rust1", since = "1.0.0")]
678 pub fn windows(&self, size: usize) -> Windows<'_, T> {
680 Windows { v: self, size }
683 /// Returns an iterator over `chunk_size` elements of the slice at a time, starting at the
684 /// beginning of the slice.
686 /// The chunks are slices and do not overlap. If `chunk_size` does not divide the length of the
687 /// slice, then the last chunk will not have length `chunk_size`.
689 /// See [`chunks_exact`] for a variant of this iterator that returns chunks of always exactly
690 /// `chunk_size` elements, and [`rchunks`] for the same iterator but starting at the end of the
695 /// Panics if `chunk_size` is 0.
700 /// let slice = ['l', 'o', 'r', 'e', 'm'];
701 /// let mut iter = slice.chunks(2);
702 /// assert_eq!(iter.next().unwrap(), &['l', 'o']);
703 /// assert_eq!(iter.next().unwrap(), &['r', 'e']);
704 /// assert_eq!(iter.next().unwrap(), &['m']);
705 /// assert!(iter.next().is_none());
708 /// [`chunks_exact`]: #method.chunks_exact
709 /// [`rchunks`]: #method.rchunks
710 #[stable(feature = "rust1", since = "1.0.0")]
712 pub fn chunks(&self, chunk_size: usize) -> Chunks<'_, T> {
713 assert!(chunk_size != 0);
714 Chunks { v: self, chunk_size }
717 /// Returns an iterator over `chunk_size` elements of the slice at a time, starting at the
718 /// beginning of the slice.
720 /// The chunks are mutable slices, and do not overlap. If `chunk_size` does not divide the
721 /// length of the slice, then the last chunk will not have length `chunk_size`.
723 /// See [`chunks_exact_mut`] for a variant of this iterator that returns chunks of always
724 /// exactly `chunk_size` elements, and [`rchunks_mut`] for the same iterator but starting at
725 /// the end of the slice.
729 /// Panics if `chunk_size` is 0.
734 /// let v = &mut [0, 0, 0, 0, 0];
735 /// let mut count = 1;
737 /// for chunk in v.chunks_mut(2) {
738 /// for elem in chunk.iter_mut() {
743 /// assert_eq!(v, &[1, 1, 2, 2, 3]);
746 /// [`chunks_exact_mut`]: #method.chunks_exact_mut
747 /// [`rchunks_mut`]: #method.rchunks_mut
748 #[stable(feature = "rust1", since = "1.0.0")]
750 pub fn chunks_mut(&mut self, chunk_size: usize) -> ChunksMut<'_, T> {
751 assert!(chunk_size != 0);
752 ChunksMut { v: self, chunk_size }
755 /// Returns an iterator over `chunk_size` elements of the slice at a time, starting at the
756 /// beginning of the slice.
758 /// The chunks are slices and do not overlap. If `chunk_size` does not divide the length of the
759 /// slice, then the last up to `chunk_size-1` elements will be omitted and can be retrieved
760 /// from the `remainder` function of the iterator.
762 /// Due to each chunk having exactly `chunk_size` elements, the compiler can often optimize the
763 /// resulting code better than in the case of [`chunks`].
765 /// See [`chunks`] for a variant of this iterator that also returns the remainder as a smaller
766 /// chunk, and [`rchunks_exact`] for the same iterator but starting at the end of the slice.
770 /// Panics if `chunk_size` is 0.
775 /// let slice = ['l', 'o', 'r', 'e', 'm'];
776 /// let mut iter = slice.chunks_exact(2);
777 /// assert_eq!(iter.next().unwrap(), &['l', 'o']);
778 /// assert_eq!(iter.next().unwrap(), &['r', 'e']);
779 /// assert!(iter.next().is_none());
780 /// assert_eq!(iter.remainder(), &['m']);
783 /// [`chunks`]: #method.chunks
784 /// [`rchunks_exact`]: #method.rchunks_exact
785 #[stable(feature = "chunks_exact", since = "1.31.0")]
787 pub fn chunks_exact(&self, chunk_size: usize) -> ChunksExact<'_, T> {
788 assert!(chunk_size != 0);
789 let rem = self.len() % chunk_size;
790 let len = self.len() - rem;
791 let (fst, snd) = self.split_at(len);
792 ChunksExact { v: fst, rem: snd, chunk_size }
795 /// Returns an iterator over `chunk_size` elements of the slice at a time, starting at the
796 /// beginning of the slice.
798 /// The chunks are mutable slices, and do not overlap. If `chunk_size` does not divide the
799 /// length of the slice, then the last up to `chunk_size-1` elements will be omitted and can be
800 /// retrieved from the `into_remainder` function of the iterator.
802 /// Due to each chunk having exactly `chunk_size` elements, the compiler can often optimize the
803 /// resulting code better than in the case of [`chunks_mut`].
805 /// See [`chunks_mut`] for a variant of this iterator that also returns the remainder as a
806 /// smaller chunk, and [`rchunks_exact_mut`] for the same iterator but starting at the end of
811 /// Panics if `chunk_size` is 0.
816 /// let v = &mut [0, 0, 0, 0, 0];
817 /// let mut count = 1;
819 /// for chunk in v.chunks_exact_mut(2) {
820 /// for elem in chunk.iter_mut() {
825 /// assert_eq!(v, &[1, 1, 2, 2, 0]);
828 /// [`chunks_mut`]: #method.chunks_mut
829 /// [`rchunks_exact_mut`]: #method.rchunks_exact_mut
830 #[stable(feature = "chunks_exact", since = "1.31.0")]
832 pub fn chunks_exact_mut(&mut self, chunk_size: usize) -> ChunksExactMut<'_, T> {
833 assert!(chunk_size != 0);
834 let rem = self.len() % chunk_size;
835 let len = self.len() - rem;
836 let (fst, snd) = self.split_at_mut(len);
837 ChunksExactMut { v: fst, rem: snd, chunk_size }
840 /// Returns an iterator over `chunk_size` elements of the slice at a time, starting at the end
843 /// The chunks are slices and do not overlap. If `chunk_size` does not divide the length of the
844 /// slice, then the last chunk will not have length `chunk_size`.
846 /// See [`rchunks_exact`] for a variant of this iterator that returns chunks of always exactly
847 /// `chunk_size` elements, and [`chunks`] for the same iterator but starting at the beginning
852 /// Panics if `chunk_size` is 0.
857 /// let slice = ['l', 'o', 'r', 'e', 'm'];
858 /// let mut iter = slice.rchunks(2);
859 /// assert_eq!(iter.next().unwrap(), &['e', 'm']);
860 /// assert_eq!(iter.next().unwrap(), &['o', 'r']);
861 /// assert_eq!(iter.next().unwrap(), &['l']);
862 /// assert!(iter.next().is_none());
865 /// [`rchunks_exact`]: #method.rchunks_exact
866 /// [`chunks`]: #method.chunks
867 #[stable(feature = "rchunks", since = "1.31.0")]
869 pub fn rchunks(&self, chunk_size: usize) -> RChunks<'_, T> {
870 assert!(chunk_size != 0);
871 RChunks { v: self, chunk_size }
874 /// Returns an iterator over `chunk_size` elements of the slice at a time, starting at the end
877 /// The chunks are mutable slices, and do not overlap. If `chunk_size` does not divide the
878 /// length of the slice, then the last chunk will not have length `chunk_size`.
880 /// See [`rchunks_exact_mut`] for a variant of this iterator that returns chunks of always
881 /// exactly `chunk_size` elements, and [`chunks_mut`] for the same iterator but starting at the
882 /// beginning of the slice.
886 /// Panics if `chunk_size` is 0.
891 /// let v = &mut [0, 0, 0, 0, 0];
892 /// let mut count = 1;
894 /// for chunk in v.rchunks_mut(2) {
895 /// for elem in chunk.iter_mut() {
900 /// assert_eq!(v, &[3, 2, 2, 1, 1]);
903 /// [`rchunks_exact_mut`]: #method.rchunks_exact_mut
904 /// [`chunks_mut`]: #method.chunks_mut
905 #[stable(feature = "rchunks", since = "1.31.0")]
907 pub fn rchunks_mut(&mut self, chunk_size: usize) -> RChunksMut<'_, T> {
908 assert!(chunk_size != 0);
909 RChunksMut { v: self, chunk_size }
912 /// Returns an iterator over `chunk_size` elements of the slice at a time, starting at the
913 /// end of the slice.
915 /// The chunks are slices and do not overlap. If `chunk_size` does not divide the length of the
916 /// slice, then the last up to `chunk_size-1` elements will be omitted and can be retrieved
917 /// from the `remainder` function of the iterator.
919 /// Due to each chunk having exactly `chunk_size` elements, the compiler can often optimize the
920 /// resulting code better than in the case of [`chunks`].
922 /// See [`rchunks`] for a variant of this iterator that also returns the remainder as a smaller
923 /// chunk, and [`chunks_exact`] for the same iterator but starting at the beginning of the
928 /// Panics if `chunk_size` is 0.
933 /// let slice = ['l', 'o', 'r', 'e', 'm'];
934 /// let mut iter = slice.rchunks_exact(2);
935 /// assert_eq!(iter.next().unwrap(), &['e', 'm']);
936 /// assert_eq!(iter.next().unwrap(), &['o', 'r']);
937 /// assert!(iter.next().is_none());
938 /// assert_eq!(iter.remainder(), &['l']);
941 /// [`chunks`]: #method.chunks
942 /// [`rchunks`]: #method.rchunks
943 /// [`chunks_exact`]: #method.chunks_exact
944 #[stable(feature = "rchunks", since = "1.31.0")]
946 pub fn rchunks_exact(&self, chunk_size: usize) -> RChunksExact<'_, T> {
947 assert!(chunk_size != 0);
948 let rem = self.len() % chunk_size;
949 let (fst, snd) = self.split_at(rem);
950 RChunksExact { v: snd, rem: fst, chunk_size }
953 /// Returns an iterator over `chunk_size` elements of the slice at a time, starting at the end
956 /// The chunks are mutable slices, and do not overlap. If `chunk_size` does not divide the
957 /// length of the slice, then the last up to `chunk_size-1` elements will be omitted and can be
958 /// retrieved from the `into_remainder` function of the iterator.
960 /// Due to each chunk having exactly `chunk_size` elements, the compiler can often optimize the
961 /// resulting code better than in the case of [`chunks_mut`].
963 /// See [`rchunks_mut`] for a variant of this iterator that also returns the remainder as a
964 /// smaller chunk, and [`chunks_exact_mut`] for the same iterator but starting at the beginning
969 /// Panics if `chunk_size` is 0.
974 /// let v = &mut [0, 0, 0, 0, 0];
975 /// let mut count = 1;
977 /// for chunk in v.rchunks_exact_mut(2) {
978 /// for elem in chunk.iter_mut() {
983 /// assert_eq!(v, &[0, 2, 2, 1, 1]);
986 /// [`chunks_mut`]: #method.chunks_mut
987 /// [`rchunks_mut`]: #method.rchunks_mut
988 /// [`chunks_exact_mut`]: #method.chunks_exact_mut
989 #[stable(feature = "rchunks", since = "1.31.0")]
991 pub fn rchunks_exact_mut(&mut self, chunk_size: usize) -> RChunksExactMut<'_, T> {
992 assert!(chunk_size != 0);
993 let rem = self.len() % chunk_size;
994 let (fst, snd) = self.split_at_mut(rem);
995 RChunksExactMut { v: snd, rem: fst, chunk_size }
998 /// Divides one slice into two at an index.
1000 /// The first will contain all indices from `[0, mid)` (excluding
1001 /// the index `mid` itself) and the second will contain all
1002 /// indices from `[mid, len)` (excluding the index `len` itself).
1006 /// Panics if `mid > len`.
1011 /// let v = [1, 2, 3, 4, 5, 6];
1014 /// let (left, right) = v.split_at(0);
1015 /// assert!(left == []);
1016 /// assert!(right == [1, 2, 3, 4, 5, 6]);
1020 /// let (left, right) = v.split_at(2);
1021 /// assert!(left == [1, 2]);
1022 /// assert!(right == [3, 4, 5, 6]);
1026 /// let (left, right) = v.split_at(6);
1027 /// assert!(left == [1, 2, 3, 4, 5, 6]);
1028 /// assert!(right == []);
1031 #[stable(feature = "rust1", since = "1.0.0")]
1033 pub fn split_at(&self, mid: usize) -> (&[T], &[T]) {
1034 (&self[..mid], &self[mid..])
1037 /// Divides one mutable slice into two at an index.
1039 /// The first will contain all indices from `[0, mid)` (excluding
1040 /// the index `mid` itself) and the second will contain all
1041 /// indices from `[mid, len)` (excluding the index `len` itself).
1045 /// Panics if `mid > len`.
1050 /// let mut v = [1, 0, 3, 0, 5, 6];
1051 /// // scoped to restrict the lifetime of the borrows
1053 /// let (left, right) = v.split_at_mut(2);
1054 /// assert!(left == [1, 0]);
1055 /// assert!(right == [3, 0, 5, 6]);
1059 /// assert!(v == [1, 2, 3, 4, 5, 6]);
1061 #[stable(feature = "rust1", since = "1.0.0")]
1063 pub fn split_at_mut(&mut self, mid: usize) -> (&mut [T], &mut [T]) {
1064 let len = self.len();
1065 let ptr = self.as_mut_ptr();
1068 assert!(mid <= len);
1070 (from_raw_parts_mut(ptr, mid), from_raw_parts_mut(ptr.add(mid), len - mid))
1074 /// Returns an iterator over subslices separated by elements that match
1075 /// `pred`. The matched element is not contained in the subslices.
1080 /// let slice = [10, 40, 33, 20];
1081 /// let mut iter = slice.split(|num| num % 3 == 0);
1083 /// assert_eq!(iter.next().unwrap(), &[10, 40]);
1084 /// assert_eq!(iter.next().unwrap(), &[20]);
1085 /// assert!(iter.next().is_none());
1088 /// If the first element is matched, an empty slice will be the first item
1089 /// returned by the iterator. Similarly, if the last element in the slice
1090 /// is matched, an empty slice will be the last item returned by the
1094 /// let slice = [10, 40, 33];
1095 /// let mut iter = slice.split(|num| num % 3 == 0);
1097 /// assert_eq!(iter.next().unwrap(), &[10, 40]);
1098 /// assert_eq!(iter.next().unwrap(), &[]);
1099 /// assert!(iter.next().is_none());
1102 /// If two matched elements are directly adjacent, an empty slice will be
1103 /// present between them:
1106 /// let slice = [10, 6, 33, 20];
1107 /// let mut iter = slice.split(|num| num % 3 == 0);
1109 /// assert_eq!(iter.next().unwrap(), &[10]);
1110 /// assert_eq!(iter.next().unwrap(), &[]);
1111 /// assert_eq!(iter.next().unwrap(), &[20]);
1112 /// assert!(iter.next().is_none());
1114 #[stable(feature = "rust1", since = "1.0.0")]
1116 pub fn split<F>(&self, pred: F) -> Split<'_, T, F>
1118 F: FnMut(&T) -> bool,
1120 Split { v: self, pred, finished: false }
1123 /// Returns an iterator over mutable subslices separated by elements that
1124 /// match `pred`. The matched element is not contained in the subslices.
1129 /// let mut v = [10, 40, 30, 20, 60, 50];
1131 /// for group in v.split_mut(|num| *num % 3 == 0) {
1134 /// assert_eq!(v, [1, 40, 30, 1, 60, 1]);
1136 #[stable(feature = "rust1", since = "1.0.0")]
1138 pub fn split_mut<F>(&mut self, pred: F) -> SplitMut<'_, T, F>
1140 F: FnMut(&T) -> bool,
1142 SplitMut { v: self, pred, finished: false }
1145 /// Returns an iterator over subslices separated by elements that match
1146 /// `pred`. The matched element is contained in the end of the previous
1147 /// subslice as a terminator.
1152 /// #![feature(split_inclusive)]
1153 /// let slice = [10, 40, 33, 20];
1154 /// let mut iter = slice.split_inclusive(|num| num % 3 == 0);
1156 /// assert_eq!(iter.next().unwrap(), &[10, 40, 33]);
1157 /// assert_eq!(iter.next().unwrap(), &[20]);
1158 /// assert!(iter.next().is_none());
1161 /// If the last element of the slice is matched,
1162 /// that element will be considered the terminator of the preceding slice.
1163 /// That slice will be the last item returned by the iterator.
1166 /// #![feature(split_inclusive)]
1167 /// let slice = [3, 10, 40, 33];
1168 /// let mut iter = slice.split_inclusive(|num| num % 3 == 0);
1170 /// assert_eq!(iter.next().unwrap(), &[3]);
1171 /// assert_eq!(iter.next().unwrap(), &[10, 40, 33]);
1172 /// assert!(iter.next().is_none());
1174 #[unstable(feature = "split_inclusive", issue = "none")]
1176 pub fn split_inclusive<F>(&self, pred: F) -> SplitInclusive<'_, T, F>
1178 F: FnMut(&T) -> bool,
1180 SplitInclusive { v: self, pred, finished: false }
1183 /// Returns an iterator over mutable subslices separated by elements that
1184 /// match `pred`. The matched element is contained in the previous
1185 /// subslice as a terminator.
1190 /// #![feature(split_inclusive)]
1191 /// let mut v = [10, 40, 30, 20, 60, 50];
1193 /// for group in v.split_inclusive_mut(|num| *num % 3 == 0) {
1194 /// let terminator_idx = group.len()-1;
1195 /// group[terminator_idx] = 1;
1197 /// assert_eq!(v, [10, 40, 1, 20, 1, 1]);
1199 #[unstable(feature = "split_inclusive", issue = "none")]
1201 pub fn split_inclusive_mut<F>(&mut self, pred: F) -> SplitInclusiveMut<'_, T, F>
1203 F: FnMut(&T) -> bool,
1205 SplitInclusiveMut { v: self, pred, finished: false }
1208 /// Returns an iterator over subslices separated by elements that match
1209 /// `pred`, starting at the end of the slice and working backwards.
1210 /// The matched element is not contained in the subslices.
1215 /// let slice = [11, 22, 33, 0, 44, 55];
1216 /// let mut iter = slice.rsplit(|num| *num == 0);
1218 /// assert_eq!(iter.next().unwrap(), &[44, 55]);
1219 /// assert_eq!(iter.next().unwrap(), &[11, 22, 33]);
1220 /// assert_eq!(iter.next(), None);
1223 /// As with `split()`, if the first or last element is matched, an empty
1224 /// slice will be the first (or last) item returned by the iterator.
1227 /// let v = &[0, 1, 1, 2, 3, 5, 8];
1228 /// let mut it = v.rsplit(|n| *n % 2 == 0);
1229 /// assert_eq!(it.next().unwrap(), &[]);
1230 /// assert_eq!(it.next().unwrap(), &[3, 5]);
1231 /// assert_eq!(it.next().unwrap(), &[1, 1]);
1232 /// assert_eq!(it.next().unwrap(), &[]);
1233 /// assert_eq!(it.next(), None);
1235 #[stable(feature = "slice_rsplit", since = "1.27.0")]
1237 pub fn rsplit<F>(&self, pred: F) -> RSplit<'_, T, F>
1239 F: FnMut(&T) -> bool,
1241 RSplit { inner: self.split(pred) }
1244 /// Returns an iterator over mutable subslices separated by elements that
1245 /// match `pred`, starting at the end of the slice and working
1246 /// backwards. The matched element is not contained in the subslices.
1251 /// let mut v = [100, 400, 300, 200, 600, 500];
1253 /// let mut count = 0;
1254 /// for group in v.rsplit_mut(|num| *num % 3 == 0) {
1256 /// group[0] = count;
1258 /// assert_eq!(v, [3, 400, 300, 2, 600, 1]);
1261 #[stable(feature = "slice_rsplit", since = "1.27.0")]
1263 pub fn rsplit_mut<F>(&mut self, pred: F) -> RSplitMut<'_, T, F>
1265 F: FnMut(&T) -> bool,
1267 RSplitMut { inner: self.split_mut(pred) }
1270 /// Returns an iterator over subslices separated by elements that match
1271 /// `pred`, limited to returning at most `n` items. The matched element is
1272 /// not contained in the subslices.
1274 /// The last element returned, if any, will contain the remainder of the
1279 /// Print the slice split once by numbers divisible by 3 (i.e., `[10, 40]`,
1280 /// `[20, 60, 50]`):
1283 /// let v = [10, 40, 30, 20, 60, 50];
1285 /// for group in v.splitn(2, |num| *num % 3 == 0) {
1286 /// println!("{:?}", group);
1289 #[stable(feature = "rust1", since = "1.0.0")]
1291 pub fn splitn<F>(&self, n: usize, pred: F) -> SplitN<'_, T, F>
1293 F: FnMut(&T) -> bool,
1295 SplitN { inner: GenericSplitN { iter: self.split(pred), count: n } }
1298 /// Returns an iterator over subslices separated by elements that match
1299 /// `pred`, limited to returning at most `n` items. The matched element is
1300 /// not contained in the subslices.
1302 /// The last element returned, if any, will contain the remainder of the
1308 /// let mut v = [10, 40, 30, 20, 60, 50];
1310 /// for group in v.splitn_mut(2, |num| *num % 3 == 0) {
1313 /// assert_eq!(v, [1, 40, 30, 1, 60, 50]);
1315 #[stable(feature = "rust1", since = "1.0.0")]
1317 pub fn splitn_mut<F>(&mut self, n: usize, pred: F) -> SplitNMut<'_, T, F>
1319 F: FnMut(&T) -> bool,
1321 SplitNMut { inner: GenericSplitN { iter: self.split_mut(pred), count: n } }
1324 /// Returns an iterator over subslices separated by elements that match
1325 /// `pred` limited to returning at most `n` items. This starts at the end of
1326 /// the slice and works backwards. The matched element is not contained in
1329 /// The last element returned, if any, will contain the remainder of the
1334 /// Print the slice split once, starting from the end, by numbers divisible
1335 /// by 3 (i.e., `[50]`, `[10, 40, 30, 20]`):
1338 /// let v = [10, 40, 30, 20, 60, 50];
1340 /// for group in v.rsplitn(2, |num| *num % 3 == 0) {
1341 /// println!("{:?}", group);
1344 #[stable(feature = "rust1", since = "1.0.0")]
1346 pub fn rsplitn<F>(&self, n: usize, pred: F) -> RSplitN<'_, T, F>
1348 F: FnMut(&T) -> bool,
1350 RSplitN { inner: GenericSplitN { iter: self.rsplit(pred), count: n } }
1353 /// Returns an iterator over subslices separated by elements that match
1354 /// `pred` limited to returning at most `n` items. This starts at the end of
1355 /// the slice and works backwards. The matched element is not contained in
1358 /// The last element returned, if any, will contain the remainder of the
1364 /// let mut s = [10, 40, 30, 20, 60, 50];
1366 /// for group in s.rsplitn_mut(2, |num| *num % 3 == 0) {
1369 /// assert_eq!(s, [1, 40, 30, 20, 60, 1]);
1371 #[stable(feature = "rust1", since = "1.0.0")]
1373 pub fn rsplitn_mut<F>(&mut self, n: usize, pred: F) -> RSplitNMut<'_, T, F>
1375 F: FnMut(&T) -> bool,
1377 RSplitNMut { inner: GenericSplitN { iter: self.rsplit_mut(pred), count: n } }
1380 /// Returns `true` if the slice contains an element with the given value.
1385 /// let v = [10, 40, 30];
1386 /// assert!(v.contains(&30));
1387 /// assert!(!v.contains(&50));
1390 /// If you do not have an `&T`, but just an `&U` such that `T: Borrow<U>`
1391 /// (e.g. `String: Borrow<str>`), you can use `iter().any`:
1394 /// let v = [String::from("hello"), String::from("world")]; // slice of `String`
1395 /// assert!(v.iter().any(|e| e == "hello")); // search with `&str`
1396 /// assert!(!v.iter().any(|e| e == "hi"));
1398 #[stable(feature = "rust1", since = "1.0.0")]
1399 pub fn contains(&self, x: &T) -> bool
1403 x.slice_contains(self)
1406 /// Returns `true` if `needle` is a prefix of the slice.
1411 /// let v = [10, 40, 30];
1412 /// assert!(v.starts_with(&[10]));
1413 /// assert!(v.starts_with(&[10, 40]));
1414 /// assert!(!v.starts_with(&[50]));
1415 /// assert!(!v.starts_with(&[10, 50]));
1418 /// Always returns `true` if `needle` is an empty slice:
1421 /// let v = &[10, 40, 30];
1422 /// assert!(v.starts_with(&[]));
1423 /// let v: &[u8] = &[];
1424 /// assert!(v.starts_with(&[]));
1426 #[stable(feature = "rust1", since = "1.0.0")]
1427 pub fn starts_with(&self, needle: &[T]) -> bool
1431 let n = needle.len();
1432 self.len() >= n && needle == &self[..n]
1435 /// Returns `true` if `needle` is a suffix of the slice.
1440 /// let v = [10, 40, 30];
1441 /// assert!(v.ends_with(&[30]));
1442 /// assert!(v.ends_with(&[40, 30]));
1443 /// assert!(!v.ends_with(&[50]));
1444 /// assert!(!v.ends_with(&[50, 30]));
1447 /// Always returns `true` if `needle` is an empty slice:
1450 /// let v = &[10, 40, 30];
1451 /// assert!(v.ends_with(&[]));
1452 /// let v: &[u8] = &[];
1453 /// assert!(v.ends_with(&[]));
1455 #[stable(feature = "rust1", since = "1.0.0")]
1456 pub fn ends_with(&self, needle: &[T]) -> bool
1460 let (m, n) = (self.len(), needle.len());
1461 m >= n && needle == &self[m - n..]
1464 /// Binary searches this sorted slice for a given element.
1466 /// If the value is found then [`Result::Ok`] is returned, containing the
1467 /// index of the matching element. If there are multiple matches, then any
1468 /// one of the matches could be returned. If the value is not found then
1469 /// [`Result::Err`] is returned, containing the index where a matching
1470 /// element could be inserted while maintaining sorted order.
1474 /// Looks up a series of four elements. The first is found, with a
1475 /// uniquely determined position; the second and third are not
1476 /// found; the fourth could match any position in `[1, 4]`.
1479 /// let s = [0, 1, 1, 1, 1, 2, 3, 5, 8, 13, 21, 34, 55];
1481 /// assert_eq!(s.binary_search(&13), Ok(9));
1482 /// assert_eq!(s.binary_search(&4), Err(7));
1483 /// assert_eq!(s.binary_search(&100), Err(13));
1484 /// let r = s.binary_search(&1);
1485 /// assert!(match r { Ok(1..=4) => true, _ => false, });
1488 /// If you want to insert an item to a sorted vector, while maintaining
1492 /// let mut s = vec![0, 1, 1, 1, 1, 2, 3, 5, 8, 13, 21, 34, 55];
1494 /// let idx = s.binary_search(&num).unwrap_or_else(|x| x);
1495 /// s.insert(idx, num);
1496 /// assert_eq!(s, [0, 1, 1, 1, 1, 2, 3, 5, 8, 13, 21, 34, 42, 55]);
1498 #[stable(feature = "rust1", since = "1.0.0")]
1499 pub fn binary_search(&self, x: &T) -> Result<usize, usize>
1503 self.binary_search_by(|p| p.cmp(x))
1506 /// Binary searches this sorted slice with a comparator function.
1508 /// The comparator function should implement an order consistent
1509 /// with the sort order of the underlying slice, returning an
1510 /// order code that indicates whether its argument is `Less`,
1511 /// `Equal` or `Greater` the desired target.
1513 /// If the value is found then [`Result::Ok`] is returned, containing the
1514 /// index of the matching element. If there are multiple matches, then any
1515 /// one of the matches could be returned. If the value is not found then
1516 /// [`Result::Err`] is returned, containing the index where a matching
1517 /// element could be inserted while maintaining sorted order.
1521 /// Looks up a series of four elements. The first is found, with a
1522 /// uniquely determined position; the second and third are not
1523 /// found; the fourth could match any position in `[1, 4]`.
1526 /// let s = [0, 1, 1, 1, 1, 2, 3, 5, 8, 13, 21, 34, 55];
1529 /// assert_eq!(s.binary_search_by(|probe| probe.cmp(&seek)), Ok(9));
1531 /// assert_eq!(s.binary_search_by(|probe| probe.cmp(&seek)), Err(7));
1533 /// assert_eq!(s.binary_search_by(|probe| probe.cmp(&seek)), Err(13));
1535 /// let r = s.binary_search_by(|probe| probe.cmp(&seek));
1536 /// assert!(match r { Ok(1..=4) => true, _ => false, });
1538 #[stable(feature = "rust1", since = "1.0.0")]
1540 pub fn binary_search_by<'a, F>(&'a self, mut f: F) -> Result<usize, usize>
1542 F: FnMut(&'a T) -> Ordering,
1545 let mut size = s.len();
1549 let mut base = 0usize;
1551 let half = size / 2;
1552 let mid = base + half;
1553 // mid is always in [0, size), that means mid is >= 0 and < size.
1554 // mid >= 0: by definition
1555 // mid < size: mid = size / 2 + size / 4 + size / 8 ...
1556 let cmp = f(unsafe { s.get_unchecked(mid) });
1557 base = if cmp == Greater { base } else { mid };
1560 // base is always in [0, size) because base <= mid.
1561 let cmp = f(unsafe { s.get_unchecked(base) });
1562 if cmp == Equal { Ok(base) } else { Err(base + (cmp == Less) as usize) }
1565 /// Binary searches this sorted slice with a key extraction function.
1567 /// Assumes that the slice is sorted by the key, for instance with
1568 /// [`sort_by_key`] using the same key extraction function.
1570 /// If the value is found then [`Result::Ok`] is returned, containing the
1571 /// index of the matching element. If there are multiple matches, then any
1572 /// one of the matches could be returned. If the value is not found then
1573 /// [`Result::Err`] is returned, containing the index where a matching
1574 /// element could be inserted while maintaining sorted order.
1576 /// [`sort_by_key`]: #method.sort_by_key
1580 /// Looks up a series of four elements in a slice of pairs sorted by
1581 /// their second elements. The first is found, with a uniquely
1582 /// determined position; the second and third are not found; the
1583 /// fourth could match any position in `[1, 4]`.
1586 /// let s = [(0, 0), (2, 1), (4, 1), (5, 1), (3, 1),
1587 /// (1, 2), (2, 3), (4, 5), (5, 8), (3, 13),
1588 /// (1, 21), (2, 34), (4, 55)];
1590 /// assert_eq!(s.binary_search_by_key(&13, |&(a,b)| b), Ok(9));
1591 /// assert_eq!(s.binary_search_by_key(&4, |&(a,b)| b), Err(7));
1592 /// assert_eq!(s.binary_search_by_key(&100, |&(a,b)| b), Err(13));
1593 /// let r = s.binary_search_by_key(&1, |&(a,b)| b);
1594 /// assert!(match r { Ok(1..=4) => true, _ => false, });
1596 #[stable(feature = "slice_binary_search_by_key", since = "1.10.0")]
1598 pub fn binary_search_by_key<'a, B, F>(&'a self, b: &B, mut f: F) -> Result<usize, usize>
1600 F: FnMut(&'a T) -> B,
1603 self.binary_search_by(|k| f(k).cmp(b))
1606 /// Sorts the slice, but may not preserve the order of equal elements.
1608 /// This sort is unstable (i.e., may reorder equal elements), in-place
1609 /// (i.e., does not allocate), and `O(n log n)` worst-case.
1611 /// # Current implementation
1613 /// The current algorithm is based on [pattern-defeating quicksort][pdqsort] by Orson Peters,
1614 /// which combines the fast average case of randomized quicksort with the fast worst case of
1615 /// heapsort, while achieving linear time on slices with certain patterns. It uses some
1616 /// randomization to avoid degenerate cases, but with a fixed seed to always provide
1617 /// deterministic behavior.
1619 /// It is typically faster than stable sorting, except in a few special cases, e.g., when the
1620 /// slice consists of several concatenated sorted sequences.
1625 /// let mut v = [-5, 4, 1, -3, 2];
1627 /// v.sort_unstable();
1628 /// assert!(v == [-5, -3, 1, 2, 4]);
1631 /// [pdqsort]: https://github.com/orlp/pdqsort
1632 #[stable(feature = "sort_unstable", since = "1.20.0")]
1634 pub fn sort_unstable(&mut self)
1638 sort::quicksort(self, |a, b| a.lt(b));
1641 /// Sorts the slice with a comparator function, but may not preserve the order of equal
1644 /// This sort is unstable (i.e., may reorder equal elements), in-place
1645 /// (i.e., does not allocate), and `O(n log n)` worst-case.
1647 /// The comparator function must define a total ordering for the elements in the slice. If
1648 /// the ordering is not total, the order of the elements is unspecified. An order is a
1649 /// total order if it is (for all a, b and c):
1651 /// * total and antisymmetric: exactly one of a < b, a == b or a > b is true; and
1652 /// * transitive, a < b and b < c implies a < c. The same must hold for both == and >.
1654 /// For example, while [`f64`] doesn't implement [`Ord`] because `NaN != NaN`, we can use
1655 /// `partial_cmp` as our sort function when we know the slice doesn't contain a `NaN`.
1658 /// let mut floats = [5f64, 4.0, 1.0, 3.0, 2.0];
1659 /// floats.sort_by(|a, b| a.partial_cmp(b).unwrap());
1660 /// assert_eq!(floats, [1.0, 2.0, 3.0, 4.0, 5.0]);
1663 /// # Current implementation
1665 /// The current algorithm is based on [pattern-defeating quicksort][pdqsort] by Orson Peters,
1666 /// which combines the fast average case of randomized quicksort with the fast worst case of
1667 /// heapsort, while achieving linear time on slices with certain patterns. It uses some
1668 /// randomization to avoid degenerate cases, but with a fixed seed to always provide
1669 /// deterministic behavior.
1671 /// It is typically faster than stable sorting, except in a few special cases, e.g., when the
1672 /// slice consists of several concatenated sorted sequences.
1677 /// let mut v = [5, 4, 1, 3, 2];
1678 /// v.sort_unstable_by(|a, b| a.cmp(b));
1679 /// assert!(v == [1, 2, 3, 4, 5]);
1681 /// // reverse sorting
1682 /// v.sort_unstable_by(|a, b| b.cmp(a));
1683 /// assert!(v == [5, 4, 3, 2, 1]);
1686 /// [pdqsort]: https://github.com/orlp/pdqsort
1687 #[stable(feature = "sort_unstable", since = "1.20.0")]
1689 pub fn sort_unstable_by<F>(&mut self, mut compare: F)
1691 F: FnMut(&T, &T) -> Ordering,
1693 sort::quicksort(self, |a, b| compare(a, b) == Ordering::Less);
1696 /// Sorts the slice with a key extraction function, but may not preserve the order of equal
1699 /// This sort is unstable (i.e., may reorder equal elements), in-place
1700 /// (i.e., does not allocate), and `O(m n log(m n))` worst-case, where the key function is
1703 /// # Current implementation
1705 /// The current algorithm is based on [pattern-defeating quicksort][pdqsort] by Orson Peters,
1706 /// which combines the fast average case of randomized quicksort with the fast worst case of
1707 /// heapsort, while achieving linear time on slices with certain patterns. It uses some
1708 /// randomization to avoid degenerate cases, but with a fixed seed to always provide
1709 /// deterministic behavior.
1711 /// Due to its key calling strategy, [`sort_unstable_by_key`](#method.sort_unstable_by_key)
1712 /// is likely to be slower than [`sort_by_cached_key`](#method.sort_by_cached_key) in
1713 /// cases where the key function is expensive.
1718 /// let mut v = [-5i32, 4, 1, -3, 2];
1720 /// v.sort_unstable_by_key(|k| k.abs());
1721 /// assert!(v == [1, 2, -3, 4, -5]);
1724 /// [pdqsort]: https://github.com/orlp/pdqsort
1725 #[stable(feature = "sort_unstable", since = "1.20.0")]
1727 pub fn sort_unstable_by_key<K, F>(&mut self, mut f: F)
1732 sort::quicksort(self, |a, b| f(a).lt(&f(b)));
1735 /// Reorder the slice such that the element at `index` is at its final sorted position.
1737 /// This reordering has the additional property that any value at position `i < index` will be
1738 /// less than or equal to any value at a position `j > index`. Additionally, this reordering is
1739 /// unstable (i.e. any number of equal elements may end up at position `index`), in-place
1740 /// (i.e. does not allocate), and `O(n)` worst-case. This function is also/ known as "kth
1741 /// element" in other libraries. It returns a triplet of the following values: all elements less
1742 /// than the one at the given index, the value at the given index, and all elements greater than
1743 /// the one at the given index.
1745 /// # Current implementation
1747 /// The current algorithm is based on the quickselect portion of the same quicksort algorithm
1748 /// used for [`sort_unstable`].
1750 /// [`sort_unstable`]: #method.sort_unstable
1754 /// Panics when `index >= len()`, meaning it always panics on empty slices.
1759 /// #![feature(slice_partition_at_index)]
1761 /// let mut v = [-5i32, 4, 1, -3, 2];
1763 /// // Find the median
1764 /// v.partition_at_index(2);
1766 /// // We are only guaranteed the slice will be one of the following, based on the way we sort
1767 /// // about the specified index.
1768 /// assert!(v == [-3, -5, 1, 2, 4] ||
1769 /// v == [-5, -3, 1, 2, 4] ||
1770 /// v == [-3, -5, 1, 4, 2] ||
1771 /// v == [-5, -3, 1, 4, 2]);
1773 #[unstable(feature = "slice_partition_at_index", issue = "55300")]
1775 pub fn partition_at_index(&mut self, index: usize) -> (&mut [T], &mut T, &mut [T])
1779 let mut f = |a: &T, b: &T| a.lt(b);
1780 sort::partition_at_index(self, index, &mut f)
1783 /// Reorder the slice with a comparator function such that the element at `index` is at its
1784 /// final sorted position.
1786 /// This reordering has the additional property that any value at position `i < index` will be
1787 /// less than or equal to any value at a position `j > index` using the comparator function.
1788 /// Additionally, this reordering is unstable (i.e. any number of equal elements may end up at
1789 /// position `index`), in-place (i.e. does not allocate), and `O(n)` worst-case. This function
1790 /// is also known as "kth element" in other libraries. It returns a triplet of the following
1791 /// values: all elements less than the one at the given index, the value at the given index,
1792 /// and all elements greater than the one at the given index, using the provided comparator
1795 /// # Current implementation
1797 /// The current algorithm is based on the quickselect portion of the same quicksort algorithm
1798 /// used for [`sort_unstable`].
1800 /// [`sort_unstable`]: #method.sort_unstable
1804 /// Panics when `index >= len()`, meaning it always panics on empty slices.
1809 /// #![feature(slice_partition_at_index)]
1811 /// let mut v = [-5i32, 4, 1, -3, 2];
1813 /// // Find the median as if the slice were sorted in descending order.
1814 /// v.partition_at_index_by(2, |a, b| b.cmp(a));
1816 /// // We are only guaranteed the slice will be one of the following, based on the way we sort
1817 /// // about the specified index.
1818 /// assert!(v == [2, 4, 1, -5, -3] ||
1819 /// v == [2, 4, 1, -3, -5] ||
1820 /// v == [4, 2, 1, -5, -3] ||
1821 /// v == [4, 2, 1, -3, -5]);
1823 #[unstable(feature = "slice_partition_at_index", issue = "55300")]
1825 pub fn partition_at_index_by<F>(
1829 ) -> (&mut [T], &mut T, &mut [T])
1831 F: FnMut(&T, &T) -> Ordering,
1833 let mut f = |a: &T, b: &T| compare(a, b) == Less;
1834 sort::partition_at_index(self, index, &mut f)
1837 /// Reorder the slice with a key extraction function such that the element at `index` is at its
1838 /// final sorted position.
1840 /// This reordering has the additional property that any value at position `i < index` will be
1841 /// less than or equal to any value at a position `j > index` using the key extraction function.
1842 /// Additionally, this reordering is unstable (i.e. any number of equal elements may end up at
1843 /// position `index`), in-place (i.e. does not allocate), and `O(n)` worst-case. This function
1844 /// is also known as "kth element" in other libraries. It returns a triplet of the following
1845 /// values: all elements less than the one at the given index, the value at the given index, and
1846 /// all elements greater than the one at the given index, using the provided key extraction
1849 /// # Current implementation
1851 /// The current algorithm is based on the quickselect portion of the same quicksort algorithm
1852 /// used for [`sort_unstable`].
1854 /// [`sort_unstable`]: #method.sort_unstable
1858 /// Panics when `index >= len()`, meaning it always panics on empty slices.
1863 /// #![feature(slice_partition_at_index)]
1865 /// let mut v = [-5i32, 4, 1, -3, 2];
1867 /// // Return the median as if the array were sorted according to absolute value.
1868 /// v.partition_at_index_by_key(2, |a| a.abs());
1870 /// // We are only guaranteed the slice will be one of the following, based on the way we sort
1871 /// // about the specified index.
1872 /// assert!(v == [1, 2, -3, 4, -5] ||
1873 /// v == [1, 2, -3, -5, 4] ||
1874 /// v == [2, 1, -3, 4, -5] ||
1875 /// v == [2, 1, -3, -5, 4]);
1877 #[unstable(feature = "slice_partition_at_index", issue = "55300")]
1879 pub fn partition_at_index_by_key<K, F>(
1883 ) -> (&mut [T], &mut T, &mut [T])
1888 let mut g = |a: &T, b: &T| f(a).lt(&f(b));
1889 sort::partition_at_index(self, index, &mut g)
1892 /// Moves all consecutive repeated elements to the end of the slice according to the
1893 /// [`PartialEq`] trait implementation.
1895 /// Returns two slices. The first contains no consecutive repeated elements.
1896 /// The second contains all the duplicates in no specified order.
1898 /// If the slice is sorted, the first returned slice contains no duplicates.
1903 /// #![feature(slice_partition_dedup)]
1905 /// let mut slice = [1, 2, 2, 3, 3, 2, 1, 1];
1907 /// let (dedup, duplicates) = slice.partition_dedup();
1909 /// assert_eq!(dedup, [1, 2, 3, 2, 1]);
1910 /// assert_eq!(duplicates, [2, 3, 1]);
1912 #[unstable(feature = "slice_partition_dedup", issue = "54279")]
1914 pub fn partition_dedup(&mut self) -> (&mut [T], &mut [T])
1918 self.partition_dedup_by(|a, b| a == b)
1921 /// Moves all but the first of consecutive elements to the end of the slice satisfying
1922 /// a given equality relation.
1924 /// Returns two slices. The first contains no consecutive repeated elements.
1925 /// The second contains all the duplicates in no specified order.
1927 /// The `same_bucket` function is passed references to two elements from the slice and
1928 /// must determine if the elements compare equal. The elements are passed in opposite order
1929 /// from their order in the slice, so if `same_bucket(a, b)` returns `true`, `a` is moved
1930 /// at the end of the slice.
1932 /// If the slice is sorted, the first returned slice contains no duplicates.
1937 /// #![feature(slice_partition_dedup)]
1939 /// let mut slice = ["foo", "Foo", "BAZ", "Bar", "bar", "baz", "BAZ"];
1941 /// let (dedup, duplicates) = slice.partition_dedup_by(|a, b| a.eq_ignore_ascii_case(b));
1943 /// assert_eq!(dedup, ["foo", "BAZ", "Bar", "baz"]);
1944 /// assert_eq!(duplicates, ["bar", "Foo", "BAZ"]);
1946 #[unstable(feature = "slice_partition_dedup", issue = "54279")]
1948 pub fn partition_dedup_by<F>(&mut self, mut same_bucket: F) -> (&mut [T], &mut [T])
1950 F: FnMut(&mut T, &mut T) -> bool,
1952 // Although we have a mutable reference to `self`, we cannot make
1953 // *arbitrary* changes. The `same_bucket` calls could panic, so we
1954 // must ensure that the slice is in a valid state at all times.
1956 // The way that we handle this is by using swaps; we iterate
1957 // over all the elements, swapping as we go so that at the end
1958 // the elements we wish to keep are in the front, and those we
1959 // wish to reject are at the back. We can then split the slice.
1960 // This operation is still O(n).
1962 // Example: We start in this state, where `r` represents "next
1963 // read" and `w` represents "next_write`.
1966 // +---+---+---+---+---+---+
1967 // | 0 | 1 | 1 | 2 | 3 | 3 |
1968 // +---+---+---+---+---+---+
1971 // Comparing self[r] against self[w-1], this is not a duplicate, so
1972 // we swap self[r] and self[w] (no effect as r==w) and then increment both
1973 // r and w, leaving us with:
1976 // +---+---+---+---+---+---+
1977 // | 0 | 1 | 1 | 2 | 3 | 3 |
1978 // +---+---+---+---+---+---+
1981 // Comparing self[r] against self[w-1], this value is a duplicate,
1982 // so we increment `r` but leave everything else unchanged:
1985 // +---+---+---+---+---+---+
1986 // | 0 | 1 | 1 | 2 | 3 | 3 |
1987 // +---+---+---+---+---+---+
1990 // Comparing self[r] against self[w-1], this is not a duplicate,
1991 // so swap self[r] and self[w] and advance r and w:
1994 // +---+---+---+---+---+---+
1995 // | 0 | 1 | 2 | 1 | 3 | 3 |
1996 // +---+---+---+---+---+---+
1999 // Not a duplicate, repeat:
2002 // +---+---+---+---+---+---+
2003 // | 0 | 1 | 2 | 3 | 1 | 3 |
2004 // +---+---+---+---+---+---+
2007 // Duplicate, advance r. End of slice. Split at w.
2009 let len = self.len();
2011 return (self, &mut []);
2014 let ptr = self.as_mut_ptr();
2015 let mut next_read: usize = 1;
2016 let mut next_write: usize = 1;
2019 // Avoid bounds checks by using raw pointers.
2020 while next_read < len {
2021 let ptr_read = ptr.add(next_read);
2022 let prev_ptr_write = ptr.add(next_write - 1);
2023 if !same_bucket(&mut *ptr_read, &mut *prev_ptr_write) {
2024 if next_read != next_write {
2025 let ptr_write = prev_ptr_write.offset(1);
2026 mem::swap(&mut *ptr_read, &mut *ptr_write);
2034 self.split_at_mut(next_write)
2037 /// Moves all but the first of consecutive elements to the end of the slice that resolve
2038 /// to the same key.
2040 /// Returns two slices. The first contains no consecutive repeated elements.
2041 /// The second contains all the duplicates in no specified order.
2043 /// If the slice is sorted, the first returned slice contains no duplicates.
2048 /// #![feature(slice_partition_dedup)]
2050 /// let mut slice = [10, 20, 21, 30, 30, 20, 11, 13];
2052 /// let (dedup, duplicates) = slice.partition_dedup_by_key(|i| *i / 10);
2054 /// assert_eq!(dedup, [10, 20, 30, 20, 11]);
2055 /// assert_eq!(duplicates, [21, 30, 13]);
2057 #[unstable(feature = "slice_partition_dedup", issue = "54279")]
2059 pub fn partition_dedup_by_key<K, F>(&mut self, mut key: F) -> (&mut [T], &mut [T])
2061 F: FnMut(&mut T) -> K,
2064 self.partition_dedup_by(|a, b| key(a) == key(b))
2067 /// Rotates the slice in-place such that the first `mid` elements of the
2068 /// slice move to the end while the last `self.len() - mid` elements move to
2069 /// the front. After calling `rotate_left`, the element previously at index
2070 /// `mid` will become the first element in the slice.
2074 /// This function will panic if `mid` is greater than the length of the
2075 /// slice. Note that `mid == self.len()` does _not_ panic and is a no-op
2080 /// Takes linear (in `self.len()`) time.
2085 /// let mut a = ['a', 'b', 'c', 'd', 'e', 'f'];
2086 /// a.rotate_left(2);
2087 /// assert_eq!(a, ['c', 'd', 'e', 'f', 'a', 'b']);
2090 /// Rotating a subslice:
2093 /// let mut a = ['a', 'b', 'c', 'd', 'e', 'f'];
2094 /// a[1..5].rotate_left(1);
2095 /// assert_eq!(a, ['a', 'c', 'd', 'e', 'b', 'f']);
2097 #[stable(feature = "slice_rotate", since = "1.26.0")]
2098 pub fn rotate_left(&mut self, mid: usize) {
2099 assert!(mid <= self.len());
2100 let k = self.len() - mid;
2103 let p = self.as_mut_ptr();
2104 rotate::ptr_rotate(mid, p.add(mid), k);
2108 /// Rotates the slice in-place such that the first `self.len() - k`
2109 /// elements of the slice move to the end while the last `k` elements move
2110 /// to the front. After calling `rotate_right`, the element previously at
2111 /// index `self.len() - k` will become the first element in the slice.
2115 /// This function will panic if `k` is greater than the length of the
2116 /// slice. Note that `k == self.len()` does _not_ panic and is a no-op
2121 /// Takes linear (in `self.len()`) time.
2126 /// let mut a = ['a', 'b', 'c', 'd', 'e', 'f'];
2127 /// a.rotate_right(2);
2128 /// assert_eq!(a, ['e', 'f', 'a', 'b', 'c', 'd']);
2131 /// Rotate a subslice:
2134 /// let mut a = ['a', 'b', 'c', 'd', 'e', 'f'];
2135 /// a[1..5].rotate_right(1);
2136 /// assert_eq!(a, ['a', 'e', 'b', 'c', 'd', 'f']);
2138 #[stable(feature = "slice_rotate", since = "1.26.0")]
2139 pub fn rotate_right(&mut self, k: usize) {
2140 assert!(k <= self.len());
2141 let mid = self.len() - k;
2144 let p = self.as_mut_ptr();
2145 rotate::ptr_rotate(mid, p.add(mid), k);
2149 /// Fills `self` with elements by cloning `value`.
2154 /// #![feature(slice_fill)]
2156 /// let mut buf = vec![0; 10];
2158 /// assert_eq!(buf, vec![1; 10]);
2160 #[unstable(feature = "slice_fill", issue = "70758")]
2161 pub fn fill<V>(&mut self, value: V)
2166 let value = value.borrow();
2168 el.clone_from(value)
2172 /// Copies the elements from `src` into `self`.
2174 /// The length of `src` must be the same as `self`.
2176 /// If `src` implements `Copy`, it can be more performant to use
2177 /// [`copy_from_slice`].
2181 /// This function will panic if the two slices have different lengths.
2185 /// Cloning two elements from a slice into another:
2188 /// let src = [1, 2, 3, 4];
2189 /// let mut dst = [0, 0];
2191 /// // Because the slices have to be the same length,
2192 /// // we slice the source slice from four elements
2193 /// // to two. It will panic if we don't do this.
2194 /// dst.clone_from_slice(&src[2..]);
2196 /// assert_eq!(src, [1, 2, 3, 4]);
2197 /// assert_eq!(dst, [3, 4]);
2200 /// Rust enforces that there can only be one mutable reference with no
2201 /// immutable references to a particular piece of data in a particular
2202 /// scope. Because of this, attempting to use `clone_from_slice` on a
2203 /// single slice will result in a compile failure:
2206 /// let mut slice = [1, 2, 3, 4, 5];
2208 /// slice[..2].clone_from_slice(&slice[3..]); // compile fail!
2211 /// To work around this, we can use [`split_at_mut`] to create two distinct
2212 /// sub-slices from a slice:
2215 /// let mut slice = [1, 2, 3, 4, 5];
2218 /// let (left, right) = slice.split_at_mut(2);
2219 /// left.clone_from_slice(&right[1..]);
2222 /// assert_eq!(slice, [4, 5, 3, 4, 5]);
2225 /// [`copy_from_slice`]: #method.copy_from_slice
2226 /// [`split_at_mut`]: #method.split_at_mut
2227 #[stable(feature = "clone_from_slice", since = "1.7.0")]
2228 pub fn clone_from_slice(&mut self, src: &[T])
2232 assert!(self.len() == src.len(), "destination and source slices have different lengths");
2233 // NOTE: We need to explicitly slice them to the same length
2234 // for bounds checking to be elided, and the optimizer will
2235 // generate memcpy for simple cases (for example T = u8).
2236 let len = self.len();
2237 let src = &src[..len];
2239 self[i].clone_from(&src[i]);
2243 /// Copies all elements from `src` into `self`, using a memcpy.
2245 /// The length of `src` must be the same as `self`.
2247 /// If `src` does not implement `Copy`, use [`clone_from_slice`].
2251 /// This function will panic if the two slices have different lengths.
2255 /// Copying two elements from a slice into another:
2258 /// let src = [1, 2, 3, 4];
2259 /// let mut dst = [0, 0];
2261 /// // Because the slices have to be the same length,
2262 /// // we slice the source slice from four elements
2263 /// // to two. It will panic if we don't do this.
2264 /// dst.copy_from_slice(&src[2..]);
2266 /// assert_eq!(src, [1, 2, 3, 4]);
2267 /// assert_eq!(dst, [3, 4]);
2270 /// Rust enforces that there can only be one mutable reference with no
2271 /// immutable references to a particular piece of data in a particular
2272 /// scope. Because of this, attempting to use `copy_from_slice` on a
2273 /// single slice will result in a compile failure:
2276 /// let mut slice = [1, 2, 3, 4, 5];
2278 /// slice[..2].copy_from_slice(&slice[3..]); // compile fail!
2281 /// To work around this, we can use [`split_at_mut`] to create two distinct
2282 /// sub-slices from a slice:
2285 /// let mut slice = [1, 2, 3, 4, 5];
2288 /// let (left, right) = slice.split_at_mut(2);
2289 /// left.copy_from_slice(&right[1..]);
2292 /// assert_eq!(slice, [4, 5, 3, 4, 5]);
2295 /// [`clone_from_slice`]: #method.clone_from_slice
2296 /// [`split_at_mut`]: #method.split_at_mut
2297 #[stable(feature = "copy_from_slice", since = "1.9.0")]
2298 pub fn copy_from_slice(&mut self, src: &[T])
2302 assert_eq!(self.len(), src.len(), "destination and source slices have different lengths");
2304 ptr::copy_nonoverlapping(src.as_ptr(), self.as_mut_ptr(), self.len());
2308 /// Copies elements from one part of the slice to another part of itself,
2309 /// using a memmove.
2311 /// `src` is the range within `self` to copy from. `dest` is the starting
2312 /// index of the range within `self` to copy to, which will have the same
2313 /// length as `src`. The two ranges may overlap. The ends of the two ranges
2314 /// must be less than or equal to `self.len()`.
2318 /// This function will panic if either range exceeds the end of the slice,
2319 /// or if the end of `src` is before the start.
2323 /// Copying four bytes within a slice:
2326 /// let mut bytes = *b"Hello, World!";
2328 /// bytes.copy_within(1..5, 8);
2330 /// assert_eq!(&bytes, b"Hello, Wello!");
2332 #[stable(feature = "copy_within", since = "1.37.0")]
2334 pub fn copy_within<R: ops::RangeBounds<usize>>(&mut self, src: R, dest: usize)
2338 let src_start = match src.start_bound() {
2339 ops::Bound::Included(&n) => n,
2340 ops::Bound::Excluded(&n) => {
2341 n.checked_add(1).unwrap_or_else(|| slice_index_overflow_fail())
2343 ops::Bound::Unbounded => 0,
2345 let src_end = match src.end_bound() {
2346 ops::Bound::Included(&n) => {
2347 n.checked_add(1).unwrap_or_else(|| slice_index_overflow_fail())
2349 ops::Bound::Excluded(&n) => n,
2350 ops::Bound::Unbounded => self.len(),
2352 assert!(src_start <= src_end, "src end is before src start");
2353 assert!(src_end <= self.len(), "src is out of bounds");
2354 let count = src_end - src_start;
2355 assert!(dest <= self.len() - count, "dest is out of bounds");
2357 ptr::copy(self.as_ptr().add(src_start), self.as_mut_ptr().add(dest), count);
2361 /// Swaps all elements in `self` with those in `other`.
2363 /// The length of `other` must be the same as `self`.
2367 /// This function will panic if the two slices have different lengths.
2371 /// Swapping two elements across slices:
2374 /// let mut slice1 = [0, 0];
2375 /// let mut slice2 = [1, 2, 3, 4];
2377 /// slice1.swap_with_slice(&mut slice2[2..]);
2379 /// assert_eq!(slice1, [3, 4]);
2380 /// assert_eq!(slice2, [1, 2, 0, 0]);
2383 /// Rust enforces that there can only be one mutable reference to a
2384 /// particular piece of data in a particular scope. Because of this,
2385 /// attempting to use `swap_with_slice` on a single slice will result in
2386 /// a compile failure:
2389 /// let mut slice = [1, 2, 3, 4, 5];
2390 /// slice[..2].swap_with_slice(&mut slice[3..]); // compile fail!
2393 /// To work around this, we can use [`split_at_mut`] to create two distinct
2394 /// mutable sub-slices from a slice:
2397 /// let mut slice = [1, 2, 3, 4, 5];
2400 /// let (left, right) = slice.split_at_mut(2);
2401 /// left.swap_with_slice(&mut right[1..]);
2404 /// assert_eq!(slice, [4, 5, 3, 1, 2]);
2407 /// [`split_at_mut`]: #method.split_at_mut
2408 #[stable(feature = "swap_with_slice", since = "1.27.0")]
2409 pub fn swap_with_slice(&mut self, other: &mut [T]) {
2410 assert!(self.len() == other.len(), "destination and source slices have different lengths");
2412 ptr::swap_nonoverlapping(self.as_mut_ptr(), other.as_mut_ptr(), self.len());
2416 /// Function to calculate lengths of the middle and trailing slice for `align_to{,_mut}`.
2417 fn align_to_offsets<U>(&self) -> (usize, usize) {
2418 // What we gonna do about `rest` is figure out what multiple of `U`s we can put in a
2419 // lowest number of `T`s. And how many `T`s we need for each such "multiple".
2421 // Consider for example T=u8 U=u16. Then we can put 1 U in 2 Ts. Simple. Now, consider
2422 // for example a case where size_of::<T> = 16, size_of::<U> = 24. We can put 2 Us in
2423 // place of every 3 Ts in the `rest` slice. A bit more complicated.
2425 // Formula to calculate this is:
2427 // Us = lcm(size_of::<T>, size_of::<U>) / size_of::<U>
2428 // Ts = lcm(size_of::<T>, size_of::<U>) / size_of::<T>
2430 // Expanded and simplified:
2432 // Us = size_of::<T> / gcd(size_of::<T>, size_of::<U>)
2433 // Ts = size_of::<U> / gcd(size_of::<T>, size_of::<U>)
2435 // Luckily since all this is constant-evaluated... performance here matters not!
2437 fn gcd(a: usize, b: usize) -> usize {
2438 use crate::intrinsics;
2439 // iterative stein’s algorithm
2440 // We should still make this `const fn` (and revert to recursive algorithm if we do)
2441 // because relying on llvm to consteval all this is… well, it makes me uncomfortable.
2442 let (ctz_a, mut ctz_b) = unsafe {
2449 (intrinsics::cttz_nonzero(a), intrinsics::cttz_nonzero(b))
2451 let k = ctz_a.min(ctz_b);
2452 let mut a = a >> ctz_a;
2455 // remove all factors of 2 from b
2458 mem::swap(&mut a, &mut b);
2465 ctz_b = intrinsics::cttz_nonzero(b);
2470 let gcd: usize = gcd(mem::size_of::<T>(), mem::size_of::<U>());
2471 let ts: usize = mem::size_of::<U>() / gcd;
2472 let us: usize = mem::size_of::<T>() / gcd;
2474 // Armed with this knowledge, we can find how many `U`s we can fit!
2475 let us_len = self.len() / ts * us;
2476 // And how many `T`s will be in the trailing slice!
2477 let ts_len = self.len() % ts;
2481 /// Transmute the slice to a slice of another type, ensuring alignment of the types is
2484 /// This method splits the slice into three distinct slices: prefix, correctly aligned middle
2485 /// slice of a new type, and the suffix slice. The method may make the middle slice the greatest
2486 /// length possible for a given type and input slice, but only your algorithm's performance
2487 /// should depend on that, not its correctness. It is permissible for all of the input data to
2488 /// be returned as the prefix or suffix slice.
2490 /// This method has no purpose when either input element `T` or output element `U` are
2491 /// zero-sized and will return the original slice without splitting anything.
2495 /// This method is essentially a `transmute` with respect to the elements in the returned
2496 /// middle slice, so all the usual caveats pertaining to `transmute::<T, U>` also apply here.
2504 /// let bytes: [u8; 7] = [1, 2, 3, 4, 5, 6, 7];
2505 /// let (prefix, shorts, suffix) = bytes.align_to::<u16>();
2506 /// // less_efficient_algorithm_for_bytes(prefix);
2507 /// // more_efficient_algorithm_for_aligned_shorts(shorts);
2508 /// // less_efficient_algorithm_for_bytes(suffix);
2511 #[stable(feature = "slice_align_to", since = "1.30.0")]
2512 pub unsafe fn align_to<U>(&self) -> (&[T], &[U], &[T]) {
2513 // Note that most of this function will be constant-evaluated,
2514 if mem::size_of::<U>() == 0 || mem::size_of::<T>() == 0 {
2515 // handle ZSTs specially, which is – don't handle them at all.
2516 return (self, &[], &[]);
2519 // First, find at what point do we split between the first and 2nd slice. Easy with
2520 // ptr.align_offset.
2521 let ptr = self.as_ptr();
2522 let offset = crate::ptr::align_offset(ptr, mem::align_of::<U>());
2523 if offset > self.len() {
2526 let (left, rest) = self.split_at(offset);
2527 // now `rest` is definitely aligned, so `from_raw_parts_mut` below is okay
2528 let (us_len, ts_len) = rest.align_to_offsets::<U>();
2531 from_raw_parts(rest.as_ptr() as *const U, us_len),
2532 from_raw_parts(rest.as_ptr().add(rest.len() - ts_len), ts_len),
2537 /// Transmute the slice to a slice of another type, ensuring alignment of the types is
2540 /// This method splits the slice into three distinct slices: prefix, correctly aligned middle
2541 /// slice of a new type, and the suffix slice. The method may make the middle slice the greatest
2542 /// length possible for a given type and input slice, but only your algorithm's performance
2543 /// should depend on that, not its correctness. It is permissible for all of the input data to
2544 /// be returned as the prefix or suffix slice.
2546 /// This method has no purpose when either input element `T` or output element `U` are
2547 /// zero-sized and will return the original slice without splitting anything.
2551 /// This method is essentially a `transmute` with respect to the elements in the returned
2552 /// middle slice, so all the usual caveats pertaining to `transmute::<T, U>` also apply here.
2560 /// let mut bytes: [u8; 7] = [1, 2, 3, 4, 5, 6, 7];
2561 /// let (prefix, shorts, suffix) = bytes.align_to_mut::<u16>();
2562 /// // less_efficient_algorithm_for_bytes(prefix);
2563 /// // more_efficient_algorithm_for_aligned_shorts(shorts);
2564 /// // less_efficient_algorithm_for_bytes(suffix);
2567 #[stable(feature = "slice_align_to", since = "1.30.0")]
2568 pub unsafe fn align_to_mut<U>(&mut self) -> (&mut [T], &mut [U], &mut [T]) {
2569 // Note that most of this function will be constant-evaluated,
2570 if mem::size_of::<U>() == 0 || mem::size_of::<T>() == 0 {
2571 // handle ZSTs specially, which is – don't handle them at all.
2572 return (self, &mut [], &mut []);
2575 // First, find at what point do we split between the first and 2nd slice. Easy with
2576 // ptr.align_offset.
2577 let ptr = self.as_ptr();
2578 let offset = crate::ptr::align_offset(ptr, mem::align_of::<U>());
2579 if offset > self.len() {
2580 (self, &mut [], &mut [])
2582 let (left, rest) = self.split_at_mut(offset);
2583 // now `rest` is definitely aligned, so `from_raw_parts_mut` below is okay
2584 let (us_len, ts_len) = rest.align_to_offsets::<U>();
2585 let rest_len = rest.len();
2586 let mut_ptr = rest.as_mut_ptr();
2587 // We can't use `rest` again after this, that would invalidate its alias `mut_ptr`!
2590 from_raw_parts_mut(mut_ptr as *mut U, us_len),
2591 from_raw_parts_mut(mut_ptr.add(rest_len - ts_len), ts_len),
2596 /// Checks if the elements of this slice are sorted.
2598 /// That is, for each element `a` and its following element `b`, `a <= b` must hold. If the
2599 /// slice yields exactly zero or one element, `true` is returned.
2601 /// Note that if `Self::Item` is only `PartialOrd`, but not `Ord`, the above definition
2602 /// implies that this function returns `false` if any two consecutive items are not
2608 /// #![feature(is_sorted)]
2609 /// let empty: [i32; 0] = [];
2611 /// assert!([1, 2, 2, 9].is_sorted());
2612 /// assert!(![1, 3, 2, 4].is_sorted());
2613 /// assert!([0].is_sorted());
2614 /// assert!(empty.is_sorted());
2615 /// assert!(![0.0, 1.0, f32::NAN].is_sorted());
2618 #[unstable(feature = "is_sorted", reason = "new API", issue = "53485")]
2619 pub fn is_sorted(&self) -> bool
2623 self.is_sorted_by(|a, b| a.partial_cmp(b))
2626 /// Checks if the elements of this slice are sorted using the given comparator function.
2628 /// Instead of using `PartialOrd::partial_cmp`, this function uses the given `compare`
2629 /// function to determine the ordering of two elements. Apart from that, it's equivalent to
2630 /// [`is_sorted`]; see its documentation for more information.
2632 /// [`is_sorted`]: #method.is_sorted
2633 #[unstable(feature = "is_sorted", reason = "new API", issue = "53485")]
2634 pub fn is_sorted_by<F>(&self, mut compare: F) -> bool
2636 F: FnMut(&T, &T) -> Option<Ordering>,
2638 self.iter().is_sorted_by(|a, b| compare(*a, *b))
2641 /// Checks if the elements of this slice are sorted using the given key extraction function.
2643 /// Instead of comparing the slice's elements directly, this function compares the keys of the
2644 /// elements, as determined by `f`. Apart from that, it's equivalent to [`is_sorted`]; see its
2645 /// documentation for more information.
2647 /// [`is_sorted`]: #method.is_sorted
2652 /// #![feature(is_sorted)]
2654 /// assert!(["c", "bb", "aaa"].is_sorted_by_key(|s| s.len()));
2655 /// assert!(![-2i32, -1, 0, 3].is_sorted_by_key(|n| n.abs()));
2658 #[unstable(feature = "is_sorted", reason = "new API", issue = "53485")]
2659 pub fn is_sorted_by_key<F, K>(&self, f: F) -> bool
2664 self.iter().is_sorted_by_key(f)
2668 #[lang = "slice_u8"]
2671 /// Checks if all bytes in this slice are within the ASCII range.
2672 #[stable(feature = "ascii_methods_on_intrinsics", since = "1.23.0")]
2674 pub fn is_ascii(&self) -> bool {
2675 self.iter().all(|b| b.is_ascii())
2678 /// Checks that two slices are an ASCII case-insensitive match.
2680 /// Same as `to_ascii_lowercase(a) == to_ascii_lowercase(b)`,
2681 /// but without allocating and copying temporaries.
2682 #[stable(feature = "ascii_methods_on_intrinsics", since = "1.23.0")]
2684 pub fn eq_ignore_ascii_case(&self, other: &[u8]) -> bool {
2685 self.len() == other.len() && self.iter().zip(other).all(|(a, b)| a.eq_ignore_ascii_case(b))
2688 /// Converts this slice to its ASCII upper case equivalent in-place.
2690 /// ASCII letters 'a' to 'z' are mapped to 'A' to 'Z',
2691 /// but non-ASCII letters are unchanged.
2693 /// To return a new uppercased value without modifying the existing one, use
2694 /// [`to_ascii_uppercase`].
2696 /// [`to_ascii_uppercase`]: #method.to_ascii_uppercase
2697 #[stable(feature = "ascii_methods_on_intrinsics", since = "1.23.0")]
2699 pub fn make_ascii_uppercase(&mut self) {
2701 byte.make_ascii_uppercase();
2705 /// Converts this slice to its ASCII lower case equivalent in-place.
2707 /// ASCII letters 'A' to 'Z' are mapped to 'a' to 'z',
2708 /// but non-ASCII letters are unchanged.
2710 /// To return a new lowercased value without modifying the existing one, use
2711 /// [`to_ascii_lowercase`].
2713 /// [`to_ascii_lowercase`]: #method.to_ascii_lowercase
2714 #[stable(feature = "ascii_methods_on_intrinsics", since = "1.23.0")]
2716 pub fn make_ascii_lowercase(&mut self) {
2718 byte.make_ascii_lowercase();
2723 #[stable(feature = "rust1", since = "1.0.0")]
2724 impl<T, I> ops::Index<I> for [T]
2728 type Output = I::Output;
2731 fn index(&self, index: I) -> &I::Output {
2736 #[stable(feature = "rust1", since = "1.0.0")]
2737 impl<T, I> ops::IndexMut<I> for [T]
2742 fn index_mut(&mut self, index: I) -> &mut I::Output {
2743 index.index_mut(self)
2750 fn slice_index_len_fail(index: usize, len: usize) -> ! {
2751 panic!("index {} out of range for slice of length {}", index, len);
2757 fn slice_index_order_fail(index: usize, end: usize) -> ! {
2758 panic!("slice index starts at {} but ends at {}", index, end);
2764 fn slice_index_overflow_fail() -> ! {
2765 panic!("attempted to index slice up to maximum usize");
2768 mod private_slice_index {
2770 #[stable(feature = "slice_get_slice", since = "1.28.0")]
2773 #[stable(feature = "slice_get_slice", since = "1.28.0")]
2774 impl Sealed for usize {}
2775 #[stable(feature = "slice_get_slice", since = "1.28.0")]
2776 impl Sealed for ops::Range<usize> {}
2777 #[stable(feature = "slice_get_slice", since = "1.28.0")]
2778 impl Sealed for ops::RangeTo<usize> {}
2779 #[stable(feature = "slice_get_slice", since = "1.28.0")]
2780 impl Sealed for ops::RangeFrom<usize> {}
2781 #[stable(feature = "slice_get_slice", since = "1.28.0")]
2782 impl Sealed for ops::RangeFull {}
2783 #[stable(feature = "slice_get_slice", since = "1.28.0")]
2784 impl Sealed for ops::RangeInclusive<usize> {}
2785 #[stable(feature = "slice_get_slice", since = "1.28.0")]
2786 impl Sealed for ops::RangeToInclusive<usize> {}
2789 /// A helper trait used for indexing operations.
2790 #[stable(feature = "slice_get_slice", since = "1.28.0")]
2791 #[rustc_on_unimplemented(
2792 on(T = "str", label = "string indices are ranges of `usize`",),
2794 all(any(T = "str", T = "&str", T = "std::string::String"), _Self = "{integer}"),
2795 note = "you can use `.chars().nth()` or `.bytes().nth()`
2796 see chapter in The Book <https://doc.rust-lang.org/book/ch08-02-strings.html#indexing-into-strings>"
2798 message = "the type `{T}` cannot be indexed by `{Self}`",
2799 label = "slice indices are of type `usize` or ranges of `usize`"
2801 pub trait SliceIndex<T: ?Sized>: private_slice_index::Sealed {
2802 /// The output type returned by methods.
2803 #[stable(feature = "slice_get_slice", since = "1.28.0")]
2804 type Output: ?Sized;
2806 /// Returns a shared reference to the output at this location, if in
2808 #[unstable(feature = "slice_index_methods", issue = "none")]
2809 fn get(self, slice: &T) -> Option<&Self::Output>;
2811 /// Returns a mutable reference to the output at this location, if in
2813 #[unstable(feature = "slice_index_methods", issue = "none")]
2814 fn get_mut(self, slice: &mut T) -> Option<&mut Self::Output>;
2816 /// Returns a shared reference to the output at this location, without
2817 /// performing any bounds checking.
2818 /// Calling this method with an out-of-bounds index is *[undefined behavior]*
2819 /// even if the resulting reference is not used.
2820 /// [undefined behavior]: ../../reference/behavior-considered-undefined.html
2821 #[unstable(feature = "slice_index_methods", issue = "none")]
2822 unsafe fn get_unchecked(self, slice: &T) -> &Self::Output;
2824 /// Returns a mutable reference to the output at this location, without
2825 /// performing any bounds checking.
2826 /// Calling this method with an out-of-bounds index is *[undefined behavior]*
2827 /// even if the resulting reference is not used.
2828 /// [undefined behavior]: ../../reference/behavior-considered-undefined.html
2829 #[unstable(feature = "slice_index_methods", issue = "none")]
2830 unsafe fn get_unchecked_mut(self, slice: &mut T) -> &mut Self::Output;
2832 /// Returns a shared reference to the output at this location, panicking
2833 /// if out of bounds.
2834 #[unstable(feature = "slice_index_methods", issue = "none")]
2835 #[cfg_attr(not(bootstrap), track_caller)]
2836 fn index(self, slice: &T) -> &Self::Output;
2838 /// Returns a mutable reference to the output at this location, panicking
2839 /// if out of bounds.
2840 #[unstable(feature = "slice_index_methods", issue = "none")]
2841 #[cfg_attr(not(bootstrap), track_caller)]
2842 fn index_mut(self, slice: &mut T) -> &mut Self::Output;
2845 #[stable(feature = "slice_get_slice_impls", since = "1.15.0")]
2846 impl<T> SliceIndex<[T]> for usize {
2850 fn get(self, slice: &[T]) -> Option<&T> {
2851 if self < slice.len() { unsafe { Some(self.get_unchecked(slice)) } } else { None }
2855 fn get_mut(self, slice: &mut [T]) -> Option<&mut T> {
2856 if self < slice.len() { unsafe { Some(self.get_unchecked_mut(slice)) } } else { None }
2860 unsafe fn get_unchecked(self, slice: &[T]) -> &T {
2861 &*slice.as_ptr().add(self)
2865 unsafe fn get_unchecked_mut(self, slice: &mut [T]) -> &mut T {
2866 &mut *slice.as_mut_ptr().add(self)
2870 fn index(self, slice: &[T]) -> &T {
2871 // N.B., use intrinsic indexing
2876 fn index_mut(self, slice: &mut [T]) -> &mut T {
2877 // N.B., use intrinsic indexing
2882 #[stable(feature = "slice_get_slice_impls", since = "1.15.0")]
2883 impl<T> SliceIndex<[T]> for ops::Range<usize> {
2887 fn get(self, slice: &[T]) -> Option<&[T]> {
2888 if self.start > self.end || self.end > slice.len() {
2891 unsafe { Some(self.get_unchecked(slice)) }
2896 fn get_mut(self, slice: &mut [T]) -> Option<&mut [T]> {
2897 if self.start > self.end || self.end > slice.len() {
2900 unsafe { Some(self.get_unchecked_mut(slice)) }
2905 unsafe fn get_unchecked(self, slice: &[T]) -> &[T] {
2906 from_raw_parts(slice.as_ptr().add(self.start), self.end - self.start)
2910 unsafe fn get_unchecked_mut(self, slice: &mut [T]) -> &mut [T] {
2911 from_raw_parts_mut(slice.as_mut_ptr().add(self.start), self.end - self.start)
2915 fn index(self, slice: &[T]) -> &[T] {
2916 if self.start > self.end {
2917 slice_index_order_fail(self.start, self.end);
2918 } else if self.end > slice.len() {
2919 slice_index_len_fail(self.end, slice.len());
2921 unsafe { self.get_unchecked(slice) }
2925 fn index_mut(self, slice: &mut [T]) -> &mut [T] {
2926 if self.start > self.end {
2927 slice_index_order_fail(self.start, self.end);
2928 } else if self.end > slice.len() {
2929 slice_index_len_fail(self.end, slice.len());
2931 unsafe { self.get_unchecked_mut(slice) }
2935 #[stable(feature = "slice_get_slice_impls", since = "1.15.0")]
2936 impl<T> SliceIndex<[T]> for ops::RangeTo<usize> {
2940 fn get(self, slice: &[T]) -> Option<&[T]> {
2941 (0..self.end).get(slice)
2945 fn get_mut(self, slice: &mut [T]) -> Option<&mut [T]> {
2946 (0..self.end).get_mut(slice)
2950 unsafe fn get_unchecked(self, slice: &[T]) -> &[T] {
2951 (0..self.end).get_unchecked(slice)
2955 unsafe fn get_unchecked_mut(self, slice: &mut [T]) -> &mut [T] {
2956 (0..self.end).get_unchecked_mut(slice)
2960 fn index(self, slice: &[T]) -> &[T] {
2961 (0..self.end).index(slice)
2965 fn index_mut(self, slice: &mut [T]) -> &mut [T] {
2966 (0..self.end).index_mut(slice)
2970 #[stable(feature = "slice_get_slice_impls", since = "1.15.0")]
2971 impl<T> SliceIndex<[T]> for ops::RangeFrom<usize> {
2975 fn get(self, slice: &[T]) -> Option<&[T]> {
2976 (self.start..slice.len()).get(slice)
2980 fn get_mut(self, slice: &mut [T]) -> Option<&mut [T]> {
2981 (self.start..slice.len()).get_mut(slice)
2985 unsafe fn get_unchecked(self, slice: &[T]) -> &[T] {
2986 (self.start..slice.len()).get_unchecked(slice)
2990 unsafe fn get_unchecked_mut(self, slice: &mut [T]) -> &mut [T] {
2991 (self.start..slice.len()).get_unchecked_mut(slice)
2995 fn index(self, slice: &[T]) -> &[T] {
2996 (self.start..slice.len()).index(slice)
3000 fn index_mut(self, slice: &mut [T]) -> &mut [T] {
3001 (self.start..slice.len()).index_mut(slice)
3005 #[stable(feature = "slice_get_slice_impls", since = "1.15.0")]
3006 impl<T> SliceIndex<[T]> for ops::RangeFull {
3010 fn get(self, slice: &[T]) -> Option<&[T]> {
3015 fn get_mut(self, slice: &mut [T]) -> Option<&mut [T]> {
3020 unsafe fn get_unchecked(self, slice: &[T]) -> &[T] {
3025 unsafe fn get_unchecked_mut(self, slice: &mut [T]) -> &mut [T] {
3030 fn index(self, slice: &[T]) -> &[T] {
3035 fn index_mut(self, slice: &mut [T]) -> &mut [T] {
3040 #[stable(feature = "inclusive_range", since = "1.26.0")]
3041 impl<T> SliceIndex<[T]> for ops::RangeInclusive<usize> {
3045 fn get(self, slice: &[T]) -> Option<&[T]> {
3046 if *self.end() == usize::max_value() {
3049 (*self.start()..self.end() + 1).get(slice)
3054 fn get_mut(self, slice: &mut [T]) -> Option<&mut [T]> {
3055 if *self.end() == usize::max_value() {
3058 (*self.start()..self.end() + 1).get_mut(slice)
3063 unsafe fn get_unchecked(self, slice: &[T]) -> &[T] {
3064 (*self.start()..self.end() + 1).get_unchecked(slice)
3068 unsafe fn get_unchecked_mut(self, slice: &mut [T]) -> &mut [T] {
3069 (*self.start()..self.end() + 1).get_unchecked_mut(slice)
3073 fn index(self, slice: &[T]) -> &[T] {
3074 if *self.end() == usize::max_value() {
3075 slice_index_overflow_fail();
3077 (*self.start()..self.end() + 1).index(slice)
3081 fn index_mut(self, slice: &mut [T]) -> &mut [T] {
3082 if *self.end() == usize::max_value() {
3083 slice_index_overflow_fail();
3085 (*self.start()..self.end() + 1).index_mut(slice)
3089 #[stable(feature = "inclusive_range", since = "1.26.0")]
3090 impl<T> SliceIndex<[T]> for ops::RangeToInclusive<usize> {
3094 fn get(self, slice: &[T]) -> Option<&[T]> {
3095 (0..=self.end).get(slice)
3099 fn get_mut(self, slice: &mut [T]) -> Option<&mut [T]> {
3100 (0..=self.end).get_mut(slice)
3104 unsafe fn get_unchecked(self, slice: &[T]) -> &[T] {
3105 (0..=self.end).get_unchecked(slice)
3109 unsafe fn get_unchecked_mut(self, slice: &mut [T]) -> &mut [T] {
3110 (0..=self.end).get_unchecked_mut(slice)
3114 fn index(self, slice: &[T]) -> &[T] {
3115 (0..=self.end).index(slice)
3119 fn index_mut(self, slice: &mut [T]) -> &mut [T] {
3120 (0..=self.end).index_mut(slice)
3124 ////////////////////////////////////////////////////////////////////////////////
3126 ////////////////////////////////////////////////////////////////////////////////
3128 #[stable(feature = "rust1", since = "1.0.0")]
3129 impl<T> Default for &[T] {
3130 /// Creates an empty slice.
3131 fn default() -> Self {
3136 #[stable(feature = "mut_slice_default", since = "1.5.0")]
3137 impl<T> Default for &mut [T] {
3138 /// Creates a mutable empty slice.
3139 fn default() -> Self {
3148 #[stable(feature = "rust1", since = "1.0.0")]
3149 impl<'a, T> IntoIterator for &'a [T] {
3151 type IntoIter = Iter<'a, T>;
3153 fn into_iter(self) -> Iter<'a, T> {
3158 #[stable(feature = "rust1", since = "1.0.0")]
3159 impl<'a, T> IntoIterator for &'a mut [T] {
3160 type Item = &'a mut T;
3161 type IntoIter = IterMut<'a, T>;
3163 fn into_iter(self) -> IterMut<'a, T> {
3168 // Macro helper functions
3170 fn size_from_ptr<T>(_: *const T) -> usize {
3174 // Inlining is_empty and len makes a huge performance difference
3175 macro_rules! is_empty {
3176 // The way we encode the length of a ZST iterator, this works both for ZST
3179 $self.ptr.as_ptr() as *const T == $self.end
3182 // To get rid of some bounds checks (see `position`), we compute the length in a somewhat
3183 // unexpected way. (Tested by `codegen/slice-position-bounds-check`.)
3185 ($self: ident) => {{
3186 #![allow(unused_unsafe)] // we're sometimes used within an unsafe block
3188 let start = $self.ptr;
3189 let size = size_from_ptr(start.as_ptr());
3191 // This _cannot_ use `unchecked_sub` because we depend on wrapping
3192 // to represent the length of long ZST slice iterators.
3193 ($self.end as usize).wrapping_sub(start.as_ptr() as usize)
3195 // We know that `start <= end`, so can do better than `offset_from`,
3196 // which needs to deal in signed. By setting appropriate flags here
3197 // we can tell LLVM this, which helps it remove bounds checks.
3198 // SAFETY: By the type invariant, `start <= end`
3199 let diff = unsafe { unchecked_sub($self.end as usize, start.as_ptr() as usize) };
3200 // By also telling LLVM that the pointers are apart by an exact
3201 // multiple of the type size, it can optimize `len() == 0` down to
3202 // `start == end` instead of `(end - start) < size`.
3203 // SAFETY: By the type invariant, the pointers are aligned so the
3204 // distance between them must be a multiple of pointee size
3205 unsafe { exact_div(diff, size) }
3210 // The shared definition of the `Iter` and `IterMut` iterators
3211 macro_rules! iterator {
3213 struct $name:ident -> $ptr:ty,
3219 // Returns the first element and moves the start of the iterator forwards by 1.
3220 // Greatly improves performance compared to an inlined function. The iterator
3221 // must not be empty.
3222 macro_rules! next_unchecked {
3223 ($self: ident) => {& $( $mut_ )* *$self.post_inc_start(1)}
3226 // Returns the last element and moves the end of the iterator backwards by 1.
3227 // Greatly improves performance compared to an inlined function. The iterator
3228 // must not be empty.
3229 macro_rules! next_back_unchecked {
3230 ($self: ident) => {& $( $mut_ )* *$self.pre_dec_end(1)}
3233 // Shrinks the iterator when T is a ZST, by moving the end of the iterator
3234 // backwards by `n`. `n` must not exceed `self.len()`.
3235 macro_rules! zst_shrink {
3236 ($self: ident, $n: ident) => {
3237 $self.end = ($self.end as * $raw_mut u8).wrapping_offset(-$n) as * $raw_mut T;
3241 impl<'a, T> $name<'a, T> {
3242 // Helper function for creating a slice from the iterator.
3244 fn make_slice(&self) -> &'a [T] {
3245 unsafe { from_raw_parts(self.ptr.as_ptr(), len!(self)) }
3248 // Helper function for moving the start of the iterator forwards by `offset` elements,
3249 // returning the old start.
3250 // Unsafe because the offset must not exceed `self.len()`.
3252 unsafe fn post_inc_start(&mut self, offset: isize) -> * $raw_mut T {
3253 if mem::size_of::<T>() == 0 {
3254 zst_shrink!(self, offset);
3257 let old = self.ptr.as_ptr();
3258 self.ptr = NonNull::new_unchecked(self.ptr.as_ptr().offset(offset));
3263 // Helper function for moving the end of the iterator backwards by `offset` elements,
3264 // returning the new end.
3265 // Unsafe because the offset must not exceed `self.len()`.
3267 unsafe fn pre_dec_end(&mut self, offset: isize) -> * $raw_mut T {
3268 if mem::size_of::<T>() == 0 {
3269 zst_shrink!(self, offset);
3272 self.end = self.end.offset(-offset);
3278 #[stable(feature = "rust1", since = "1.0.0")]
3279 impl<T> ExactSizeIterator for $name<'_, T> {
3281 fn len(&self) -> usize {
3286 fn is_empty(&self) -> bool {
3291 #[stable(feature = "rust1", since = "1.0.0")]
3292 impl<'a, T> Iterator for $name<'a, T> {
3296 fn next(&mut self) -> Option<$elem> {
3297 // could be implemented with slices, but this avoids bounds checks
3299 assume(!self.ptr.as_ptr().is_null());
3300 if mem::size_of::<T>() != 0 {
3301 assume(!self.end.is_null());
3303 if is_empty!(self) {
3306 Some(next_unchecked!(self))
3312 fn size_hint(&self) -> (usize, Option<usize>) {
3313 let exact = len!(self);
3314 (exact, Some(exact))
3318 fn count(self) -> usize {
3323 fn nth(&mut self, n: usize) -> Option<$elem> {
3324 if n >= len!(self) {
3325 // This iterator is now empty.
3326 if mem::size_of::<T>() == 0 {
3327 // We have to do it this way as `ptr` may never be 0, but `end`
3328 // could be (due to wrapping).
3329 self.end = self.ptr.as_ptr();
3332 // End can't be 0 if T isn't ZST because ptr isn't 0 and end >= ptr
3333 self.ptr = NonNull::new_unchecked(self.end as *mut T);
3338 // We are in bounds. `post_inc_start` does the right thing even for ZSTs.
3340 self.post_inc_start(n as isize);
3341 Some(next_unchecked!(self))
3346 fn last(mut self) -> Option<$elem> {
3351 #[rustc_inherit_overflow_checks]
3352 fn position<P>(&mut self, mut predicate: P) -> Option<usize> where
3354 P: FnMut(Self::Item) -> bool,
3356 // The addition might panic on overflow.
3358 self.try_fold(0, move |i, x| {
3359 if predicate(x) { Err(i) }
3363 unsafe { assume(i < n) };
3369 fn rposition<P>(&mut self, mut predicate: P) -> Option<usize> where
3370 P: FnMut(Self::Item) -> bool,
3371 Self: Sized + ExactSizeIterator + DoubleEndedIterator
3373 // No need for an overflow check here, because `ExactSizeIterator`
3375 self.try_rfold(n, move |i, x| {
3377 if predicate(x) { Err(i) }
3381 unsafe { assume(i < n) };
3389 #[stable(feature = "rust1", since = "1.0.0")]
3390 impl<'a, T> DoubleEndedIterator for $name<'a, T> {
3392 fn next_back(&mut self) -> Option<$elem> {
3393 // could be implemented with slices, but this avoids bounds checks
3395 assume(!self.ptr.as_ptr().is_null());
3396 if mem::size_of::<T>() != 0 {
3397 assume(!self.end.is_null());
3399 if is_empty!(self) {
3402 Some(next_back_unchecked!(self))
3408 fn nth_back(&mut self, n: usize) -> Option<$elem> {
3409 if n >= len!(self) {
3410 // This iterator is now empty.
3411 self.end = self.ptr.as_ptr();
3414 // We are in bounds. `pre_dec_end` does the right thing even for ZSTs.
3416 self.pre_dec_end(n as isize);
3417 Some(next_back_unchecked!(self))
3422 #[stable(feature = "fused", since = "1.26.0")]
3423 impl<T> FusedIterator for $name<'_, T> {}
3425 #[unstable(feature = "trusted_len", issue = "37572")]
3426 unsafe impl<T> TrustedLen for $name<'_, T> {}
3430 /// Immutable slice iterator
3432 /// This struct is created by the [`iter`] method on [slices].
3439 /// // First, we declare a type which has `iter` method to get the `Iter` struct (&[usize here]):
3440 /// let slice = &[1, 2, 3];
3442 /// // Then, we iterate over it:
3443 /// for element in slice.iter() {
3444 /// println!("{}", element);
3448 /// [`iter`]: ../../std/primitive.slice.html#method.iter
3449 /// [slices]: ../../std/primitive.slice.html
3450 #[stable(feature = "rust1", since = "1.0.0")]
3451 pub struct Iter<'a, T: 'a> {
3453 end: *const T, // If T is a ZST, this is actually ptr+len. This encoding is picked so that
3454 // ptr == end is a quick test for the Iterator being empty, that works
3455 // for both ZST and non-ZST.
3456 _marker: marker::PhantomData<&'a T>,
3459 #[stable(feature = "core_impl_debug", since = "1.9.0")]
3460 impl<T: fmt::Debug> fmt::Debug for Iter<'_, T> {
3461 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
3462 f.debug_tuple("Iter").field(&self.as_slice()).finish()
3466 #[stable(feature = "rust1", since = "1.0.0")]
3467 unsafe impl<T: Sync> Sync for Iter<'_, T> {}
3468 #[stable(feature = "rust1", since = "1.0.0")]
3469 unsafe impl<T: Sync> Send for Iter<'_, T> {}
3471 impl<'a, T> Iter<'a, T> {
3472 /// Views the underlying data as a subslice of the original data.
3474 /// This has the same lifetime as the original slice, and so the
3475 /// iterator can continue to be used while this exists.
3482 /// // First, we declare a type which has the `iter` method to get the `Iter`
3483 /// // struct (&[usize here]):
3484 /// let slice = &[1, 2, 3];
3486 /// // Then, we get the iterator:
3487 /// let mut iter = slice.iter();
3488 /// // So if we print what `as_slice` method returns here, we have "[1, 2, 3]":
3489 /// println!("{:?}", iter.as_slice());
3491 /// // Next, we move to the second element of the slice:
3493 /// // Now `as_slice` returns "[2, 3]":
3494 /// println!("{:?}", iter.as_slice());
3496 #[stable(feature = "iter_to_slice", since = "1.4.0")]
3497 pub fn as_slice(&self) -> &'a [T] {
3502 iterator! {struct Iter -> *const T, &'a T, const, {/* no mut */}, {
3503 fn is_sorted_by<F>(self, mut compare: F) -> bool
3506 F: FnMut(&Self::Item, &Self::Item) -> Option<Ordering>,
3508 self.as_slice().windows(2).all(|w| {
3509 compare(&&w[0], &&w[1]).map(|o| o != Ordering::Greater).unwrap_or(false)
3514 #[stable(feature = "rust1", since = "1.0.0")]
3515 impl<T> Clone for Iter<'_, T> {
3516 fn clone(&self) -> Self {
3517 Iter { ptr: self.ptr, end: self.end, _marker: self._marker }
3521 #[stable(feature = "slice_iter_as_ref", since = "1.13.0")]
3522 impl<T> AsRef<[T]> for Iter<'_, T> {
3523 fn as_ref(&self) -> &[T] {
3528 /// Mutable slice iterator.
3530 /// This struct is created by the [`iter_mut`] method on [slices].
3537 /// // First, we declare a type which has `iter_mut` method to get the `IterMut`
3538 /// // struct (&[usize here]):
3539 /// let mut slice = &mut [1, 2, 3];
3541 /// // Then, we iterate over it and increment each element value:
3542 /// for element in slice.iter_mut() {
3546 /// // We now have "[2, 3, 4]":
3547 /// println!("{:?}", slice);
3550 /// [`iter_mut`]: ../../std/primitive.slice.html#method.iter_mut
3551 /// [slices]: ../../std/primitive.slice.html
3552 #[stable(feature = "rust1", since = "1.0.0")]
3553 pub struct IterMut<'a, T: 'a> {
3555 end: *mut T, // If T is a ZST, this is actually ptr+len. This encoding is picked so that
3556 // ptr == end is a quick test for the Iterator being empty, that works
3557 // for both ZST and non-ZST.
3558 _marker: marker::PhantomData<&'a mut T>,
3561 #[stable(feature = "core_impl_debug", since = "1.9.0")]
3562 impl<T: fmt::Debug> fmt::Debug for IterMut<'_, T> {
3563 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
3564 f.debug_tuple("IterMut").field(&self.make_slice()).finish()
3568 #[stable(feature = "rust1", since = "1.0.0")]
3569 unsafe impl<T: Sync> Sync for IterMut<'_, T> {}
3570 #[stable(feature = "rust1", since = "1.0.0")]
3571 unsafe impl<T: Send> Send for IterMut<'_, T> {}
3573 impl<'a, T> IterMut<'a, T> {
3574 /// Views the underlying data as a subslice of the original data.
3576 /// To avoid creating `&mut` references that alias, this is forced
3577 /// to consume the iterator.
3584 /// // First, we declare a type which has `iter_mut` method to get the `IterMut`
3585 /// // struct (&[usize here]):
3586 /// let mut slice = &mut [1, 2, 3];
3589 /// // Then, we get the iterator:
3590 /// let mut iter = slice.iter_mut();
3591 /// // We move to next element:
3593 /// // So if we print what `into_slice` method returns here, we have "[2, 3]":
3594 /// println!("{:?}", iter.into_slice());
3597 /// // Now let's modify a value of the slice:
3599 /// // First we get back the iterator:
3600 /// let mut iter = slice.iter_mut();
3601 /// // We change the value of the first element of the slice returned by the `next` method:
3602 /// *iter.next().unwrap() += 1;
3604 /// // Now slice is "[2, 2, 3]":
3605 /// println!("{:?}", slice);
3607 #[stable(feature = "iter_to_slice", since = "1.4.0")]
3608 pub fn into_slice(self) -> &'a mut [T] {
3609 unsafe { from_raw_parts_mut(self.ptr.as_ptr(), len!(self)) }
3612 /// Views the underlying data as a subslice of the original data.
3614 /// To avoid creating `&mut [T]` references that alias, the returned slice
3615 /// borrows its lifetime from the iterator the method is applied on.
3622 /// # #![feature(slice_iter_mut_as_slice)]
3623 /// let mut slice: &mut [usize] = &mut [1, 2, 3];
3625 /// // First, we get the iterator:
3626 /// let mut iter = slice.iter_mut();
3627 /// // So if we check what the `as_slice` method returns here, we have "[1, 2, 3]":
3628 /// assert_eq!(iter.as_slice(), &[1, 2, 3]);
3630 /// // Next, we move to the second element of the slice:
3632 /// // Now `as_slice` returns "[2, 3]":
3633 /// assert_eq!(iter.as_slice(), &[2, 3]);
3635 #[unstable(feature = "slice_iter_mut_as_slice", reason = "recently added", issue = "58957")]
3636 pub fn as_slice(&self) -> &[T] {
3641 iterator! {struct IterMut -> *mut T, &'a mut T, mut, {mut}, {}}
3643 /// An internal abstraction over the splitting iterators, so that
3644 /// splitn, splitn_mut etc can be implemented once.
3646 trait SplitIter: DoubleEndedIterator {
3647 /// Marks the underlying iterator as complete, extracting the remaining
3648 /// portion of the slice.
3649 fn finish(&mut self) -> Option<Self::Item>;
3652 /// An iterator over subslices separated by elements that match a predicate
3655 /// This struct is created by the [`split`] method on [slices].
3657 /// [`split`]: ../../std/primitive.slice.html#method.split
3658 /// [slices]: ../../std/primitive.slice.html
3659 #[stable(feature = "rust1", since = "1.0.0")]
3660 pub struct Split<'a, T: 'a, P>
3662 P: FnMut(&T) -> bool,
3669 #[stable(feature = "core_impl_debug", since = "1.9.0")]
3670 impl<T: fmt::Debug, P> fmt::Debug for Split<'_, T, P>
3672 P: FnMut(&T) -> bool,
3674 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
3675 f.debug_struct("Split").field("v", &self.v).field("finished", &self.finished).finish()
3679 // FIXME(#26925) Remove in favor of `#[derive(Clone)]`
3680 #[stable(feature = "rust1", since = "1.0.0")]
3681 impl<T, P> Clone for Split<'_, T, P>
3683 P: Clone + FnMut(&T) -> bool,
3685 fn clone(&self) -> Self {
3686 Split { v: self.v, pred: self.pred.clone(), finished: self.finished }
3690 #[stable(feature = "rust1", since = "1.0.0")]
3691 impl<'a, T, P> Iterator for Split<'a, T, P>
3693 P: FnMut(&T) -> bool,
3695 type Item = &'a [T];
3698 fn next(&mut self) -> Option<&'a [T]> {
3703 match self.v.iter().position(|x| (self.pred)(x)) {
3704 None => self.finish(),
3706 let ret = Some(&self.v[..idx]);
3707 self.v = &self.v[idx + 1..];
3714 fn size_hint(&self) -> (usize, Option<usize>) {
3715 if self.finished { (0, Some(0)) } else { (1, Some(self.v.len() + 1)) }
3719 #[stable(feature = "rust1", since = "1.0.0")]
3720 impl<'a, T, P> DoubleEndedIterator for Split<'a, T, P>
3722 P: FnMut(&T) -> bool,
3725 fn next_back(&mut self) -> Option<&'a [T]> {
3730 match self.v.iter().rposition(|x| (self.pred)(x)) {
3731 None => self.finish(),
3733 let ret = Some(&self.v[idx + 1..]);
3734 self.v = &self.v[..idx];
3741 impl<'a, T, P> SplitIter for Split<'a, T, P>
3743 P: FnMut(&T) -> bool,
3746 fn finish(&mut self) -> Option<&'a [T]> {
3750 self.finished = true;
3756 #[stable(feature = "fused", since = "1.26.0")]
3757 impl<T, P> FusedIterator for Split<'_, T, P> where P: FnMut(&T) -> bool {}
3759 /// An iterator over subslices separated by elements that match a predicate
3760 /// function. Unlike `Split`, it contains the matched part as a terminator
3761 /// of the subslice.
3763 /// This struct is created by the [`split_inclusive`] method on [slices].
3765 /// [`split_inclusive`]: ../../std/primitive.slice.html#method.split_inclusive
3766 /// [slices]: ../../std/primitive.slice.html
3767 #[unstable(feature = "split_inclusive", issue = "none")]
3768 pub struct SplitInclusive<'a, T: 'a, P>
3770 P: FnMut(&T) -> bool,
3777 #[unstable(feature = "split_inclusive", issue = "none")]
3778 impl<T: fmt::Debug, P> fmt::Debug for SplitInclusive<'_, T, P>
3780 P: FnMut(&T) -> bool,
3782 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
3783 f.debug_struct("SplitInclusive")
3784 .field("v", &self.v)
3785 .field("finished", &self.finished)
3790 // FIXME(#26925) Remove in favor of `#[derive(Clone)]`
3791 #[unstable(feature = "split_inclusive", issue = "none")]
3792 impl<T, P> Clone for SplitInclusive<'_, T, P>
3794 P: Clone + FnMut(&T) -> bool,
3796 fn clone(&self) -> Self {
3797 SplitInclusive { v: self.v, pred: self.pred.clone(), finished: self.finished }
3801 #[unstable(feature = "split_inclusive", issue = "none")]
3802 impl<'a, T, P> Iterator for SplitInclusive<'a, T, P>
3804 P: FnMut(&T) -> bool,
3806 type Item = &'a [T];
3809 fn next(&mut self) -> Option<&'a [T]> {
3815 self.v.iter().position(|x| (self.pred)(x)).map(|idx| idx + 1).unwrap_or(self.v.len());
3816 if idx == self.v.len() {
3817 self.finished = true;
3819 let ret = Some(&self.v[..idx]);
3820 self.v = &self.v[idx..];
3825 fn size_hint(&self) -> (usize, Option<usize>) {
3826 if self.finished { (0, Some(0)) } else { (1, Some(self.v.len() + 1)) }
3830 #[unstable(feature = "split_inclusive", issue = "none")]
3831 impl<'a, T, P> DoubleEndedIterator for SplitInclusive<'a, T, P>
3833 P: FnMut(&T) -> bool,
3836 fn next_back(&mut self) -> Option<&'a [T]> {
3841 // The last index of self.v is already checked and found to match
3842 // by the last iteration, so we start searching a new match
3843 // one index to the left.
3844 let remainder = if self.v.is_empty() { &[] } else { &self.v[..(self.v.len() - 1)] };
3845 let idx = remainder.iter().rposition(|x| (self.pred)(x)).map(|idx| idx + 1).unwrap_or(0);
3847 self.finished = true;
3849 let ret = Some(&self.v[idx..]);
3850 self.v = &self.v[..idx];
3855 #[unstable(feature = "split_inclusive", issue = "none")]
3856 impl<T, P> FusedIterator for SplitInclusive<'_, T, P> where P: FnMut(&T) -> bool {}
3858 /// An iterator over the mutable subslices of the vector which are separated
3859 /// by elements that match `pred`.
3861 /// This struct is created by the [`split_mut`] method on [slices].
3863 /// [`split_mut`]: ../../std/primitive.slice.html#method.split_mut
3864 /// [slices]: ../../std/primitive.slice.html
3865 #[stable(feature = "rust1", since = "1.0.0")]
3866 pub struct SplitMut<'a, T: 'a, P>
3868 P: FnMut(&T) -> bool,
3875 #[stable(feature = "core_impl_debug", since = "1.9.0")]
3876 impl<T: fmt::Debug, P> fmt::Debug for SplitMut<'_, T, P>
3878 P: FnMut(&T) -> bool,
3880 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
3881 f.debug_struct("SplitMut").field("v", &self.v).field("finished", &self.finished).finish()
3885 impl<'a, T, P> SplitIter for SplitMut<'a, T, P>
3887 P: FnMut(&T) -> bool,
3890 fn finish(&mut self) -> Option<&'a mut [T]> {
3894 self.finished = true;
3895 Some(mem::replace(&mut self.v, &mut []))
3900 #[stable(feature = "rust1", since = "1.0.0")]
3901 impl<'a, T, P> Iterator for SplitMut<'a, T, P>
3903 P: FnMut(&T) -> bool,
3905 type Item = &'a mut [T];
3908 fn next(&mut self) -> Option<&'a mut [T]> {
3914 // work around borrowck limitations
3915 let pred = &mut self.pred;
3916 self.v.iter().position(|x| (*pred)(x))
3919 None => self.finish(),
3921 let tmp = mem::replace(&mut self.v, &mut []);
3922 let (head, tail) = tmp.split_at_mut(idx);
3923 self.v = &mut tail[1..];
3930 fn size_hint(&self) -> (usize, Option<usize>) {
3934 // if the predicate doesn't match anything, we yield one slice
3935 // if it matches every element, we yield len+1 empty slices.
3936 (1, Some(self.v.len() + 1))
3941 #[stable(feature = "rust1", since = "1.0.0")]
3942 impl<'a, T, P> DoubleEndedIterator for SplitMut<'a, T, P>
3944 P: FnMut(&T) -> bool,
3947 fn next_back(&mut self) -> Option<&'a mut [T]> {
3953 // work around borrowck limitations
3954 let pred = &mut self.pred;
3955 self.v.iter().rposition(|x| (*pred)(x))
3958 None => self.finish(),
3960 let tmp = mem::replace(&mut self.v, &mut []);
3961 let (head, tail) = tmp.split_at_mut(idx);
3963 Some(&mut tail[1..])
3969 #[stable(feature = "fused", since = "1.26.0")]
3970 impl<T, P> FusedIterator for SplitMut<'_, T, P> where P: FnMut(&T) -> bool {}
3972 /// An iterator over the mutable subslices of the vector which are separated
3973 /// by elements that match `pred`. Unlike `SplitMut`, it contains the matched
3974 /// parts in the ends of the subslices.
3976 /// This struct is created by the [`split_inclusive_mut`] method on [slices].
3978 /// [`split_inclusive_mut`]: ../../std/primitive.slice.html#method.split_inclusive_mut
3979 /// [slices]: ../../std/primitive.slice.html
3980 #[unstable(feature = "split_inclusive", issue = "none")]
3981 pub struct SplitInclusiveMut<'a, T: 'a, P>
3983 P: FnMut(&T) -> bool,
3990 #[unstable(feature = "split_inclusive", issue = "none")]
3991 impl<T: fmt::Debug, P> fmt::Debug for SplitInclusiveMut<'_, T, P>
3993 P: FnMut(&T) -> bool,
3995 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
3996 f.debug_struct("SplitInclusiveMut")
3997 .field("v", &self.v)
3998 .field("finished", &self.finished)
4003 #[unstable(feature = "split_inclusive", issue = "none")]
4004 impl<'a, T, P> Iterator for SplitInclusiveMut<'a, T, P>
4006 P: FnMut(&T) -> bool,
4008 type Item = &'a mut [T];
4011 fn next(&mut self) -> Option<&'a mut [T]> {
4017 // work around borrowck limitations
4018 let pred = &mut self.pred;
4019 self.v.iter().position(|x| (*pred)(x))
4021 let idx = idx_opt.map(|idx| idx + 1).unwrap_or(self.v.len());
4022 if idx == self.v.len() {
4023 self.finished = true;
4025 let tmp = mem::replace(&mut self.v, &mut []);
4026 let (head, tail) = tmp.split_at_mut(idx);
4032 fn size_hint(&self) -> (usize, Option<usize>) {
4036 // if the predicate doesn't match anything, we yield one slice
4037 // if it matches every element, we yield len+1 empty slices.
4038 (1, Some(self.v.len() + 1))
4043 #[unstable(feature = "split_inclusive", issue = "none")]
4044 impl<'a, T, P> DoubleEndedIterator for SplitInclusiveMut<'a, T, P>
4046 P: FnMut(&T) -> bool,
4049 fn next_back(&mut self) -> Option<&'a mut [T]> {
4054 let idx_opt = if self.v.is_empty() {
4057 // work around borrowck limitations
4058 let pred = &mut self.pred;
4060 // The last index of self.v is already checked and found to match
4061 // by the last iteration, so we start searching a new match
4062 // one index to the left.
4063 let remainder = &self.v[..(self.v.len() - 1)];
4064 remainder.iter().rposition(|x| (*pred)(x))
4066 let idx = idx_opt.map(|idx| idx + 1).unwrap_or(0);
4068 self.finished = true;
4070 let tmp = mem::replace(&mut self.v, &mut []);
4071 let (head, tail) = tmp.split_at_mut(idx);
4077 #[unstable(feature = "split_inclusive", issue = "none")]
4078 impl<T, P> FusedIterator for SplitInclusiveMut<'_, T, P> where P: FnMut(&T) -> bool {}
4080 /// An iterator over subslices separated by elements that match a predicate
4081 /// function, starting from the end of the slice.
4083 /// This struct is created by the [`rsplit`] method on [slices].
4085 /// [`rsplit`]: ../../std/primitive.slice.html#method.rsplit
4086 /// [slices]: ../../std/primitive.slice.html
4087 #[stable(feature = "slice_rsplit", since = "1.27.0")]
4088 #[derive(Clone)] // Is this correct, or does it incorrectly require `T: Clone`?
4089 pub struct RSplit<'a, T: 'a, P>
4091 P: FnMut(&T) -> bool,
4093 inner: Split<'a, T, P>,
4096 #[stable(feature = "slice_rsplit", since = "1.27.0")]
4097 impl<T: fmt::Debug, P> fmt::Debug for RSplit<'_, T, P>
4099 P: FnMut(&T) -> bool,
4101 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
4102 f.debug_struct("RSplit")
4103 .field("v", &self.inner.v)
4104 .field("finished", &self.inner.finished)
4109 #[stable(feature = "slice_rsplit", since = "1.27.0")]
4110 impl<'a, T, P> Iterator for RSplit<'a, T, P>
4112 P: FnMut(&T) -> bool,
4114 type Item = &'a [T];
4117 fn next(&mut self) -> Option<&'a [T]> {
4118 self.inner.next_back()
4122 fn size_hint(&self) -> (usize, Option<usize>) {
4123 self.inner.size_hint()
4127 #[stable(feature = "slice_rsplit", since = "1.27.0")]
4128 impl<'a, T, P> DoubleEndedIterator for RSplit<'a, T, P>
4130 P: FnMut(&T) -> bool,
4133 fn next_back(&mut self) -> Option<&'a [T]> {
4138 #[stable(feature = "slice_rsplit", since = "1.27.0")]
4139 impl<'a, T, P> SplitIter for RSplit<'a, T, P>
4141 P: FnMut(&T) -> bool,
4144 fn finish(&mut self) -> Option<&'a [T]> {
4149 #[stable(feature = "slice_rsplit", since = "1.27.0")]
4150 impl<T, P> FusedIterator for RSplit<'_, T, P> where P: FnMut(&T) -> bool {}
4152 /// An iterator over the subslices of the vector which are separated
4153 /// by elements that match `pred`, starting from the end of the slice.
4155 /// This struct is created by the [`rsplit_mut`] method on [slices].
4157 /// [`rsplit_mut`]: ../../std/primitive.slice.html#method.rsplit_mut
4158 /// [slices]: ../../std/primitive.slice.html
4159 #[stable(feature = "slice_rsplit", since = "1.27.0")]
4160 pub struct RSplitMut<'a, T: 'a, P>
4162 P: FnMut(&T) -> bool,
4164 inner: SplitMut<'a, T, P>,
4167 #[stable(feature = "slice_rsplit", since = "1.27.0")]
4168 impl<T: fmt::Debug, P> fmt::Debug for RSplitMut<'_, T, P>
4170 P: FnMut(&T) -> bool,
4172 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
4173 f.debug_struct("RSplitMut")
4174 .field("v", &self.inner.v)
4175 .field("finished", &self.inner.finished)
4180 #[stable(feature = "slice_rsplit", since = "1.27.0")]
4181 impl<'a, T, P> SplitIter for RSplitMut<'a, T, P>
4183 P: FnMut(&T) -> bool,
4186 fn finish(&mut self) -> Option<&'a mut [T]> {
4191 #[stable(feature = "slice_rsplit", since = "1.27.0")]
4192 impl<'a, T, P> Iterator for RSplitMut<'a, T, P>
4194 P: FnMut(&T) -> bool,
4196 type Item = &'a mut [T];
4199 fn next(&mut self) -> Option<&'a mut [T]> {
4200 self.inner.next_back()
4204 fn size_hint(&self) -> (usize, Option<usize>) {
4205 self.inner.size_hint()
4209 #[stable(feature = "slice_rsplit", since = "1.27.0")]
4210 impl<'a, T, P> DoubleEndedIterator for RSplitMut<'a, T, P>
4212 P: FnMut(&T) -> bool,
4215 fn next_back(&mut self) -> Option<&'a mut [T]> {
4220 #[stable(feature = "slice_rsplit", since = "1.27.0")]
4221 impl<T, P> FusedIterator for RSplitMut<'_, T, P> where P: FnMut(&T) -> bool {}
4223 /// An private iterator over subslices separated by elements that
4224 /// match a predicate function, splitting at most a fixed number of
4227 struct GenericSplitN<I> {
4232 impl<T, I: SplitIter<Item = T>> Iterator for GenericSplitN<I> {
4236 fn next(&mut self) -> Option<T> {
4251 fn size_hint(&self) -> (usize, Option<usize>) {
4252 let (lower, upper_opt) = self.iter.size_hint();
4253 (lower, upper_opt.map(|upper| cmp::min(self.count, upper)))
4257 /// An iterator over subslices separated by elements that match a predicate
4258 /// function, limited to a given number of splits.
4260 /// This struct is created by the [`splitn`] method on [slices].
4262 /// [`splitn`]: ../../std/primitive.slice.html#method.splitn
4263 /// [slices]: ../../std/primitive.slice.html
4264 #[stable(feature = "rust1", since = "1.0.0")]
4265 pub struct SplitN<'a, T: 'a, P>
4267 P: FnMut(&T) -> bool,
4269 inner: GenericSplitN<Split<'a, T, P>>,
4272 #[stable(feature = "core_impl_debug", since = "1.9.0")]
4273 impl<T: fmt::Debug, P> fmt::Debug for SplitN<'_, T, P>
4275 P: FnMut(&T) -> bool,
4277 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
4278 f.debug_struct("SplitN").field("inner", &self.inner).finish()
4282 /// An iterator over subslices separated by elements that match a
4283 /// predicate function, limited to a given number of splits, starting
4284 /// from the end of the slice.
4286 /// This struct is created by the [`rsplitn`] method on [slices].
4288 /// [`rsplitn`]: ../../std/primitive.slice.html#method.rsplitn
4289 /// [slices]: ../../std/primitive.slice.html
4290 #[stable(feature = "rust1", since = "1.0.0")]
4291 pub struct RSplitN<'a, T: 'a, P>
4293 P: FnMut(&T) -> bool,
4295 inner: GenericSplitN<RSplit<'a, T, P>>,
4298 #[stable(feature = "core_impl_debug", since = "1.9.0")]
4299 impl<T: fmt::Debug, P> fmt::Debug for RSplitN<'_, T, P>
4301 P: FnMut(&T) -> bool,
4303 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
4304 f.debug_struct("RSplitN").field("inner", &self.inner).finish()
4308 /// An iterator over subslices separated by elements that match a predicate
4309 /// function, limited to a given number of splits.
4311 /// This struct is created by the [`splitn_mut`] method on [slices].
4313 /// [`splitn_mut`]: ../../std/primitive.slice.html#method.splitn_mut
4314 /// [slices]: ../../std/primitive.slice.html
4315 #[stable(feature = "rust1", since = "1.0.0")]
4316 pub struct SplitNMut<'a, T: 'a, P>
4318 P: FnMut(&T) -> bool,
4320 inner: GenericSplitN<SplitMut<'a, T, P>>,
4323 #[stable(feature = "core_impl_debug", since = "1.9.0")]
4324 impl<T: fmt::Debug, P> fmt::Debug for SplitNMut<'_, T, P>
4326 P: FnMut(&T) -> bool,
4328 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
4329 f.debug_struct("SplitNMut").field("inner", &self.inner).finish()
4333 /// An iterator over subslices separated by elements that match a
4334 /// predicate function, limited to a given number of splits, starting
4335 /// from the end of the slice.
4337 /// This struct is created by the [`rsplitn_mut`] method on [slices].
4339 /// [`rsplitn_mut`]: ../../std/primitive.slice.html#method.rsplitn_mut
4340 /// [slices]: ../../std/primitive.slice.html
4341 #[stable(feature = "rust1", since = "1.0.0")]
4342 pub struct RSplitNMut<'a, T: 'a, P>
4344 P: FnMut(&T) -> bool,
4346 inner: GenericSplitN<RSplitMut<'a, T, P>>,
4349 #[stable(feature = "core_impl_debug", since = "1.9.0")]
4350 impl<T: fmt::Debug, P> fmt::Debug for RSplitNMut<'_, T, P>
4352 P: FnMut(&T) -> bool,
4354 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
4355 f.debug_struct("RSplitNMut").field("inner", &self.inner).finish()
4359 macro_rules! forward_iterator {
4360 ($name:ident: $elem:ident, $iter_of:ty) => {
4361 #[stable(feature = "rust1", since = "1.0.0")]
4362 impl<'a, $elem, P> Iterator for $name<'a, $elem, P>
4364 P: FnMut(&T) -> bool,
4366 type Item = $iter_of;
4369 fn next(&mut self) -> Option<$iter_of> {
4374 fn size_hint(&self) -> (usize, Option<usize>) {
4375 self.inner.size_hint()
4379 #[stable(feature = "fused", since = "1.26.0")]
4380 impl<'a, $elem, P> FusedIterator for $name<'a, $elem, P> where P: FnMut(&T) -> bool {}
4384 forward_iterator! { SplitN: T, &'a [T] }
4385 forward_iterator! { RSplitN: T, &'a [T] }
4386 forward_iterator! { SplitNMut: T, &'a mut [T] }
4387 forward_iterator! { RSplitNMut: T, &'a mut [T] }
4389 /// An iterator over overlapping subslices of length `size`.
4391 /// This struct is created by the [`windows`] method on [slices].
4393 /// [`windows`]: ../../std/primitive.slice.html#method.windows
4394 /// [slices]: ../../std/primitive.slice.html
4396 #[stable(feature = "rust1", since = "1.0.0")]
4397 pub struct Windows<'a, T: 'a> {
4402 // FIXME(#26925) Remove in favor of `#[derive(Clone)]`
4403 #[stable(feature = "rust1", since = "1.0.0")]
4404 impl<T> Clone for Windows<'_, T> {
4405 fn clone(&self) -> Self {
4406 Windows { v: self.v, size: self.size }
4410 #[stable(feature = "rust1", since = "1.0.0")]
4411 impl<'a, T> Iterator for Windows<'a, T> {
4412 type Item = &'a [T];
4415 fn next(&mut self) -> Option<&'a [T]> {
4416 if self.size > self.v.len() {
4419 let ret = Some(&self.v[..self.size]);
4420 self.v = &self.v[1..];
4426 fn size_hint(&self) -> (usize, Option<usize>) {
4427 if self.size > self.v.len() {
4430 let size = self.v.len() - self.size + 1;
4436 fn count(self) -> usize {
4441 fn nth(&mut self, n: usize) -> Option<Self::Item> {
4442 let (end, overflow) = self.size.overflowing_add(n);
4443 if end > self.v.len() || overflow {
4447 let nth = &self.v[n..end];
4448 self.v = &self.v[n + 1..];
4454 fn last(self) -> Option<Self::Item> {
4455 if self.size > self.v.len() {
4458 let start = self.v.len() - self.size;
4459 Some(&self.v[start..])
4464 #[stable(feature = "rust1", since = "1.0.0")]
4465 impl<'a, T> DoubleEndedIterator for Windows<'a, T> {
4467 fn next_back(&mut self) -> Option<&'a [T]> {
4468 if self.size > self.v.len() {
4471 let ret = Some(&self.v[self.v.len() - self.size..]);
4472 self.v = &self.v[..self.v.len() - 1];
4478 fn nth_back(&mut self, n: usize) -> Option<Self::Item> {
4479 let (end, overflow) = self.v.len().overflowing_sub(n);
4480 if end < self.size || overflow {
4484 let ret = &self.v[end - self.size..end];
4485 self.v = &self.v[..end - 1];
4491 #[stable(feature = "rust1", since = "1.0.0")]
4492 impl<T> ExactSizeIterator for Windows<'_, T> {}
4494 #[unstable(feature = "trusted_len", issue = "37572")]
4495 unsafe impl<T> TrustedLen for Windows<'_, T> {}
4497 #[stable(feature = "fused", since = "1.26.0")]
4498 impl<T> FusedIterator for Windows<'_, T> {}
4501 unsafe impl<'a, T> TrustedRandomAccess for Windows<'a, T> {
4502 unsafe fn get_unchecked(&mut self, i: usize) -> &'a [T] {
4503 from_raw_parts(self.v.as_ptr().add(i), self.size)
4505 fn may_have_side_effect() -> bool {
4510 /// An iterator over a slice in (non-overlapping) chunks (`chunk_size` elements at a
4511 /// time), starting at the beginning of the slice.
4513 /// When the slice len is not evenly divided by the chunk size, the last slice
4514 /// of the iteration will be the remainder.
4516 /// This struct is created by the [`chunks`] method on [slices].
4518 /// [`chunks`]: ../../std/primitive.slice.html#method.chunks
4519 /// [slices]: ../../std/primitive.slice.html
4521 #[stable(feature = "rust1", since = "1.0.0")]
4522 pub struct Chunks<'a, T: 'a> {
4527 // FIXME(#26925) Remove in favor of `#[derive(Clone)]`
4528 #[stable(feature = "rust1", since = "1.0.0")]
4529 impl<T> Clone for Chunks<'_, T> {
4530 fn clone(&self) -> Self {
4531 Chunks { v: self.v, chunk_size: self.chunk_size }
4535 #[stable(feature = "rust1", since = "1.0.0")]
4536 impl<'a, T> Iterator for Chunks<'a, T> {
4537 type Item = &'a [T];
4540 fn next(&mut self) -> Option<&'a [T]> {
4541 if self.v.is_empty() {
4544 let chunksz = cmp::min(self.v.len(), self.chunk_size);
4545 let (fst, snd) = self.v.split_at(chunksz);
4552 fn size_hint(&self) -> (usize, Option<usize>) {
4553 if self.v.is_empty() {
4556 let n = self.v.len() / self.chunk_size;
4557 let rem = self.v.len() % self.chunk_size;
4558 let n = if rem > 0 { n + 1 } else { n };
4564 fn count(self) -> usize {
4569 fn nth(&mut self, n: usize) -> Option<Self::Item> {
4570 let (start, overflow) = n.overflowing_mul(self.chunk_size);
4571 if start >= self.v.len() || overflow {
4575 let end = match start.checked_add(self.chunk_size) {
4576 Some(sum) => cmp::min(self.v.len(), sum),
4577 None => self.v.len(),
4579 let nth = &self.v[start..end];
4580 self.v = &self.v[end..];
4586 fn last(self) -> Option<Self::Item> {
4587 if self.v.is_empty() {
4590 let start = (self.v.len() - 1) / self.chunk_size * self.chunk_size;
4591 Some(&self.v[start..])
4596 #[stable(feature = "rust1", since = "1.0.0")]
4597 impl<'a, T> DoubleEndedIterator for Chunks<'a, T> {
4599 fn next_back(&mut self) -> Option<&'a [T]> {
4600 if self.v.is_empty() {
4603 let remainder = self.v.len() % self.chunk_size;
4604 let chunksz = if remainder != 0 { remainder } else { self.chunk_size };
4605 let (fst, snd) = self.v.split_at(self.v.len() - chunksz);
4612 fn nth_back(&mut self, n: usize) -> Option<Self::Item> {
4613 let len = self.len();
4618 let start = (len - 1 - n) * self.chunk_size;
4619 let end = match start.checked_add(self.chunk_size) {
4620 Some(res) => cmp::min(res, self.v.len()),
4621 None => self.v.len(),
4623 let nth_back = &self.v[start..end];
4624 self.v = &self.v[..start];
4630 #[stable(feature = "rust1", since = "1.0.0")]
4631 impl<T> ExactSizeIterator for Chunks<'_, T> {}
4633 #[unstable(feature = "trusted_len", issue = "37572")]
4634 unsafe impl<T> TrustedLen for Chunks<'_, T> {}
4636 #[stable(feature = "fused", since = "1.26.0")]
4637 impl<T> FusedIterator for Chunks<'_, T> {}
4640 unsafe impl<'a, T> TrustedRandomAccess for Chunks<'a, T> {
4641 unsafe fn get_unchecked(&mut self, i: usize) -> &'a [T] {
4642 let start = i * self.chunk_size;
4643 let end = match start.checked_add(self.chunk_size) {
4644 None => self.v.len(),
4645 Some(end) => cmp::min(end, self.v.len()),
4647 from_raw_parts(self.v.as_ptr().add(start), end - start)
4649 fn may_have_side_effect() -> bool {
4654 /// An iterator over a slice in (non-overlapping) mutable chunks (`chunk_size`
4655 /// elements at a time), starting at the beginning of the slice.
4657 /// When the slice len is not evenly divided by the chunk size, the last slice
4658 /// of the iteration will be the remainder.
4660 /// This struct is created by the [`chunks_mut`] method on [slices].
4662 /// [`chunks_mut`]: ../../std/primitive.slice.html#method.chunks_mut
4663 /// [slices]: ../../std/primitive.slice.html
4665 #[stable(feature = "rust1", since = "1.0.0")]
4666 pub struct ChunksMut<'a, T: 'a> {
4671 #[stable(feature = "rust1", since = "1.0.0")]
4672 impl<'a, T> Iterator for ChunksMut<'a, T> {
4673 type Item = &'a mut [T];
4676 fn next(&mut self) -> Option<&'a mut [T]> {
4677 if self.v.is_empty() {
4680 let sz = cmp::min(self.v.len(), self.chunk_size);
4681 let tmp = mem::replace(&mut self.v, &mut []);
4682 let (head, tail) = tmp.split_at_mut(sz);
4689 fn size_hint(&self) -> (usize, Option<usize>) {
4690 if self.v.is_empty() {
4693 let n = self.v.len() / self.chunk_size;
4694 let rem = self.v.len() % self.chunk_size;
4695 let n = if rem > 0 { n + 1 } else { n };
4701 fn count(self) -> usize {
4706 fn nth(&mut self, n: usize) -> Option<&'a mut [T]> {
4707 let (start, overflow) = n.overflowing_mul(self.chunk_size);
4708 if start >= self.v.len() || overflow {
4712 let end = match start.checked_add(self.chunk_size) {
4713 Some(sum) => cmp::min(self.v.len(), sum),
4714 None => self.v.len(),
4716 let tmp = mem::replace(&mut self.v, &mut []);
4717 let (head, tail) = tmp.split_at_mut(end);
4718 let (_, nth) = head.split_at_mut(start);
4725 fn last(self) -> Option<Self::Item> {
4726 if self.v.is_empty() {
4729 let start = (self.v.len() - 1) / self.chunk_size * self.chunk_size;
4730 Some(&mut self.v[start..])
4735 #[stable(feature = "rust1", since = "1.0.0")]
4736 impl<'a, T> DoubleEndedIterator for ChunksMut<'a, T> {
4738 fn next_back(&mut self) -> Option<&'a mut [T]> {
4739 if self.v.is_empty() {
4742 let remainder = self.v.len() % self.chunk_size;
4743 let sz = if remainder != 0 { remainder } else { self.chunk_size };
4744 let tmp = mem::replace(&mut self.v, &mut []);
4745 let tmp_len = tmp.len();
4746 let (head, tail) = tmp.split_at_mut(tmp_len - sz);
4753 fn nth_back(&mut self, n: usize) -> Option<Self::Item> {
4754 let len = self.len();
4759 let start = (len - 1 - n) * self.chunk_size;
4760 let end = match start.checked_add(self.chunk_size) {
4761 Some(res) => cmp::min(res, self.v.len()),
4762 None => self.v.len(),
4764 let (temp, _tail) = mem::replace(&mut self.v, &mut []).split_at_mut(end);
4765 let (head, nth_back) = temp.split_at_mut(start);
4772 #[stable(feature = "rust1", since = "1.0.0")]
4773 impl<T> ExactSizeIterator for ChunksMut<'_, T> {}
4775 #[unstable(feature = "trusted_len", issue = "37572")]
4776 unsafe impl<T> TrustedLen for ChunksMut<'_, T> {}
4778 #[stable(feature = "fused", since = "1.26.0")]
4779 impl<T> FusedIterator for ChunksMut<'_, T> {}
4782 unsafe impl<'a, T> TrustedRandomAccess for ChunksMut<'a, T> {
4783 unsafe fn get_unchecked(&mut self, i: usize) -> &'a mut [T] {
4784 let start = i * self.chunk_size;
4785 let end = match start.checked_add(self.chunk_size) {
4786 None => self.v.len(),
4787 Some(end) => cmp::min(end, self.v.len()),
4789 from_raw_parts_mut(self.v.as_mut_ptr().add(start), end - start)
4791 fn may_have_side_effect() -> bool {
4796 /// An iterator over a slice in (non-overlapping) chunks (`chunk_size` elements at a
4797 /// time), starting at the beginning of the slice.
4799 /// When the slice len is not evenly divided by the chunk size, the last
4800 /// up to `chunk_size-1` elements will be omitted but can be retrieved from
4801 /// the [`remainder`] function from the iterator.
4803 /// This struct is created by the [`chunks_exact`] method on [slices].
4805 /// [`chunks_exact`]: ../../std/primitive.slice.html#method.chunks_exact
4806 /// [`remainder`]: ../../std/slice/struct.ChunksExact.html#method.remainder
4807 /// [slices]: ../../std/primitive.slice.html
4809 #[stable(feature = "chunks_exact", since = "1.31.0")]
4810 pub struct ChunksExact<'a, T: 'a> {
4816 impl<'a, T> ChunksExact<'a, T> {
4817 /// Returns the remainder of the original slice that is not going to be
4818 /// returned by the iterator. The returned slice has at most `chunk_size-1`
4820 #[stable(feature = "chunks_exact", since = "1.31.0")]
4821 pub fn remainder(&self) -> &'a [T] {
4826 // FIXME(#26925) Remove in favor of `#[derive(Clone)]`
4827 #[stable(feature = "chunks_exact", since = "1.31.0")]
4828 impl<T> Clone for ChunksExact<'_, T> {
4829 fn clone(&self) -> Self {
4830 ChunksExact { v: self.v, rem: self.rem, chunk_size: self.chunk_size }
4834 #[stable(feature = "chunks_exact", since = "1.31.0")]
4835 impl<'a, T> Iterator for ChunksExact<'a, T> {
4836 type Item = &'a [T];
4839 fn next(&mut self) -> Option<&'a [T]> {
4840 if self.v.len() < self.chunk_size {
4843 let (fst, snd) = self.v.split_at(self.chunk_size);
4850 fn size_hint(&self) -> (usize, Option<usize>) {
4851 let n = self.v.len() / self.chunk_size;
4856 fn count(self) -> usize {
4861 fn nth(&mut self, n: usize) -> Option<Self::Item> {
4862 let (start, overflow) = n.overflowing_mul(self.chunk_size);
4863 if start >= self.v.len() || overflow {
4867 let (_, snd) = self.v.split_at(start);
4874 fn last(mut self) -> Option<Self::Item> {
4879 #[stable(feature = "chunks_exact", since = "1.31.0")]
4880 impl<'a, T> DoubleEndedIterator for ChunksExact<'a, T> {
4882 fn next_back(&mut self) -> Option<&'a [T]> {
4883 if self.v.len() < self.chunk_size {
4886 let (fst, snd) = self.v.split_at(self.v.len() - self.chunk_size);
4893 fn nth_back(&mut self, n: usize) -> Option<Self::Item> {
4894 let len = self.len();
4899 let start = (len - 1 - n) * self.chunk_size;
4900 let end = start + self.chunk_size;
4901 let nth_back = &self.v[start..end];
4902 self.v = &self.v[..start];
4908 #[stable(feature = "chunks_exact", since = "1.31.0")]
4909 impl<T> ExactSizeIterator for ChunksExact<'_, T> {
4910 fn is_empty(&self) -> bool {
4915 #[unstable(feature = "trusted_len", issue = "37572")]
4916 unsafe impl<T> TrustedLen for ChunksExact<'_, T> {}
4918 #[stable(feature = "chunks_exact", since = "1.31.0")]
4919 impl<T> FusedIterator for ChunksExact<'_, T> {}
4922 #[stable(feature = "chunks_exact", since = "1.31.0")]
4923 unsafe impl<'a, T> TrustedRandomAccess for ChunksExact<'a, T> {
4924 unsafe fn get_unchecked(&mut self, i: usize) -> &'a [T] {
4925 let start = i * self.chunk_size;
4926 from_raw_parts(self.v.as_ptr().add(start), self.chunk_size)
4928 fn may_have_side_effect() -> bool {
4933 /// An iterator over a slice in (non-overlapping) mutable chunks (`chunk_size`
4934 /// elements at a time), starting at the beginning of the slice.
4936 /// When the slice len is not evenly divided by the chunk size, the last up to
4937 /// `chunk_size-1` elements will be omitted but can be retrieved from the
4938 /// [`into_remainder`] function from the iterator.
4940 /// This struct is created by the [`chunks_exact_mut`] method on [slices].
4942 /// [`chunks_exact_mut`]: ../../std/primitive.slice.html#method.chunks_exact_mut
4943 /// [`into_remainder`]: ../../std/slice/struct.ChunksExactMut.html#method.into_remainder
4944 /// [slices]: ../../std/primitive.slice.html
4946 #[stable(feature = "chunks_exact", since = "1.31.0")]
4947 pub struct ChunksExactMut<'a, T: 'a> {
4953 impl<'a, T> ChunksExactMut<'a, T> {
4954 /// Returns the remainder of the original slice that is not going to be
4955 /// returned by the iterator. The returned slice has at most `chunk_size-1`
4957 #[stable(feature = "chunks_exact", since = "1.31.0")]
4958 pub fn into_remainder(self) -> &'a mut [T] {
4963 #[stable(feature = "chunks_exact", since = "1.31.0")]
4964 impl<'a, T> Iterator for ChunksExactMut<'a, T> {
4965 type Item = &'a mut [T];
4968 fn next(&mut self) -> Option<&'a mut [T]> {
4969 if self.v.len() < self.chunk_size {
4972 let tmp = mem::replace(&mut self.v, &mut []);
4973 let (head, tail) = tmp.split_at_mut(self.chunk_size);
4980 fn size_hint(&self) -> (usize, Option<usize>) {
4981 let n = self.v.len() / self.chunk_size;
4986 fn count(self) -> usize {
4991 fn nth(&mut self, n: usize) -> Option<&'a mut [T]> {
4992 let (start, overflow) = n.overflowing_mul(self.chunk_size);
4993 if start >= self.v.len() || overflow {
4997 let tmp = mem::replace(&mut self.v, &mut []);
4998 let (_, snd) = tmp.split_at_mut(start);
5005 fn last(mut self) -> Option<Self::Item> {
5010 #[stable(feature = "chunks_exact", since = "1.31.0")]
5011 impl<'a, T> DoubleEndedIterator for ChunksExactMut<'a, T> {
5013 fn next_back(&mut self) -> Option<&'a mut [T]> {
5014 if self.v.len() < self.chunk_size {
5017 let tmp = mem::replace(&mut self.v, &mut []);
5018 let tmp_len = tmp.len();
5019 let (head, tail) = tmp.split_at_mut(tmp_len - self.chunk_size);
5026 fn nth_back(&mut self, n: usize) -> Option<Self::Item> {
5027 let len = self.len();
5032 let start = (len - 1 - n) * self.chunk_size;
5033 let end = start + self.chunk_size;
5034 let (temp, _tail) = mem::replace(&mut self.v, &mut []).split_at_mut(end);
5035 let (head, nth_back) = temp.split_at_mut(start);
5042 #[stable(feature = "chunks_exact", since = "1.31.0")]
5043 impl<T> ExactSizeIterator for ChunksExactMut<'_, T> {
5044 fn is_empty(&self) -> bool {
5049 #[unstable(feature = "trusted_len", issue = "37572")]
5050 unsafe impl<T> TrustedLen for ChunksExactMut<'_, T> {}
5052 #[stable(feature = "chunks_exact", since = "1.31.0")]
5053 impl<T> FusedIterator for ChunksExactMut<'_, T> {}
5056 #[stable(feature = "chunks_exact", since = "1.31.0")]
5057 unsafe impl<'a, T> TrustedRandomAccess for ChunksExactMut<'a, T> {
5058 unsafe fn get_unchecked(&mut self, i: usize) -> &'a mut [T] {
5059 let start = i * self.chunk_size;
5060 from_raw_parts_mut(self.v.as_mut_ptr().add(start), self.chunk_size)
5062 fn may_have_side_effect() -> bool {
5067 /// An iterator over a slice in (non-overlapping) chunks (`chunk_size` elements at a
5068 /// time), starting at the end of the slice.
5070 /// When the slice len is not evenly divided by the chunk size, the last slice
5071 /// of the iteration will be the remainder.
5073 /// This struct is created by the [`rchunks`] method on [slices].
5075 /// [`rchunks`]: ../../std/primitive.slice.html#method.rchunks
5076 /// [slices]: ../../std/primitive.slice.html
5078 #[stable(feature = "rchunks", since = "1.31.0")]
5079 pub struct RChunks<'a, T: 'a> {
5084 // FIXME(#26925) Remove in favor of `#[derive(Clone)]`
5085 #[stable(feature = "rchunks", since = "1.31.0")]
5086 impl<T> Clone for RChunks<'_, T> {
5087 fn clone(&self) -> Self {
5088 RChunks { v: self.v, chunk_size: self.chunk_size }
5092 #[stable(feature = "rchunks", since = "1.31.0")]
5093 impl<'a, T> Iterator for RChunks<'a, T> {
5094 type Item = &'a [T];
5097 fn next(&mut self) -> Option<&'a [T]> {
5098 if self.v.is_empty() {
5101 let chunksz = cmp::min(self.v.len(), self.chunk_size);
5102 let (fst, snd) = self.v.split_at(self.v.len() - chunksz);
5109 fn size_hint(&self) -> (usize, Option<usize>) {
5110 if self.v.is_empty() {
5113 let n = self.v.len() / self.chunk_size;
5114 let rem = self.v.len() % self.chunk_size;
5115 let n = if rem > 0 { n + 1 } else { n };
5121 fn count(self) -> usize {
5126 fn nth(&mut self, n: usize) -> Option<Self::Item> {
5127 let (end, overflow) = n.overflowing_mul(self.chunk_size);
5128 if end >= self.v.len() || overflow {
5132 // Can't underflow because of the check above
5133 let end = self.v.len() - end;
5134 let start = match end.checked_sub(self.chunk_size) {
5138 let nth = &self.v[start..end];
5139 self.v = &self.v[0..start];
5145 fn last(self) -> Option<Self::Item> {
5146 if self.v.is_empty() {
5149 let rem = self.v.len() % self.chunk_size;
5150 let end = if rem == 0 { self.chunk_size } else { rem };
5151 Some(&self.v[0..end])
5156 #[stable(feature = "rchunks", since = "1.31.0")]
5157 impl<'a, T> DoubleEndedIterator for RChunks<'a, T> {
5159 fn next_back(&mut self) -> Option<&'a [T]> {
5160 if self.v.is_empty() {
5163 let remainder = self.v.len() % self.chunk_size;
5164 let chunksz = if remainder != 0 { remainder } else { self.chunk_size };
5165 let (fst, snd) = self.v.split_at(chunksz);
5172 fn nth_back(&mut self, n: usize) -> Option<Self::Item> {
5173 let len = self.len();
5178 // can't underflow because `n < len`
5179 let offset_from_end = (len - 1 - n) * self.chunk_size;
5180 let end = self.v.len() - offset_from_end;
5181 let start = end.saturating_sub(self.chunk_size);
5182 let nth_back = &self.v[start..end];
5183 self.v = &self.v[end..];
5189 #[stable(feature = "rchunks", since = "1.31.0")]
5190 impl<T> ExactSizeIterator for RChunks<'_, T> {}
5192 #[unstable(feature = "trusted_len", issue = "37572")]
5193 unsafe impl<T> TrustedLen for RChunks<'_, T> {}
5195 #[stable(feature = "rchunks", since = "1.31.0")]
5196 impl<T> FusedIterator for RChunks<'_, T> {}
5199 #[stable(feature = "rchunks", since = "1.31.0")]
5200 unsafe impl<'a, T> TrustedRandomAccess for RChunks<'a, T> {
5201 unsafe fn get_unchecked(&mut self, i: usize) -> &'a [T] {
5202 let end = self.v.len() - i * self.chunk_size;
5203 let start = match end.checked_sub(self.chunk_size) {
5205 Some(start) => start,
5207 from_raw_parts(self.v.as_ptr().add(start), end - start)
5209 fn may_have_side_effect() -> bool {
5214 /// An iterator over a slice in (non-overlapping) mutable chunks (`chunk_size`
5215 /// elements at a time), starting at the end of the slice.
5217 /// When the slice len is not evenly divided by the chunk size, the last slice
5218 /// of the iteration will be the remainder.
5220 /// This struct is created by the [`rchunks_mut`] method on [slices].
5222 /// [`rchunks_mut`]: ../../std/primitive.slice.html#method.rchunks_mut
5223 /// [slices]: ../../std/primitive.slice.html
5225 #[stable(feature = "rchunks", since = "1.31.0")]
5226 pub struct RChunksMut<'a, T: 'a> {
5231 #[stable(feature = "rchunks", since = "1.31.0")]
5232 impl<'a, T> Iterator for RChunksMut<'a, T> {
5233 type Item = &'a mut [T];
5236 fn next(&mut self) -> Option<&'a mut [T]> {
5237 if self.v.is_empty() {
5240 let sz = cmp::min(self.v.len(), self.chunk_size);
5241 let tmp = mem::replace(&mut self.v, &mut []);
5242 let tmp_len = tmp.len();
5243 let (head, tail) = tmp.split_at_mut(tmp_len - sz);
5250 fn size_hint(&self) -> (usize, Option<usize>) {
5251 if self.v.is_empty() {
5254 let n = self.v.len() / self.chunk_size;
5255 let rem = self.v.len() % self.chunk_size;
5256 let n = if rem > 0 { n + 1 } else { n };
5262 fn count(self) -> usize {
5267 fn nth(&mut self, n: usize) -> Option<&'a mut [T]> {
5268 let (end, overflow) = n.overflowing_mul(self.chunk_size);
5269 if end >= self.v.len() || overflow {
5273 // Can't underflow because of the check above
5274 let end = self.v.len() - end;
5275 let start = match end.checked_sub(self.chunk_size) {
5279 let tmp = mem::replace(&mut self.v, &mut []);
5280 let (head, tail) = tmp.split_at_mut(start);
5281 let (nth, _) = tail.split_at_mut(end - start);
5288 fn last(self) -> Option<Self::Item> {
5289 if self.v.is_empty() {
5292 let rem = self.v.len() % self.chunk_size;
5293 let end = if rem == 0 { self.chunk_size } else { rem };
5294 Some(&mut self.v[0..end])
5299 #[stable(feature = "rchunks", since = "1.31.0")]
5300 impl<'a, T> DoubleEndedIterator for RChunksMut<'a, T> {
5302 fn next_back(&mut self) -> Option<&'a mut [T]> {
5303 if self.v.is_empty() {
5306 let remainder = self.v.len() % self.chunk_size;
5307 let sz = if remainder != 0 { remainder } else { self.chunk_size };
5308 let tmp = mem::replace(&mut self.v, &mut []);
5309 let (head, tail) = tmp.split_at_mut(sz);
5316 fn nth_back(&mut self, n: usize) -> Option<Self::Item> {
5317 let len = self.len();
5322 // can't underflow because `n < len`
5323 let offset_from_end = (len - 1 - n) * self.chunk_size;
5324 let end = self.v.len() - offset_from_end;
5325 let start = end.saturating_sub(self.chunk_size);
5326 let (tmp, tail) = mem::replace(&mut self.v, &mut []).split_at_mut(end);
5327 let (_, nth_back) = tmp.split_at_mut(start);
5334 #[stable(feature = "rchunks", since = "1.31.0")]
5335 impl<T> ExactSizeIterator for RChunksMut<'_, T> {}
5337 #[unstable(feature = "trusted_len", issue = "37572")]
5338 unsafe impl<T> TrustedLen for RChunksMut<'_, T> {}
5340 #[stable(feature = "rchunks", since = "1.31.0")]
5341 impl<T> FusedIterator for RChunksMut<'_, T> {}
5344 #[stable(feature = "rchunks", since = "1.31.0")]
5345 unsafe impl<'a, T> TrustedRandomAccess for RChunksMut<'a, T> {
5346 unsafe fn get_unchecked(&mut self, i: usize) -> &'a mut [T] {
5347 let end = self.v.len() - i * self.chunk_size;
5348 let start = match end.checked_sub(self.chunk_size) {
5350 Some(start) => start,
5352 from_raw_parts_mut(self.v.as_mut_ptr().add(start), end - start)
5354 fn may_have_side_effect() -> bool {
5359 /// An iterator over a slice in (non-overlapping) chunks (`chunk_size` elements at a
5360 /// time), starting at the end of the slice.
5362 /// When the slice len is not evenly divided by the chunk size, the last
5363 /// up to `chunk_size-1` elements will be omitted but can be retrieved from
5364 /// the [`remainder`] function from the iterator.
5366 /// This struct is created by the [`rchunks_exact`] method on [slices].
5368 /// [`rchunks_exact`]: ../../std/primitive.slice.html#method.rchunks_exact
5369 /// [`remainder`]: ../../std/slice/struct.ChunksExact.html#method.remainder
5370 /// [slices]: ../../std/primitive.slice.html
5372 #[stable(feature = "rchunks", since = "1.31.0")]
5373 pub struct RChunksExact<'a, T: 'a> {
5379 impl<'a, T> RChunksExact<'a, T> {
5380 /// Returns the remainder of the original slice that is not going to be
5381 /// returned by the iterator. The returned slice has at most `chunk_size-1`
5383 #[stable(feature = "rchunks", since = "1.31.0")]
5384 pub fn remainder(&self) -> &'a [T] {
5389 // FIXME(#26925) Remove in favor of `#[derive(Clone)]`
5390 #[stable(feature = "rchunks", since = "1.31.0")]
5391 impl<'a, T> Clone for RChunksExact<'a, T> {
5392 fn clone(&self) -> RChunksExact<'a, T> {
5393 RChunksExact { v: self.v, rem: self.rem, chunk_size: self.chunk_size }
5397 #[stable(feature = "rchunks", since = "1.31.0")]
5398 impl<'a, T> Iterator for RChunksExact<'a, T> {
5399 type Item = &'a [T];
5402 fn next(&mut self) -> Option<&'a [T]> {
5403 if self.v.len() < self.chunk_size {
5406 let (fst, snd) = self.v.split_at(self.v.len() - self.chunk_size);
5413 fn size_hint(&self) -> (usize, Option<usize>) {
5414 let n = self.v.len() / self.chunk_size;
5419 fn count(self) -> usize {
5424 fn nth(&mut self, n: usize) -> Option<Self::Item> {
5425 let (end, overflow) = n.overflowing_mul(self.chunk_size);
5426 if end >= self.v.len() || overflow {
5430 let (fst, _) = self.v.split_at(self.v.len() - end);
5437 fn last(mut self) -> Option<Self::Item> {
5442 #[stable(feature = "rchunks", since = "1.31.0")]
5443 impl<'a, T> DoubleEndedIterator for RChunksExact<'a, T> {
5445 fn next_back(&mut self) -> Option<&'a [T]> {
5446 if self.v.len() < self.chunk_size {
5449 let (fst, snd) = self.v.split_at(self.chunk_size);
5456 fn nth_back(&mut self, n: usize) -> Option<Self::Item> {
5457 let len = self.len();
5462 // now that we know that `n` corresponds to a chunk,
5463 // none of these operations can underflow/overflow
5464 let offset = (len - n) * self.chunk_size;
5465 let start = self.v.len() - offset;
5466 let end = start + self.chunk_size;
5467 let nth_back = &self.v[start..end];
5468 self.v = &self.v[end..];
5474 #[stable(feature = "rchunks", since = "1.31.0")]
5475 impl<'a, T> ExactSizeIterator for RChunksExact<'a, T> {
5476 fn is_empty(&self) -> bool {
5481 #[unstable(feature = "trusted_len", issue = "37572")]
5482 unsafe impl<T> TrustedLen for RChunksExact<'_, T> {}
5484 #[stable(feature = "rchunks", since = "1.31.0")]
5485 impl<T> FusedIterator for RChunksExact<'_, T> {}
5488 #[stable(feature = "rchunks", since = "1.31.0")]
5489 unsafe impl<'a, T> TrustedRandomAccess for RChunksExact<'a, T> {
5490 unsafe fn get_unchecked(&mut self, i: usize) -> &'a [T] {
5491 let end = self.v.len() - i * self.chunk_size;
5492 let start = end - self.chunk_size;
5493 from_raw_parts(self.v.as_ptr().add(start), self.chunk_size)
5495 fn may_have_side_effect() -> bool {
5500 /// An iterator over a slice in (non-overlapping) mutable chunks (`chunk_size`
5501 /// elements at a time), starting at the end of the slice.
5503 /// When the slice len is not evenly divided by the chunk size, the last up to
5504 /// `chunk_size-1` elements will be omitted but can be retrieved from the
5505 /// [`into_remainder`] function from the iterator.
5507 /// This struct is created by the [`rchunks_exact_mut`] method on [slices].
5509 /// [`rchunks_exact_mut`]: ../../std/primitive.slice.html#method.rchunks_exact_mut
5510 /// [`into_remainder`]: ../../std/slice/struct.ChunksExactMut.html#method.into_remainder
5511 /// [slices]: ../../std/primitive.slice.html
5513 #[stable(feature = "rchunks", since = "1.31.0")]
5514 pub struct RChunksExactMut<'a, T: 'a> {
5520 impl<'a, T> RChunksExactMut<'a, T> {
5521 /// Returns the remainder of the original slice that is not going to be
5522 /// returned by the iterator. The returned slice has at most `chunk_size-1`
5524 #[stable(feature = "rchunks", since = "1.31.0")]
5525 pub fn into_remainder(self) -> &'a mut [T] {
5530 #[stable(feature = "rchunks", since = "1.31.0")]
5531 impl<'a, T> Iterator for RChunksExactMut<'a, T> {
5532 type Item = &'a mut [T];
5535 fn next(&mut self) -> Option<&'a mut [T]> {
5536 if self.v.len() < self.chunk_size {
5539 let tmp = mem::replace(&mut self.v, &mut []);
5540 let tmp_len = tmp.len();
5541 let (head, tail) = tmp.split_at_mut(tmp_len - self.chunk_size);
5548 fn size_hint(&self) -> (usize, Option<usize>) {
5549 let n = self.v.len() / self.chunk_size;
5554 fn count(self) -> usize {
5559 fn nth(&mut self, n: usize) -> Option<&'a mut [T]> {
5560 let (end, overflow) = n.overflowing_mul(self.chunk_size);
5561 if end >= self.v.len() || overflow {
5565 let tmp = mem::replace(&mut self.v, &mut []);
5566 let tmp_len = tmp.len();
5567 let (fst, _) = tmp.split_at_mut(tmp_len - end);
5574 fn last(mut self) -> Option<Self::Item> {
5579 #[stable(feature = "rchunks", since = "1.31.0")]
5580 impl<'a, T> DoubleEndedIterator for RChunksExactMut<'a, T> {
5582 fn next_back(&mut self) -> Option<&'a mut [T]> {
5583 if self.v.len() < self.chunk_size {
5586 let tmp = mem::replace(&mut self.v, &mut []);
5587 let (head, tail) = tmp.split_at_mut(self.chunk_size);
5594 fn nth_back(&mut self, n: usize) -> Option<Self::Item> {
5595 let len = self.len();
5600 // now that we know that `n` corresponds to a chunk,
5601 // none of these operations can underflow/overflow
5602 let offset = (len - n) * self.chunk_size;
5603 let start = self.v.len() - offset;
5604 let end = start + self.chunk_size;
5605 let (tmp, tail) = mem::replace(&mut self.v, &mut []).split_at_mut(end);
5606 let (_, nth_back) = tmp.split_at_mut(start);
5613 #[stable(feature = "rchunks", since = "1.31.0")]
5614 impl<T> ExactSizeIterator for RChunksExactMut<'_, T> {
5615 fn is_empty(&self) -> bool {
5620 #[unstable(feature = "trusted_len", issue = "37572")]
5621 unsafe impl<T> TrustedLen for RChunksExactMut<'_, T> {}
5623 #[stable(feature = "rchunks", since = "1.31.0")]
5624 impl<T> FusedIterator for RChunksExactMut<'_, T> {}
5627 #[stable(feature = "rchunks", since = "1.31.0")]
5628 unsafe impl<'a, T> TrustedRandomAccess for RChunksExactMut<'a, T> {
5629 unsafe fn get_unchecked(&mut self, i: usize) -> &'a mut [T] {
5630 let end = self.v.len() - i * self.chunk_size;
5631 let start = end - self.chunk_size;
5632 from_raw_parts_mut(self.v.as_mut_ptr().add(start), self.chunk_size)
5634 fn may_have_side_effect() -> bool {
5643 /// Forms a slice from a pointer and a length.
5645 /// The `len` argument is the number of **elements**, not the number of bytes.
5649 /// Behavior is undefined if any of the following conditions are violated:
5651 /// * `data` must be [valid] for reads for `len * mem::size_of::<T>()` many bytes,
5652 /// and it must be properly aligned. This means in particular:
5654 /// * The entire memory range of this slice must be contained within a single allocated object!
5655 /// Slices can never span across multiple allocated objects.
5656 /// * `data` must be non-null and aligned even for zero-length slices. One
5657 /// reason for this is that enum layout optimizations may rely on references
5658 /// (including slices of any length) being aligned and non-null to distinguish
5659 /// them from other data. You can obtain a pointer that is usable as `data`
5660 /// for zero-length slices using [`NonNull::dangling()`].
5662 /// * The memory referenced by the returned slice must not be mutated for the duration
5663 /// of lifetime `'a`, except inside an `UnsafeCell`.
5665 /// * The total size `len * mem::size_of::<T>()` of the slice must be no larger than `isize::MAX`.
5666 /// See the safety documentation of [`pointer::offset`].
5670 /// The lifetime for the returned slice is inferred from its usage. To
5671 /// prevent accidental misuse, it's suggested to tie the lifetime to whichever
5672 /// source lifetime is safe in the context, such as by providing a helper
5673 /// function taking the lifetime of a host value for the slice, or by explicit
5681 /// // manifest a slice for a single element
5683 /// let ptr = &x as *const _;
5684 /// let slice = unsafe { slice::from_raw_parts(ptr, 1) };
5685 /// assert_eq!(slice[0], 42);
5688 /// [valid]: ../../std/ptr/index.html#safety
5689 /// [`NonNull::dangling()`]: ../../std/ptr/struct.NonNull.html#method.dangling
5690 /// [`pointer::offset`]: ../../std/primitive.pointer.html#method.offset
5692 #[stable(feature = "rust1", since = "1.0.0")]
5693 pub unsafe fn from_raw_parts<'a, T>(data: *const T, len: usize) -> &'a [T] {
5694 debug_assert!(is_aligned_and_not_null(data), "attempt to create unaligned or null slice");
5696 mem::size_of::<T>().saturating_mul(len) <= isize::MAX as usize,
5697 "attempt to create slice covering at least half the address space"
5699 &*ptr::slice_from_raw_parts(data, len)
5702 /// Performs the same functionality as [`from_raw_parts`], except that a
5703 /// mutable slice is returned.
5707 /// Behavior is undefined if any of the following conditions are violated:
5709 /// * `data` must be [valid] for writes for `len * mem::size_of::<T>()` many bytes,
5710 /// and it must be properly aligned. This means in particular:
5712 /// * The entire memory range of this slice must be contained within a single allocated object!
5713 /// Slices can never span across multiple allocated objects.
5714 /// * `data` must be non-null and aligned even for zero-length slices. One
5715 /// reason for this is that enum layout optimizations may rely on references
5716 /// (including slices of any length) being aligned and non-null to distinguish
5717 /// them from other data. You can obtain a pointer that is usable as `data`
5718 /// for zero-length slices using [`NonNull::dangling()`].
5720 /// * The memory referenced by the returned slice must not be accessed through any other pointer
5721 /// (not derived from the return value) for the duration of lifetime `'a`.
5722 /// Both read and write accesses are forbidden.
5724 /// * The total size `len * mem::size_of::<T>()` of the slice must be no larger than `isize::MAX`.
5725 /// See the safety documentation of [`pointer::offset`].
5727 /// [valid]: ../../std/ptr/index.html#safety
5728 /// [`NonNull::dangling()`]: ../../std/ptr/struct.NonNull.html#method.dangling
5729 /// [`pointer::offset`]: ../../std/primitive.pointer.html#method.offset
5730 /// [`from_raw_parts`]: ../../std/slice/fn.from_raw_parts.html
5732 #[stable(feature = "rust1", since = "1.0.0")]
5733 pub unsafe fn from_raw_parts_mut<'a, T>(data: *mut T, len: usize) -> &'a mut [T] {
5734 debug_assert!(is_aligned_and_not_null(data), "attempt to create unaligned or null slice");
5736 mem::size_of::<T>().saturating_mul(len) <= isize::MAX as usize,
5737 "attempt to create slice covering at least half the address space"
5739 &mut *ptr::slice_from_raw_parts_mut(data, len)
5742 /// Converts a reference to T into a slice of length 1 (without copying).
5743 #[stable(feature = "from_ref", since = "1.28.0")]
5744 pub fn from_ref<T>(s: &T) -> &[T] {
5745 unsafe { from_raw_parts(s, 1) }
5748 /// Converts a reference to T into a slice of length 1 (without copying).
5749 #[stable(feature = "from_ref", since = "1.28.0")]
5750 pub fn from_mut<T>(s: &mut T) -> &mut [T] {
5751 unsafe { from_raw_parts_mut(s, 1) }
5754 // This function is public only because there is no other way to unit test heapsort.
5755 #[unstable(feature = "sort_internals", reason = "internal to sort module", issue = "none")]
5757 pub fn heapsort<T, F>(v: &mut [T], mut is_less: F)
5759 F: FnMut(&T, &T) -> bool,
5761 sort::heapsort(v, &mut is_less);
5765 // Comparison traits
5769 /// Calls implementation provided memcmp.
5771 /// Interprets the data as u8.
5773 /// Returns 0 for equal, < 0 for less than and > 0 for greater
5775 // FIXME(#32610): Return type should be c_int
5776 fn memcmp(s1: *const u8, s2: *const u8, n: usize) -> i32;
5779 #[stable(feature = "rust1", since = "1.0.0")]
5780 impl<A, B> PartialEq<[B]> for [A]
5784 fn eq(&self, other: &[B]) -> bool {
5785 SlicePartialEq::equal(self, other)
5788 fn ne(&self, other: &[B]) -> bool {
5789 SlicePartialEq::not_equal(self, other)
5793 #[stable(feature = "rust1", since = "1.0.0")]
5794 impl<T: Eq> Eq for [T] {}
5796 /// Implements comparison of vectors lexicographically.
5797 #[stable(feature = "rust1", since = "1.0.0")]
5798 impl<T: Ord> Ord for [T] {
5799 fn cmp(&self, other: &[T]) -> Ordering {
5800 SliceOrd::compare(self, other)
5804 /// Implements comparison of vectors lexicographically.
5805 #[stable(feature = "rust1", since = "1.0.0")]
5806 impl<T: PartialOrd> PartialOrd for [T] {
5807 fn partial_cmp(&self, other: &[T]) -> Option<Ordering> {
5808 SlicePartialOrd::partial_compare(self, other)
5813 // intermediate trait for specialization of slice's PartialEq
5814 trait SlicePartialEq<B> {
5815 fn equal(&self, other: &[B]) -> bool;
5817 fn not_equal(&self, other: &[B]) -> bool {
5822 // Generic slice equality
5823 impl<A, B> SlicePartialEq<B> for [A]
5827 default fn equal(&self, other: &[B]) -> bool {
5828 if self.len() != other.len() {
5832 self.iter().zip(other.iter()).all(|(x, y)| x == y)
5836 // Use an equal-pointer optimization when types are `Eq`
5837 impl<A> SlicePartialEq<A> for [A]
5839 A: PartialEq<A> + Eq,
5841 default fn equal(&self, other: &[A]) -> bool {
5842 if self.len() != other.len() {
5846 if self.as_ptr() == other.as_ptr() {
5850 self.iter().zip(other.iter()).all(|(x, y)| x == y)
5854 // Use memcmp for bytewise equality when the types allow
5855 impl<A> SlicePartialEq<A> for [A]
5857 A: PartialEq<A> + BytewiseEquality,
5859 fn equal(&self, other: &[A]) -> bool {
5860 if self.len() != other.len() {
5863 if self.as_ptr() == other.as_ptr() {
5867 let size = mem::size_of_val(self);
5868 memcmp(self.as_ptr() as *const u8, other.as_ptr() as *const u8, size) == 0
5874 // intermediate trait for specialization of slice's PartialOrd
5875 trait SlicePartialOrd: Sized {
5876 fn partial_compare(left: &[Self], right: &[Self]) -> Option<Ordering>;
5879 impl<A: PartialOrd> SlicePartialOrd for A {
5880 default fn partial_compare(left: &[A], right: &[A]) -> Option<Ordering> {
5881 let l = cmp::min(left.len(), right.len());
5883 // Slice to the loop iteration range to enable bound check
5884 // elimination in the compiler
5885 let lhs = &left[..l];
5886 let rhs = &right[..l];
5889 match lhs[i].partial_cmp(&rhs[i]) {
5890 Some(Ordering::Equal) => (),
5891 non_eq => return non_eq,
5895 left.len().partial_cmp(&right.len())
5899 // This is the impl that we would like to have. Unfortunately it's not sound.
5900 // See `partial_ord_slice.rs`.
5902 impl<A> SlicePartialOrd for A
5906 default fn partial_compare(left: &[A], right: &[A]) -> Option<Ordering> {
5907 Some(SliceOrd::compare(left, right))
5912 impl<A: AlwaysApplicableOrd> SlicePartialOrd for A {
5913 fn partial_compare(left: &[A], right: &[A]) -> Option<Ordering> {
5914 Some(SliceOrd::compare(left, right))
5918 trait AlwaysApplicableOrd: SliceOrd + Ord {}
5920 macro_rules! always_applicable_ord {
5921 ($([$($p:tt)*] $t:ty,)*) => {
5922 $(impl<$($p)*> AlwaysApplicableOrd for $t {})*
5926 always_applicable_ord! {
5927 [] u8, [] u16, [] u32, [] u64, [] u128, [] usize,
5928 [] i8, [] i16, [] i32, [] i64, [] i128, [] isize,
5930 [T: ?Sized] *const T, [T: ?Sized] *mut T,
5931 [T: AlwaysApplicableOrd] &T,
5932 [T: AlwaysApplicableOrd] &mut T,
5933 [T: AlwaysApplicableOrd] Option<T>,
5937 // intermediate trait for specialization of slice's Ord
5938 trait SliceOrd: Sized {
5939 fn compare(left: &[Self], right: &[Self]) -> Ordering;
5942 impl<A: Ord> SliceOrd for A {
5943 default fn compare(left: &[Self], right: &[Self]) -> Ordering {
5944 let l = cmp::min(left.len(), right.len());
5946 // Slice to the loop iteration range to enable bound check
5947 // elimination in the compiler
5948 let lhs = &left[..l];
5949 let rhs = &right[..l];
5952 match lhs[i].cmp(&rhs[i]) {
5953 Ordering::Equal => (),
5954 non_eq => return non_eq,
5958 left.len().cmp(&right.len())
5962 // memcmp compares a sequence of unsigned bytes lexicographically.
5963 // this matches the order we want for [u8], but no others (not even [i8]).
5964 impl SliceOrd for u8 {
5966 fn compare(left: &[Self], right: &[Self]) -> Ordering {
5968 unsafe { memcmp(left.as_ptr(), right.as_ptr(), cmp::min(left.len(), right.len())) };
5970 left.len().cmp(&right.len())
5971 } else if order < 0 {
5980 /// Trait implemented for types that can be compared for equality using
5981 /// their bytewise representation
5982 trait BytewiseEquality: Eq + Copy {}
5984 macro_rules! impl_marker_for {
5985 ($traitname:ident, $($ty:ty)*) => {
5987 impl $traitname for $ty { }
5992 impl_marker_for!(BytewiseEquality,
5993 u8 i8 u16 i16 u32 i32 u64 i64 u128 i128 usize isize char bool);
5996 unsafe impl<'a, T> TrustedRandomAccess for Iter<'a, T> {
5997 unsafe fn get_unchecked(&mut self, i: usize) -> &'a T {
5998 &*self.ptr.as_ptr().add(i)
6000 fn may_have_side_effect() -> bool {
6006 unsafe impl<'a, T> TrustedRandomAccess for IterMut<'a, T> {
6007 unsafe fn get_unchecked(&mut self, i: usize) -> &'a mut T {
6008 &mut *self.ptr.as_ptr().add(i)
6010 fn may_have_side_effect() -> bool {
6015 trait SliceContains: Sized {
6016 fn slice_contains(&self, x: &[Self]) -> bool;
6019 impl<T> SliceContains for T
6023 default fn slice_contains(&self, x: &[Self]) -> bool {
6024 x.iter().any(|y| *y == *self)
6028 impl SliceContains for u8 {
6029 fn slice_contains(&self, x: &[Self]) -> bool {
6030 memchr::memchr(*self, x).is_some()
6034 impl SliceContains for i8 {
6035 fn slice_contains(&self, x: &[Self]) -> bool {
6036 let byte = *self as u8;
6037 let bytes: &[u8] = unsafe { from_raw_parts(x.as_ptr() as *const u8, x.len()) };
6038 memchr::memchr(byte, bytes).is_some()