1 // ignore-tidy-filelength
3 //! Slice management and manipulation.
5 //! For more details see [`std::slice`].
7 //! [`std::slice`]: ../../std/slice/index.html
9 #![stable(feature = "rust1", since = "1.0.0")]
11 use crate::cmp::Ordering::{self, Equal, Greater, Less};
12 use crate::intrinsics::assume;
13 use crate::marker::{self, Copy};
15 use crate::ops::{FnMut, Range, RangeBounds};
16 use crate::option::Option;
17 use crate::option::Option::{None, Some};
18 use crate::ptr::{self, NonNull};
19 use crate::result::Result;
20 use crate::result::Result::{Err, Ok};
23 feature = "slice_internals",
25 reason = "exposed from core to be reused in std; use the memchr crate"
27 /// Pure rust memchr implementation, taken from rust-memchr
38 use iter::GenericSplitN;
40 #[stable(feature = "rust1", since = "1.0.0")]
41 pub use iter::{Chunks, ChunksMut, Windows};
42 #[stable(feature = "rust1", since = "1.0.0")]
43 pub use iter::{Iter, IterMut};
44 #[stable(feature = "rust1", since = "1.0.0")]
45 pub use iter::{RSplitN, RSplitNMut, Split, SplitMut, SplitN, SplitNMut};
47 #[stable(feature = "slice_rsplit", since = "1.27.0")]
48 pub use iter::{RSplit, RSplitMut};
50 #[stable(feature = "chunks_exact", since = "1.31.0")]
51 pub use iter::{ChunksExact, ChunksExactMut};
53 #[stable(feature = "rchunks", since = "1.31.0")]
54 pub use iter::{RChunks, RChunksExact, RChunksExactMut, RChunksMut};
56 #[unstable(feature = "array_chunks", issue = "74985")]
57 pub use iter::{ArrayChunks, ArrayChunksMut};
59 #[unstable(feature = "array_windows", issue = "75027")]
60 pub use iter::ArrayWindows;
62 #[unstable(feature = "split_inclusive", issue = "72360")]
63 pub use iter::{SplitInclusive, SplitInclusiveMut};
65 #[stable(feature = "rust1", since = "1.0.0")]
66 pub use raw::{from_raw_parts, from_raw_parts_mut};
68 #[stable(feature = "from_ref", since = "1.28.0")]
69 pub use raw::{from_mut, from_ref};
71 // This function is public only because there is no other way to unit test heapsort.
72 #[unstable(feature = "sort_internals", reason = "internal to sort module", issue = "none")]
73 pub use sort::heapsort;
75 #[stable(feature = "slice_get_slice", since = "1.28.0")]
76 pub use index::SliceIndex;
78 #[unstable(feature = "slice_check_range", issue = "76393")]
79 pub use index::check_range;
84 /// Returns the number of elements in the slice.
89 /// let a = [1, 2, 3];
90 /// assert_eq!(a.len(), 3);
92 #[stable(feature = "rust1", since = "1.0.0")]
93 #[rustc_const_stable(feature = "const_slice_len", since = "1.32.0")]
95 // SAFETY: const sound because we transmute out the length field as a usize (which it must be)
96 #[allow_internal_unstable(const_fn_union)]
97 pub const fn len(&self) -> usize {
98 // SAFETY: this is safe because `&[T]` and `FatPtr<T>` have the same layout.
99 // Only `std` can make this guarantee.
100 unsafe { crate::ptr::Repr { rust: self }.raw.len }
103 /// Returns `true` if the slice has a length of 0.
108 /// let a = [1, 2, 3];
109 /// assert!(!a.is_empty());
111 #[stable(feature = "rust1", since = "1.0.0")]
112 #[rustc_const_stable(feature = "const_slice_is_empty", since = "1.32.0")]
114 pub const fn is_empty(&self) -> bool {
118 /// Returns the first element of the slice, or `None` if it is empty.
123 /// let v = [10, 40, 30];
124 /// assert_eq!(Some(&10), v.first());
126 /// let w: &[i32] = &[];
127 /// assert_eq!(None, w.first());
129 #[stable(feature = "rust1", since = "1.0.0")]
131 pub fn first(&self) -> Option<&T> {
132 if let [first, ..] = self { Some(first) } else { None }
135 /// Returns a mutable pointer to the first element of the slice, or `None` if it is empty.
140 /// let x = &mut [0, 1, 2];
142 /// if let Some(first) = x.first_mut() {
145 /// assert_eq!(x, &[5, 1, 2]);
147 #[stable(feature = "rust1", since = "1.0.0")]
149 pub fn first_mut(&mut self) -> Option<&mut T> {
150 if let [first, ..] = self { Some(first) } else { None }
153 /// Returns the first and all the rest of the elements of the slice, or `None` if it is empty.
158 /// let x = &[0, 1, 2];
160 /// if let Some((first, elements)) = x.split_first() {
161 /// assert_eq!(first, &0);
162 /// assert_eq!(elements, &[1, 2]);
165 #[stable(feature = "slice_splits", since = "1.5.0")]
167 pub fn split_first(&self) -> Option<(&T, &[T])> {
168 if let [first, tail @ ..] = self { Some((first, tail)) } else { None }
171 /// Returns the first and all the rest of the elements of the slice, or `None` if it is empty.
176 /// let x = &mut [0, 1, 2];
178 /// if let Some((first, elements)) = x.split_first_mut() {
183 /// assert_eq!(x, &[3, 4, 5]);
185 #[stable(feature = "slice_splits", since = "1.5.0")]
187 pub fn split_first_mut(&mut self) -> Option<(&mut T, &mut [T])> {
188 if let [first, tail @ ..] = self { Some((first, tail)) } else { None }
191 /// Returns the last and all the rest of the elements of the slice, or `None` if it is empty.
196 /// let x = &[0, 1, 2];
198 /// if let Some((last, elements)) = x.split_last() {
199 /// assert_eq!(last, &2);
200 /// assert_eq!(elements, &[0, 1]);
203 #[stable(feature = "slice_splits", since = "1.5.0")]
205 pub fn split_last(&self) -> Option<(&T, &[T])> {
206 if let [init @ .., last] = self { Some((last, init)) } else { None }
209 /// Returns the last and all the rest of the elements of the slice, or `None` if it is empty.
214 /// let x = &mut [0, 1, 2];
216 /// if let Some((last, elements)) = x.split_last_mut() {
221 /// assert_eq!(x, &[4, 5, 3]);
223 #[stable(feature = "slice_splits", since = "1.5.0")]
225 pub fn split_last_mut(&mut self) -> Option<(&mut T, &mut [T])> {
226 if let [init @ .., last] = self { Some((last, init)) } else { None }
229 /// Returns the last element of the slice, or `None` if it is empty.
234 /// let v = [10, 40, 30];
235 /// assert_eq!(Some(&30), v.last());
237 /// let w: &[i32] = &[];
238 /// assert_eq!(None, w.last());
240 #[stable(feature = "rust1", since = "1.0.0")]
242 pub fn last(&self) -> Option<&T> {
243 if let [.., last] = self { Some(last) } else { None }
246 /// Returns a mutable pointer to the last item in the slice.
251 /// let x = &mut [0, 1, 2];
253 /// if let Some(last) = x.last_mut() {
256 /// assert_eq!(x, &[0, 1, 10]);
258 #[stable(feature = "rust1", since = "1.0.0")]
260 pub fn last_mut(&mut self) -> Option<&mut T> {
261 if let [.., last] = self { Some(last) } else { None }
264 /// Returns a reference to an element or subslice depending on the type of
267 /// - If given a position, returns a reference to the element at that
268 /// position or `None` if out of bounds.
269 /// - If given a range, returns the subslice corresponding to that range,
270 /// or `None` if out of bounds.
275 /// let v = [10, 40, 30];
276 /// assert_eq!(Some(&40), v.get(1));
277 /// assert_eq!(Some(&[10, 40][..]), v.get(0..2));
278 /// assert_eq!(None, v.get(3));
279 /// assert_eq!(None, v.get(0..4));
281 #[stable(feature = "rust1", since = "1.0.0")]
283 pub fn get<I>(&self, index: I) -> Option<&I::Output>
290 /// Returns a mutable reference to an element or subslice depending on the
291 /// type of index (see [`get`]) or `None` if the index is out of bounds.
293 /// [`get`]: #method.get
298 /// let x = &mut [0, 1, 2];
300 /// if let Some(elem) = x.get_mut(1) {
303 /// assert_eq!(x, &[0, 42, 2]);
305 #[stable(feature = "rust1", since = "1.0.0")]
307 pub fn get_mut<I>(&mut self, index: I) -> Option<&mut I::Output>
314 /// Returns a reference to an element or subslice, without doing bounds
317 /// For a safe alternative see [`get`].
321 /// Calling this method with an out-of-bounds index is *[undefined behavior]*
322 /// even if the resulting reference is not used.
324 /// [`get`]: #method.get
325 /// [undefined behavior]: https://doc.rust-lang.org/reference/behavior-considered-undefined.html
330 /// let x = &[1, 2, 4];
333 /// assert_eq!(x.get_unchecked(1), &2);
336 #[stable(feature = "rust1", since = "1.0.0")]
338 pub unsafe fn get_unchecked<I>(&self, index: I) -> &I::Output
342 // SAFETY: the caller must uphold most of the safety requirements for `get_unchecked`;
343 // the slice is dereferencable because `self` is a safe reference.
344 // The returned pointer is safe because impls of `SliceIndex` have to guarantee that it is.
345 unsafe { &*index.get_unchecked(self) }
348 /// Returns a mutable reference to an element or subslice, without doing
351 /// For a safe alternative see [`get_mut`].
355 /// Calling this method with an out-of-bounds index is *[undefined behavior]*
356 /// even if the resulting reference is not used.
358 /// [`get_mut`]: #method.get_mut
359 /// [undefined behavior]: https://doc.rust-lang.org/reference/behavior-considered-undefined.html
364 /// let x = &mut [1, 2, 4];
367 /// let elem = x.get_unchecked_mut(1);
370 /// assert_eq!(x, &[1, 13, 4]);
372 #[stable(feature = "rust1", since = "1.0.0")]
374 pub unsafe fn get_unchecked_mut<I>(&mut self, index: I) -> &mut I::Output
378 // SAFETY: the caller must uphold the safety requirements for `get_unchecked_mut`;
379 // the slice is dereferencable because `self` is a safe reference.
380 // The returned pointer is safe because impls of `SliceIndex` have to guarantee that it is.
381 unsafe { &mut *index.get_unchecked_mut(self) }
384 /// Returns a raw pointer to the slice's buffer.
386 /// The caller must ensure that the slice outlives the pointer this
387 /// function returns, or else it will end up pointing to garbage.
389 /// The caller must also ensure that the memory the pointer (non-transitively) points to
390 /// is never written to (except inside an `UnsafeCell`) using this pointer or any pointer
391 /// derived from it. If you need to mutate the contents of the slice, use [`as_mut_ptr`].
393 /// Modifying the container referenced by this slice may cause its buffer
394 /// to be reallocated, which would also make any pointers to it invalid.
399 /// let x = &[1, 2, 4];
400 /// let x_ptr = x.as_ptr();
403 /// for i in 0..x.len() {
404 /// assert_eq!(x.get_unchecked(i), &*x_ptr.add(i));
409 /// [`as_mut_ptr`]: #method.as_mut_ptr
410 #[stable(feature = "rust1", since = "1.0.0")]
411 #[rustc_const_stable(feature = "const_slice_as_ptr", since = "1.32.0")]
413 pub const fn as_ptr(&self) -> *const T {
414 self as *const [T] as *const T
417 /// Returns an unsafe mutable pointer to the slice's buffer.
419 /// The caller must ensure that the slice outlives the pointer this
420 /// function returns, or else it will end up pointing to garbage.
422 /// Modifying the container referenced by this slice may cause its buffer
423 /// to be reallocated, which would also make any pointers to it invalid.
428 /// let x = &mut [1, 2, 4];
429 /// let x_ptr = x.as_mut_ptr();
432 /// for i in 0..x.len() {
433 /// *x_ptr.add(i) += 2;
436 /// assert_eq!(x, &[3, 4, 6]);
438 #[stable(feature = "rust1", since = "1.0.0")]
440 pub fn as_mut_ptr(&mut self) -> *mut T {
441 self as *mut [T] as *mut T
444 /// Returns the two raw pointers spanning the slice.
446 /// The returned range is half-open, which means that the end pointer
447 /// points *one past* the last element of the slice. This way, an empty
448 /// slice is represented by two equal pointers, and the difference between
449 /// the two pointers represents the size of the slice.
451 /// See [`as_ptr`] for warnings on using these pointers. The end pointer
452 /// requires extra caution, as it does not point to a valid element in the
455 /// This function is useful for interacting with foreign interfaces which
456 /// use two pointers to refer to a range of elements in memory, as is
459 /// It can also be useful to check if a pointer to an element refers to an
460 /// element of this slice:
463 /// #![feature(slice_ptr_range)]
465 /// let a = [1, 2, 3];
466 /// let x = &a[1] as *const _;
467 /// let y = &5 as *const _;
469 /// assert!(a.as_ptr_range().contains(&x));
470 /// assert!(!a.as_ptr_range().contains(&y));
473 /// [`as_ptr`]: #method.as_ptr
474 #[unstable(feature = "slice_ptr_range", issue = "65807")]
476 pub fn as_ptr_range(&self) -> Range<*const T> {
477 let start = self.as_ptr();
478 // SAFETY: The `add` here is safe, because:
480 // - Both pointers are part of the same object, as pointing directly
481 // past the object also counts.
483 // - The size of the slice is never larger than isize::MAX bytes, as
485 // - https://github.com/rust-lang/unsafe-code-guidelines/issues/102#issuecomment-473340447
486 // - https://doc.rust-lang.org/reference/behavior-considered-undefined.html
487 // - https://doc.rust-lang.org/core/slice/fn.from_raw_parts.html#safety
488 // (This doesn't seem normative yet, but the very same assumption is
489 // made in many places, including the Index implementation of slices.)
491 // - There is no wrapping around involved, as slices do not wrap past
492 // the end of the address space.
494 // See the documentation of pointer::add.
495 let end = unsafe { start.add(self.len()) };
499 /// Returns the two unsafe mutable pointers spanning the slice.
501 /// The returned range is half-open, which means that the end pointer
502 /// points *one past* the last element of the slice. This way, an empty
503 /// slice is represented by two equal pointers, and the difference between
504 /// the two pointers represents the size of the slice.
506 /// See [`as_mut_ptr`] for warnings on using these pointers. The end
507 /// pointer requires extra caution, as it does not point to a valid element
510 /// This function is useful for interacting with foreign interfaces which
511 /// use two pointers to refer to a range of elements in memory, as is
514 /// [`as_mut_ptr`]: #method.as_mut_ptr
515 #[unstable(feature = "slice_ptr_range", issue = "65807")]
517 pub fn as_mut_ptr_range(&mut self) -> Range<*mut T> {
518 let start = self.as_mut_ptr();
519 // SAFETY: See as_ptr_range() above for why `add` here is safe.
520 let end = unsafe { start.add(self.len()) };
524 /// Swaps two elements in the slice.
528 /// * a - The index of the first element
529 /// * b - The index of the second element
533 /// Panics if `a` or `b` are out of bounds.
538 /// let mut v = ["a", "b", "c", "d"];
540 /// assert!(v == ["a", "d", "c", "b"]);
542 #[stable(feature = "rust1", since = "1.0.0")]
544 pub fn swap(&mut self, a: usize, b: usize) {
545 // Can't take two mutable loans from one vector, so instead just cast
546 // them to their raw pointers to do the swap.
547 let pa: *mut T = &mut self[a];
548 let pb: *mut T = &mut self[b];
549 // SAFETY: `pa` and `pb` have been created from safe mutable references and refer
550 // to elements in the slice and therefore are guaranteed to be valid and aligned.
551 // Note that accessing the elements behind `a` and `b` is checked and will
552 // panic when out of bounds.
558 /// Reverses the order of elements in the slice, in place.
563 /// let mut v = [1, 2, 3];
565 /// assert!(v == [3, 2, 1]);
567 #[stable(feature = "rust1", since = "1.0.0")]
569 pub fn reverse(&mut self) {
570 let mut i: usize = 0;
573 // For very small types, all the individual reads in the normal
574 // path perform poorly. We can do better, given efficient unaligned
575 // load/store, by loading a larger chunk and reversing a register.
577 // Ideally LLVM would do this for us, as it knows better than we do
578 // whether unaligned reads are efficient (since that changes between
579 // different ARM versions, for example) and what the best chunk size
580 // would be. Unfortunately, as of LLVM 4.0 (2017-05) it only unrolls
581 // the loop, so we need to do this ourselves. (Hypothesis: reverse
582 // is troublesome because the sides can be aligned differently --
583 // will be, when the length is odd -- so there's no way of emitting
584 // pre- and postludes to use fully-aligned SIMD in the middle.)
586 let fast_unaligned = cfg!(any(target_arch = "x86", target_arch = "x86_64"));
588 if fast_unaligned && mem::size_of::<T>() == 1 {
589 // Use the llvm.bswap intrinsic to reverse u8s in a usize
590 let chunk = mem::size_of::<usize>();
591 while i + chunk - 1 < ln / 2 {
592 // SAFETY: There are several things to check here:
594 // - Note that `chunk` is either 4 or 8 due to the cfg check
595 // above. So `chunk - 1` is positive.
596 // - Indexing with index `i` is fine as the loop check guarantees
597 // `i + chunk - 1 < ln / 2`
598 // <=> `i < ln / 2 - (chunk - 1) < ln / 2 < ln`.
599 // - Indexing with index `ln - i - chunk = ln - (i + chunk)` is fine:
600 // - `i + chunk > 0` is trivially true.
601 // - The loop check guarantees:
602 // `i + chunk - 1 < ln / 2`
603 // <=> `i + chunk ≤ ln / 2 ≤ ln`, thus subtraction does not underflow.
604 // - The `read_unaligned` and `write_unaligned` calls are fine:
605 // - `pa` points to index `i` where `i < ln / 2 - (chunk - 1)`
606 // (see above) and `pb` points to index `ln - i - chunk`, so
607 // both are at least `chunk`
608 // many bytes away from the end of `self`.
609 // - Any initialized memory is valid `usize`.
611 let pa: *mut T = self.get_unchecked_mut(i);
612 let pb: *mut T = self.get_unchecked_mut(ln - i - chunk);
613 let va = ptr::read_unaligned(pa as *mut usize);
614 let vb = ptr::read_unaligned(pb as *mut usize);
615 ptr::write_unaligned(pa as *mut usize, vb.swap_bytes());
616 ptr::write_unaligned(pb as *mut usize, va.swap_bytes());
622 if fast_unaligned && mem::size_of::<T>() == 2 {
623 // Use rotate-by-16 to reverse u16s in a u32
624 let chunk = mem::size_of::<u32>() / 2;
625 while i + chunk - 1 < ln / 2 {
626 // SAFETY: An unaligned u32 can be read from `i` if `i + 1 < ln`
627 // (and obviously `i < ln`), because each element is 2 bytes and
630 // `i + chunk - 1 < ln / 2` # while condition
631 // `i + 2 - 1 < ln / 2`
634 // Since it's less than the length divided by 2, then it must be
637 // This also means that the condition `0 < i + chunk <= ln` is
638 // always respected, ensuring the `pb` pointer can be used
641 let pa: *mut T = self.get_unchecked_mut(i);
642 let pb: *mut T = self.get_unchecked_mut(ln - i - chunk);
643 let va = ptr::read_unaligned(pa as *mut u32);
644 let vb = ptr::read_unaligned(pb as *mut u32);
645 ptr::write_unaligned(pa as *mut u32, vb.rotate_left(16));
646 ptr::write_unaligned(pb as *mut u32, va.rotate_left(16));
653 // SAFETY: `i` is inferior to half the length of the slice so
654 // accessing `i` and `ln - i - 1` is safe (`i` starts at 0 and
655 // will not go further than `ln / 2 - 1`).
656 // The resulting pointers `pa` and `pb` are therefore valid and
657 // aligned, and can be read from and written to.
659 // Unsafe swap to avoid the bounds check in safe swap.
660 let pa: *mut T = self.get_unchecked_mut(i);
661 let pb: *mut T = self.get_unchecked_mut(ln - i - 1);
668 /// Returns an iterator over the slice.
673 /// let x = &[1, 2, 4];
674 /// let mut iterator = x.iter();
676 /// assert_eq!(iterator.next(), Some(&1));
677 /// assert_eq!(iterator.next(), Some(&2));
678 /// assert_eq!(iterator.next(), Some(&4));
679 /// assert_eq!(iterator.next(), None);
681 #[stable(feature = "rust1", since = "1.0.0")]
683 pub fn iter(&self) -> Iter<'_, T> {
684 let ptr = self.as_ptr();
685 // SAFETY: There are several things here:
687 // `ptr` has been obtained by `self.as_ptr()` where `self` is a valid
688 // reference thus it is non-NUL and safe to use and pass to
689 // `NonNull::new_unchecked` .
691 // Adding `self.len()` to the starting pointer gives a pointer
692 // at the end of `self`. `end` will never be dereferenced, only checked
693 // for direct pointer equality with `ptr` to check if the iterator is
696 // In the case of a ZST, the end pointer is just the start pointer plus
697 // the length, to also allows for the fast `ptr == end` check.
699 // See the `next_unchecked!` and `is_empty!` macros as well as the
700 // `post_inc_start` method for more informations.
702 assume(!ptr.is_null());
704 let end = if mem::size_of::<T>() == 0 {
705 (ptr as *const u8).wrapping_add(self.len()) as *const T
710 Iter { ptr: NonNull::new_unchecked(ptr as *mut T), end, _marker: marker::PhantomData }
714 /// Returns an iterator that allows modifying each value.
719 /// let x = &mut [1, 2, 4];
720 /// for elem in x.iter_mut() {
723 /// assert_eq!(x, &[3, 4, 6]);
725 #[stable(feature = "rust1", since = "1.0.0")]
727 pub fn iter_mut(&mut self) -> IterMut<'_, T> {
728 let ptr = self.as_mut_ptr();
729 // SAFETY: There are several things here:
731 // `ptr` has been obtained by `self.as_ptr()` where `self` is a valid
732 // reference thus it is non-NUL and safe to use and pass to
733 // `NonNull::new_unchecked` .
735 // Adding `self.len()` to the starting pointer gives a pointer
736 // at the end of `self`. `end` will never be dereferenced, only checked
737 // for direct pointer equality with `ptr` to check if the iterator is
740 // In the case of a ZST, the end pointer is just the start pointer plus
741 // the length, to also allows for the fast `ptr == end` check.
743 // See the `next_unchecked!` and `is_empty!` macros as well as the
744 // `post_inc_start` method for more informations.
746 assume(!ptr.is_null());
748 let end = if mem::size_of::<T>() == 0 {
749 (ptr as *mut u8).wrapping_add(self.len()) as *mut T
754 IterMut { ptr: NonNull::new_unchecked(ptr), end, _marker: marker::PhantomData }
758 /// Returns an iterator over all contiguous windows of length
759 /// `size`. The windows overlap. If the slice is shorter than
760 /// `size`, the iterator returns no values.
764 /// Panics if `size` is 0.
769 /// let slice = ['r', 'u', 's', 't'];
770 /// let mut iter = slice.windows(2);
771 /// assert_eq!(iter.next().unwrap(), &['r', 'u']);
772 /// assert_eq!(iter.next().unwrap(), &['u', 's']);
773 /// assert_eq!(iter.next().unwrap(), &['s', 't']);
774 /// assert!(iter.next().is_none());
777 /// If the slice is shorter than `size`:
780 /// let slice = ['f', 'o', 'o'];
781 /// let mut iter = slice.windows(4);
782 /// assert!(iter.next().is_none());
784 #[stable(feature = "rust1", since = "1.0.0")]
786 pub fn windows(&self, size: usize) -> Windows<'_, T> {
788 Windows { v: self, size }
791 /// Returns an iterator over `chunk_size` elements of the slice at a time, starting at the
792 /// beginning of the slice.
794 /// The chunks are slices and do not overlap. If `chunk_size` does not divide the length of the
795 /// slice, then the last chunk will not have length `chunk_size`.
797 /// See [`chunks_exact`] for a variant of this iterator that returns chunks of always exactly
798 /// `chunk_size` elements, and [`rchunks`] for the same iterator but starting at the end of the
803 /// Panics if `chunk_size` is 0.
808 /// let slice = ['l', 'o', 'r', 'e', 'm'];
809 /// let mut iter = slice.chunks(2);
810 /// assert_eq!(iter.next().unwrap(), &['l', 'o']);
811 /// assert_eq!(iter.next().unwrap(), &['r', 'e']);
812 /// assert_eq!(iter.next().unwrap(), &['m']);
813 /// assert!(iter.next().is_none());
816 /// [`chunks_exact`]: #method.chunks_exact
817 /// [`rchunks`]: #method.rchunks
818 #[stable(feature = "rust1", since = "1.0.0")]
820 pub fn chunks(&self, chunk_size: usize) -> Chunks<'_, T> {
821 assert_ne!(chunk_size, 0);
822 Chunks { v: self, chunk_size }
825 /// Returns an iterator over `chunk_size` elements of the slice at a time, starting at the
826 /// beginning of the slice.
828 /// The chunks are mutable slices, and do not overlap. If `chunk_size` does not divide the
829 /// length of the slice, then the last chunk will not have length `chunk_size`.
831 /// See [`chunks_exact_mut`] for a variant of this iterator that returns chunks of always
832 /// exactly `chunk_size` elements, and [`rchunks_mut`] for the same iterator but starting at
833 /// the end of the slice.
837 /// Panics if `chunk_size` is 0.
842 /// let v = &mut [0, 0, 0, 0, 0];
843 /// let mut count = 1;
845 /// for chunk in v.chunks_mut(2) {
846 /// for elem in chunk.iter_mut() {
851 /// assert_eq!(v, &[1, 1, 2, 2, 3]);
854 /// [`chunks_exact_mut`]: #method.chunks_exact_mut
855 /// [`rchunks_mut`]: #method.rchunks_mut
856 #[stable(feature = "rust1", since = "1.0.0")]
858 pub fn chunks_mut(&mut self, chunk_size: usize) -> ChunksMut<'_, T> {
859 assert_ne!(chunk_size, 0);
860 ChunksMut { v: self, chunk_size }
863 /// Returns an iterator over `chunk_size` elements of the slice at a time, starting at the
864 /// beginning of the slice.
866 /// The chunks are slices and do not overlap. If `chunk_size` does not divide the length of the
867 /// slice, then the last up to `chunk_size-1` elements will be omitted and can be retrieved
868 /// from the `remainder` function of the iterator.
870 /// Due to each chunk having exactly `chunk_size` elements, the compiler can often optimize the
871 /// resulting code better than in the case of [`chunks`].
873 /// See [`chunks`] for a variant of this iterator that also returns the remainder as a smaller
874 /// chunk, and [`rchunks_exact`] for the same iterator but starting at the end of the slice.
878 /// Panics if `chunk_size` is 0.
883 /// let slice = ['l', 'o', 'r', 'e', 'm'];
884 /// let mut iter = slice.chunks_exact(2);
885 /// assert_eq!(iter.next().unwrap(), &['l', 'o']);
886 /// assert_eq!(iter.next().unwrap(), &['r', 'e']);
887 /// assert!(iter.next().is_none());
888 /// assert_eq!(iter.remainder(), &['m']);
891 /// [`chunks`]: #method.chunks
892 /// [`rchunks_exact`]: #method.rchunks_exact
893 #[stable(feature = "chunks_exact", since = "1.31.0")]
895 pub fn chunks_exact(&self, chunk_size: usize) -> ChunksExact<'_, T> {
896 assert_ne!(chunk_size, 0);
897 let rem = self.len() % chunk_size;
898 let fst_len = self.len() - rem;
899 // SAFETY: 0 <= fst_len <= self.len() by construction above
900 let (fst, snd) = unsafe { self.split_at_unchecked(fst_len) };
901 ChunksExact { v: fst, rem: snd, chunk_size }
904 /// Returns an iterator over `chunk_size` elements of the slice at a time, starting at the
905 /// beginning of the slice.
907 /// The chunks are mutable slices, and do not overlap. If `chunk_size` does not divide the
908 /// length of the slice, then the last up to `chunk_size-1` elements will be omitted and can be
909 /// retrieved from the `into_remainder` function of the iterator.
911 /// Due to each chunk having exactly `chunk_size` elements, the compiler can often optimize the
912 /// resulting code better than in the case of [`chunks_mut`].
914 /// See [`chunks_mut`] for a variant of this iterator that also returns the remainder as a
915 /// smaller chunk, and [`rchunks_exact_mut`] for the same iterator but starting at the end of
920 /// Panics if `chunk_size` is 0.
925 /// let v = &mut [0, 0, 0, 0, 0];
926 /// let mut count = 1;
928 /// for chunk in v.chunks_exact_mut(2) {
929 /// for elem in chunk.iter_mut() {
934 /// assert_eq!(v, &[1, 1, 2, 2, 0]);
937 /// [`chunks_mut`]: #method.chunks_mut
938 /// [`rchunks_exact_mut`]: #method.rchunks_exact_mut
939 #[stable(feature = "chunks_exact", since = "1.31.0")]
941 pub fn chunks_exact_mut(&mut self, chunk_size: usize) -> ChunksExactMut<'_, T> {
942 assert_ne!(chunk_size, 0);
943 let rem = self.len() % chunk_size;
944 let fst_len = self.len() - rem;
945 // SAFETY: 0 <= fst_len <= self.len() by construction above
946 let (fst, snd) = unsafe { self.split_at_mut_unchecked(fst_len) };
947 ChunksExactMut { v: fst, rem: snd, chunk_size }
950 /// Returns an iterator over `N` elements of the slice at a time, starting at the
951 /// beginning of the slice.
953 /// The chunks are array references and do not overlap. If `N` does not divide the
954 /// length of the slice, then the last up to `N-1` elements will be omitted and can be
955 /// retrieved from the `remainder` function of the iterator.
957 /// This method is the const generic equivalent of [`chunks_exact`].
961 /// Panics if `N` is 0. This check will most probably get changed to a compile time
962 /// error before this method gets stabilized.
967 /// #![feature(array_chunks)]
968 /// let slice = ['l', 'o', 'r', 'e', 'm'];
969 /// let mut iter = slice.array_chunks();
970 /// assert_eq!(iter.next().unwrap(), &['l', 'o']);
971 /// assert_eq!(iter.next().unwrap(), &['r', 'e']);
972 /// assert!(iter.next().is_none());
973 /// assert_eq!(iter.remainder(), &['m']);
976 /// [`chunks_exact`]: #method.chunks_exact
977 #[unstable(feature = "array_chunks", issue = "74985")]
979 pub fn array_chunks<const N: usize>(&self) -> ArrayChunks<'_, T, N> {
981 let len = self.len() / N;
982 let (fst, snd) = self.split_at(len * N);
983 // SAFETY: We cast a slice of `len * N` elements into
984 // a slice of `len` many `N` elements chunks.
985 let array_slice: &[[T; N]] = unsafe { from_raw_parts(fst.as_ptr().cast(), len) };
986 ArrayChunks { iter: array_slice.iter(), rem: snd }
989 /// Returns an iterator over `N` elements of the slice at a time, starting at the
990 /// beginning of the slice.
992 /// The chunks are mutable array references and do not overlap. If `N` does not divide
993 /// the length of the slice, then the last up to `N-1` elements will be omitted and
994 /// can be retrieved from the `into_remainder` function of the iterator.
996 /// This method is the const generic equivalent of [`chunks_exact_mut`].
1000 /// Panics if `N` is 0. This check will most probably get changed to a compile time
1001 /// error before this method gets stabilized.
1006 /// #![feature(array_chunks)]
1007 /// let v = &mut [0, 0, 0, 0, 0];
1008 /// let mut count = 1;
1010 /// for chunk in v.array_chunks_mut() {
1011 /// *chunk = [count; 2];
1014 /// assert_eq!(v, &[1, 1, 2, 2, 0]);
1017 /// [`chunks_exact_mut`]: #method.chunks_exact_mut
1018 #[unstable(feature = "array_chunks", issue = "74985")]
1020 pub fn array_chunks_mut<const N: usize>(&mut self) -> ArrayChunksMut<'_, T, N> {
1022 let len = self.len() / N;
1023 let (fst, snd) = self.split_at_mut(len * N);
1024 // SAFETY: We cast a slice of `len * N` elements into
1025 // a slice of `len` many `N` elements chunks.
1027 let array_slice: &mut [[T; N]] = from_raw_parts_mut(fst.as_mut_ptr().cast(), len);
1028 ArrayChunksMut { iter: array_slice.iter_mut(), rem: snd }
1032 /// Returns an iterator over overlapping windows of `N` elements of a slice,
1033 /// starting at the beginning of the slice.
1035 /// This is the const generic equivalent of [`windows`].
1037 /// If `N` is smaller than the size of the array, it will return no windows.
1041 /// Panics if `N` is 0. This check will most probably get changed to a compile time
1042 /// error before this method gets stabilized.
1047 /// #![feature(array_windows)]
1048 /// let slice = [0, 1, 2, 3];
1049 /// let mut iter = slice.array_windows();
1050 /// assert_eq!(iter.next().unwrap(), &[0, 1]);
1051 /// assert_eq!(iter.next().unwrap(), &[1, 2]);
1052 /// assert_eq!(iter.next().unwrap(), &[2, 3]);
1053 /// assert!(iter.next().is_none());
1056 /// [`windows`]: #method.windows
1057 #[unstable(feature = "array_windows", issue = "75027")]
1059 pub fn array_windows<const N: usize>(&self) -> ArrayWindows<'_, T, N> {
1062 let num_windows = self.len().saturating_sub(N - 1);
1063 ArrayWindows { slice_head: self.as_ptr(), num: num_windows, marker: marker::PhantomData }
1066 /// Returns an iterator over `chunk_size` elements of the slice at a time, starting at the end
1069 /// The chunks are slices and do not overlap. If `chunk_size` does not divide the length of the
1070 /// slice, then the last chunk will not have length `chunk_size`.
1072 /// See [`rchunks_exact`] for a variant of this iterator that returns chunks of always exactly
1073 /// `chunk_size` elements, and [`chunks`] for the same iterator but starting at the beginning
1078 /// Panics if `chunk_size` is 0.
1083 /// let slice = ['l', 'o', 'r', 'e', 'm'];
1084 /// let mut iter = slice.rchunks(2);
1085 /// assert_eq!(iter.next().unwrap(), &['e', 'm']);
1086 /// assert_eq!(iter.next().unwrap(), &['o', 'r']);
1087 /// assert_eq!(iter.next().unwrap(), &['l']);
1088 /// assert!(iter.next().is_none());
1091 /// [`rchunks_exact`]: #method.rchunks_exact
1092 /// [`chunks`]: #method.chunks
1093 #[stable(feature = "rchunks", since = "1.31.0")]
1095 pub fn rchunks(&self, chunk_size: usize) -> RChunks<'_, T> {
1096 assert!(chunk_size != 0);
1097 RChunks { v: self, chunk_size }
1100 /// Returns an iterator over `chunk_size` elements of the slice at a time, starting at the end
1103 /// The chunks are mutable slices, and do not overlap. If `chunk_size` does not divide the
1104 /// length of the slice, then the last chunk will not have length `chunk_size`.
1106 /// See [`rchunks_exact_mut`] for a variant of this iterator that returns chunks of always
1107 /// exactly `chunk_size` elements, and [`chunks_mut`] for the same iterator but starting at the
1108 /// beginning of the slice.
1112 /// Panics if `chunk_size` is 0.
1117 /// let v = &mut [0, 0, 0, 0, 0];
1118 /// let mut count = 1;
1120 /// for chunk in v.rchunks_mut(2) {
1121 /// for elem in chunk.iter_mut() {
1126 /// assert_eq!(v, &[3, 2, 2, 1, 1]);
1129 /// [`rchunks_exact_mut`]: #method.rchunks_exact_mut
1130 /// [`chunks_mut`]: #method.chunks_mut
1131 #[stable(feature = "rchunks", since = "1.31.0")]
1133 pub fn rchunks_mut(&mut self, chunk_size: usize) -> RChunksMut<'_, T> {
1134 assert!(chunk_size != 0);
1135 RChunksMut { v: self, chunk_size }
1138 /// Returns an iterator over `chunk_size` elements of the slice at a time, starting at the
1139 /// end of the slice.
1141 /// The chunks are slices and do not overlap. If `chunk_size` does not divide the length of the
1142 /// slice, then the last up to `chunk_size-1` elements will be omitted and can be retrieved
1143 /// from the `remainder` function of the iterator.
1145 /// Due to each chunk having exactly `chunk_size` elements, the compiler can often optimize the
1146 /// resulting code better than in the case of [`chunks`].
1148 /// See [`rchunks`] for a variant of this iterator that also returns the remainder as a smaller
1149 /// chunk, and [`chunks_exact`] for the same iterator but starting at the beginning of the
1154 /// Panics if `chunk_size` is 0.
1159 /// let slice = ['l', 'o', 'r', 'e', 'm'];
1160 /// let mut iter = slice.rchunks_exact(2);
1161 /// assert_eq!(iter.next().unwrap(), &['e', 'm']);
1162 /// assert_eq!(iter.next().unwrap(), &['o', 'r']);
1163 /// assert!(iter.next().is_none());
1164 /// assert_eq!(iter.remainder(), &['l']);
1167 /// [`chunks`]: #method.chunks
1168 /// [`rchunks`]: #method.rchunks
1169 /// [`chunks_exact`]: #method.chunks_exact
1170 #[stable(feature = "rchunks", since = "1.31.0")]
1172 pub fn rchunks_exact(&self, chunk_size: usize) -> RChunksExact<'_, T> {
1173 assert!(chunk_size != 0);
1174 let rem = self.len() % chunk_size;
1175 // SAFETY: 0 <= rem <= self.len() by construction above
1176 let (fst, snd) = unsafe { self.split_at_unchecked(rem) };
1177 RChunksExact { v: snd, rem: fst, chunk_size }
1180 /// Returns an iterator over `chunk_size` elements of the slice at a time, starting at the end
1183 /// The chunks are mutable slices, and do not overlap. If `chunk_size` does not divide the
1184 /// length of the slice, then the last up to `chunk_size-1` elements will be omitted and can be
1185 /// retrieved from the `into_remainder` function of the iterator.
1187 /// Due to each chunk having exactly `chunk_size` elements, the compiler can often optimize the
1188 /// resulting code better than in the case of [`chunks_mut`].
1190 /// See [`rchunks_mut`] for a variant of this iterator that also returns the remainder as a
1191 /// smaller chunk, and [`chunks_exact_mut`] for the same iterator but starting at the beginning
1196 /// Panics if `chunk_size` is 0.
1201 /// let v = &mut [0, 0, 0, 0, 0];
1202 /// let mut count = 1;
1204 /// for chunk in v.rchunks_exact_mut(2) {
1205 /// for elem in chunk.iter_mut() {
1210 /// assert_eq!(v, &[0, 2, 2, 1, 1]);
1213 /// [`chunks_mut`]: #method.chunks_mut
1214 /// [`rchunks_mut`]: #method.rchunks_mut
1215 /// [`chunks_exact_mut`]: #method.chunks_exact_mut
1216 #[stable(feature = "rchunks", since = "1.31.0")]
1218 pub fn rchunks_exact_mut(&mut self, chunk_size: usize) -> RChunksExactMut<'_, T> {
1219 assert!(chunk_size != 0);
1220 let rem = self.len() % chunk_size;
1221 // SAFETY: 0 <= rem <= self.len() by construction above
1222 let (fst, snd) = unsafe { self.split_at_mut_unchecked(rem) };
1223 RChunksExactMut { v: snd, rem: fst, chunk_size }
1226 /// Divides one slice into two at an index.
1228 /// The first will contain all indices from `[0, mid)` (excluding
1229 /// the index `mid` itself) and the second will contain all
1230 /// indices from `[mid, len)` (excluding the index `len` itself).
1234 /// Panics if `mid > len`.
1239 /// let v = [1, 2, 3, 4, 5, 6];
1242 /// let (left, right) = v.split_at(0);
1243 /// assert_eq!(left, []);
1244 /// assert_eq!(right, [1, 2, 3, 4, 5, 6]);
1248 /// let (left, right) = v.split_at(2);
1249 /// assert_eq!(left, [1, 2]);
1250 /// assert_eq!(right, [3, 4, 5, 6]);
1254 /// let (left, right) = v.split_at(6);
1255 /// assert_eq!(left, [1, 2, 3, 4, 5, 6]);
1256 /// assert_eq!(right, []);
1259 #[stable(feature = "rust1", since = "1.0.0")]
1261 pub fn split_at(&self, mid: usize) -> (&[T], &[T]) {
1262 assert!(mid <= self.len());
1263 // SAFETY: `[ptr; mid]` and `[mid; len]` are inside `self`, which
1264 // fulfills the requirements of `from_raw_parts_mut`.
1265 unsafe { self.split_at_unchecked(mid) }
1268 /// Divides one mutable slice into two at an index.
1270 /// The first will contain all indices from `[0, mid)` (excluding
1271 /// the index `mid` itself) and the second will contain all
1272 /// indices from `[mid, len)` (excluding the index `len` itself).
1276 /// Panics if `mid > len`.
1281 /// let mut v = [1, 0, 3, 0, 5, 6];
1282 /// // scoped to restrict the lifetime of the borrows
1284 /// let (left, right) = v.split_at_mut(2);
1285 /// assert_eq!(left, [1, 0]);
1286 /// assert_eq!(right, [3, 0, 5, 6]);
1290 /// assert_eq!(v, [1, 2, 3, 4, 5, 6]);
1292 #[stable(feature = "rust1", since = "1.0.0")]
1294 pub fn split_at_mut(&mut self, mid: usize) -> (&mut [T], &mut [T]) {
1295 assert!(mid <= self.len());
1296 // SAFETY: `[ptr; mid]` and `[mid; len]` are inside `self`, which
1297 // fulfills the requirements of `from_raw_parts_mut`.
1298 unsafe { self.split_at_mut_unchecked(mid) }
1301 /// Divides one slice into two at an index, without doing bounds checking.
1303 /// The first will contain all indices from `[0, mid)` (excluding
1304 /// the index `mid` itself) and the second will contain all
1305 /// indices from `[mid, len)` (excluding the index `len` itself).
1307 /// For a safe alternative see [`split_at`].
1311 /// Calling this method with an out-of-bounds index is *[undefined behavior]*
1312 /// even if the resulting reference is not used. The caller has to ensure that
1313 /// `0 <= mid <= self.len()`.
1315 /// [`split_at`]: #method.split_at
1316 /// [undefined behavior]: https://doc.rust-lang.org/reference/behavior-considered-undefined.html
1321 /// #![feature(slice_split_at_unchecked)]
1323 /// let v = [1, 2, 3, 4, 5, 6];
1326 /// let (left, right) = v.split_at_unchecked(0);
1327 /// assert_eq!(left, []);
1328 /// assert_eq!(right, [1, 2, 3, 4, 5, 6]);
1332 /// let (left, right) = v.split_at_unchecked(2);
1333 /// assert_eq!(left, [1, 2]);
1334 /// assert_eq!(right, [3, 4, 5, 6]);
1338 /// let (left, right) = v.split_at_unchecked(6);
1339 /// assert_eq!(left, [1, 2, 3, 4, 5, 6]);
1340 /// assert_eq!(right, []);
1343 #[unstable(feature = "slice_split_at_unchecked", reason = "new API", issue = "76014")]
1345 unsafe fn split_at_unchecked(&self, mid: usize) -> (&[T], &[T]) {
1346 // SAFETY: Caller has to check that `0 <= mid <= self.len()`
1347 unsafe { (self.get_unchecked(..mid), self.get_unchecked(mid..)) }
1350 /// Divides one mutable slice into two at an index, without doing bounds checking.
1352 /// The first will contain all indices from `[0, mid)` (excluding
1353 /// the index `mid` itself) and the second will contain all
1354 /// indices from `[mid, len)` (excluding the index `len` itself).
1356 /// For a safe alternative see [`split_at_mut`].
1360 /// Calling this method with an out-of-bounds index is *[undefined behavior]*
1361 /// even if the resulting reference is not used. The caller has to ensure that
1362 /// `0 <= mid <= self.len()`.
1364 /// [`split_at_mut`]: #method.split_at_mut
1365 /// [undefined behavior]: https://doc.rust-lang.org/reference/behavior-considered-undefined.html
1370 /// #![feature(slice_split_at_unchecked)]
1372 /// let mut v = [1, 0, 3, 0, 5, 6];
1373 /// // scoped to restrict the lifetime of the borrows
1375 /// let (left, right) = v.split_at_mut_unchecked(2);
1376 /// assert_eq!(left, [1, 0]);
1377 /// assert_eq!(right, [3, 0, 5, 6]);
1381 /// assert_eq!(v, [1, 2, 3, 4, 5, 6]);
1383 #[unstable(feature = "slice_split_at_unchecked", reason = "new API", issue = "76014")]
1385 unsafe fn split_at_mut_unchecked(&mut self, mid: usize) -> (&mut [T], &mut [T]) {
1386 let len = self.len();
1387 let ptr = self.as_mut_ptr();
1389 // SAFETY: Caller has to check that `0 <= mid <= self.len()`.
1391 // `[ptr; mid]` and `[mid; len]` are not overlapping, so returning a mutable reference
1393 unsafe { (from_raw_parts_mut(ptr, mid), from_raw_parts_mut(ptr.add(mid), len - mid)) }
1396 /// Returns an iterator over subslices separated by elements that match
1397 /// `pred`. The matched element is not contained in the subslices.
1402 /// let slice = [10, 40, 33, 20];
1403 /// let mut iter = slice.split(|num| num % 3 == 0);
1405 /// assert_eq!(iter.next().unwrap(), &[10, 40]);
1406 /// assert_eq!(iter.next().unwrap(), &[20]);
1407 /// assert!(iter.next().is_none());
1410 /// If the first element is matched, an empty slice will be the first item
1411 /// returned by the iterator. Similarly, if the last element in the slice
1412 /// is matched, an empty slice will be the last item returned by the
1416 /// let slice = [10, 40, 33];
1417 /// let mut iter = slice.split(|num| num % 3 == 0);
1419 /// assert_eq!(iter.next().unwrap(), &[10, 40]);
1420 /// assert_eq!(iter.next().unwrap(), &[]);
1421 /// assert!(iter.next().is_none());
1424 /// If two matched elements are directly adjacent, an empty slice will be
1425 /// present between them:
1428 /// let slice = [10, 6, 33, 20];
1429 /// let mut iter = slice.split(|num| num % 3 == 0);
1431 /// assert_eq!(iter.next().unwrap(), &[10]);
1432 /// assert_eq!(iter.next().unwrap(), &[]);
1433 /// assert_eq!(iter.next().unwrap(), &[20]);
1434 /// assert!(iter.next().is_none());
1436 #[stable(feature = "rust1", since = "1.0.0")]
1438 pub fn split<F>(&self, pred: F) -> Split<'_, T, F>
1440 F: FnMut(&T) -> bool,
1442 Split { v: self, pred, finished: false }
1445 /// Returns an iterator over mutable subslices separated by elements that
1446 /// match `pred`. The matched element is not contained in the subslices.
1451 /// let mut v = [10, 40, 30, 20, 60, 50];
1453 /// for group in v.split_mut(|num| *num % 3 == 0) {
1456 /// assert_eq!(v, [1, 40, 30, 1, 60, 1]);
1458 #[stable(feature = "rust1", since = "1.0.0")]
1460 pub fn split_mut<F>(&mut self, pred: F) -> SplitMut<'_, T, F>
1462 F: FnMut(&T) -> bool,
1464 SplitMut { v: self, pred, finished: false }
1467 /// Returns an iterator over subslices separated by elements that match
1468 /// `pred`. The matched element is contained in the end of the previous
1469 /// subslice as a terminator.
1474 /// #![feature(split_inclusive)]
1475 /// let slice = [10, 40, 33, 20];
1476 /// let mut iter = slice.split_inclusive(|num| num % 3 == 0);
1478 /// assert_eq!(iter.next().unwrap(), &[10, 40, 33]);
1479 /// assert_eq!(iter.next().unwrap(), &[20]);
1480 /// assert!(iter.next().is_none());
1483 /// If the last element of the slice is matched,
1484 /// that element will be considered the terminator of the preceding slice.
1485 /// That slice will be the last item returned by the iterator.
1488 /// #![feature(split_inclusive)]
1489 /// let slice = [3, 10, 40, 33];
1490 /// let mut iter = slice.split_inclusive(|num| num % 3 == 0);
1492 /// assert_eq!(iter.next().unwrap(), &[3]);
1493 /// assert_eq!(iter.next().unwrap(), &[10, 40, 33]);
1494 /// assert!(iter.next().is_none());
1496 #[unstable(feature = "split_inclusive", issue = "72360")]
1498 pub fn split_inclusive<F>(&self, pred: F) -> SplitInclusive<'_, T, F>
1500 F: FnMut(&T) -> bool,
1502 SplitInclusive { v: self, pred, finished: false }
1505 /// Returns an iterator over mutable subslices separated by elements that
1506 /// match `pred`. The matched element is contained in the previous
1507 /// subslice as a terminator.
1512 /// #![feature(split_inclusive)]
1513 /// let mut v = [10, 40, 30, 20, 60, 50];
1515 /// for group in v.split_inclusive_mut(|num| *num % 3 == 0) {
1516 /// let terminator_idx = group.len()-1;
1517 /// group[terminator_idx] = 1;
1519 /// assert_eq!(v, [10, 40, 1, 20, 1, 1]);
1521 #[unstable(feature = "split_inclusive", issue = "72360")]
1523 pub fn split_inclusive_mut<F>(&mut self, pred: F) -> SplitInclusiveMut<'_, T, F>
1525 F: FnMut(&T) -> bool,
1527 SplitInclusiveMut { v: self, pred, finished: false }
1530 /// Returns an iterator over subslices separated by elements that match
1531 /// `pred`, starting at the end of the slice and working backwards.
1532 /// The matched element is not contained in the subslices.
1537 /// let slice = [11, 22, 33, 0, 44, 55];
1538 /// let mut iter = slice.rsplit(|num| *num == 0);
1540 /// assert_eq!(iter.next().unwrap(), &[44, 55]);
1541 /// assert_eq!(iter.next().unwrap(), &[11, 22, 33]);
1542 /// assert_eq!(iter.next(), None);
1545 /// As with `split()`, if the first or last element is matched, an empty
1546 /// slice will be the first (or last) item returned by the iterator.
1549 /// let v = &[0, 1, 1, 2, 3, 5, 8];
1550 /// let mut it = v.rsplit(|n| *n % 2 == 0);
1551 /// assert_eq!(it.next().unwrap(), &[]);
1552 /// assert_eq!(it.next().unwrap(), &[3, 5]);
1553 /// assert_eq!(it.next().unwrap(), &[1, 1]);
1554 /// assert_eq!(it.next().unwrap(), &[]);
1555 /// assert_eq!(it.next(), None);
1557 #[stable(feature = "slice_rsplit", since = "1.27.0")]
1559 pub fn rsplit<F>(&self, pred: F) -> RSplit<'_, T, F>
1561 F: FnMut(&T) -> bool,
1563 RSplit { inner: self.split(pred) }
1566 /// Returns an iterator over mutable subslices separated by elements that
1567 /// match `pred`, starting at the end of the slice and working
1568 /// backwards. The matched element is not contained in the subslices.
1573 /// let mut v = [100, 400, 300, 200, 600, 500];
1575 /// let mut count = 0;
1576 /// for group in v.rsplit_mut(|num| *num % 3 == 0) {
1578 /// group[0] = count;
1580 /// assert_eq!(v, [3, 400, 300, 2, 600, 1]);
1583 #[stable(feature = "slice_rsplit", since = "1.27.0")]
1585 pub fn rsplit_mut<F>(&mut self, pred: F) -> RSplitMut<'_, T, F>
1587 F: FnMut(&T) -> bool,
1589 RSplitMut { inner: self.split_mut(pred) }
1592 /// Returns an iterator over subslices separated by elements that match
1593 /// `pred`, limited to returning at most `n` items. The matched element is
1594 /// not contained in the subslices.
1596 /// The last element returned, if any, will contain the remainder of the
1601 /// Print the slice split once by numbers divisible by 3 (i.e., `[10, 40]`,
1602 /// `[20, 60, 50]`):
1605 /// let v = [10, 40, 30, 20, 60, 50];
1607 /// for group in v.splitn(2, |num| *num % 3 == 0) {
1608 /// println!("{:?}", group);
1611 #[stable(feature = "rust1", since = "1.0.0")]
1613 pub fn splitn<F>(&self, n: usize, pred: F) -> SplitN<'_, T, F>
1615 F: FnMut(&T) -> bool,
1617 SplitN { inner: GenericSplitN { iter: self.split(pred), count: n } }
1620 /// Returns an iterator over subslices separated by elements that match
1621 /// `pred`, limited to returning at most `n` items. The matched element is
1622 /// not contained in the subslices.
1624 /// The last element returned, if any, will contain the remainder of the
1630 /// let mut v = [10, 40, 30, 20, 60, 50];
1632 /// for group in v.splitn_mut(2, |num| *num % 3 == 0) {
1635 /// assert_eq!(v, [1, 40, 30, 1, 60, 50]);
1637 #[stable(feature = "rust1", since = "1.0.0")]
1639 pub fn splitn_mut<F>(&mut self, n: usize, pred: F) -> SplitNMut<'_, T, F>
1641 F: FnMut(&T) -> bool,
1643 SplitNMut { inner: GenericSplitN { iter: self.split_mut(pred), count: n } }
1646 /// Returns an iterator over subslices separated by elements that match
1647 /// `pred` limited to returning at most `n` items. This starts at the end of
1648 /// the slice and works backwards. The matched element is not contained in
1651 /// The last element returned, if any, will contain the remainder of the
1656 /// Print the slice split once, starting from the end, by numbers divisible
1657 /// by 3 (i.e., `[50]`, `[10, 40, 30, 20]`):
1660 /// let v = [10, 40, 30, 20, 60, 50];
1662 /// for group in v.rsplitn(2, |num| *num % 3 == 0) {
1663 /// println!("{:?}", group);
1666 #[stable(feature = "rust1", since = "1.0.0")]
1668 pub fn rsplitn<F>(&self, n: usize, pred: F) -> RSplitN<'_, T, F>
1670 F: FnMut(&T) -> bool,
1672 RSplitN { inner: GenericSplitN { iter: self.rsplit(pred), count: n } }
1675 /// Returns an iterator over subslices separated by elements that match
1676 /// `pred` limited to returning at most `n` items. This starts at the end of
1677 /// the slice and works backwards. The matched element is not contained in
1680 /// The last element returned, if any, will contain the remainder of the
1686 /// let mut s = [10, 40, 30, 20, 60, 50];
1688 /// for group in s.rsplitn_mut(2, |num| *num % 3 == 0) {
1691 /// assert_eq!(s, [1, 40, 30, 20, 60, 1]);
1693 #[stable(feature = "rust1", since = "1.0.0")]
1695 pub fn rsplitn_mut<F>(&mut self, n: usize, pred: F) -> RSplitNMut<'_, T, F>
1697 F: FnMut(&T) -> bool,
1699 RSplitNMut { inner: GenericSplitN { iter: self.rsplit_mut(pred), count: n } }
1702 /// Returns `true` if the slice contains an element with the given value.
1707 /// let v = [10, 40, 30];
1708 /// assert!(v.contains(&30));
1709 /// assert!(!v.contains(&50));
1712 /// If you do not have an `&T`, but just an `&U` such that `T: Borrow<U>`
1713 /// (e.g. `String: Borrow<str>`), you can use `iter().any`:
1716 /// let v = [String::from("hello"), String::from("world")]; // slice of `String`
1717 /// assert!(v.iter().any(|e| e == "hello")); // search with `&str`
1718 /// assert!(!v.iter().any(|e| e == "hi"));
1720 #[stable(feature = "rust1", since = "1.0.0")]
1721 pub fn contains(&self, x: &T) -> bool
1725 cmp::SliceContains::slice_contains(x, self)
1728 /// Returns `true` if `needle` is a prefix of the slice.
1733 /// let v = [10, 40, 30];
1734 /// assert!(v.starts_with(&[10]));
1735 /// assert!(v.starts_with(&[10, 40]));
1736 /// assert!(!v.starts_with(&[50]));
1737 /// assert!(!v.starts_with(&[10, 50]));
1740 /// Always returns `true` if `needle` is an empty slice:
1743 /// let v = &[10, 40, 30];
1744 /// assert!(v.starts_with(&[]));
1745 /// let v: &[u8] = &[];
1746 /// assert!(v.starts_with(&[]));
1748 #[stable(feature = "rust1", since = "1.0.0")]
1749 pub fn starts_with(&self, needle: &[T]) -> bool
1753 let n = needle.len();
1754 self.len() >= n && needle == &self[..n]
1757 /// Returns `true` if `needle` is a suffix of the slice.
1762 /// let v = [10, 40, 30];
1763 /// assert!(v.ends_with(&[30]));
1764 /// assert!(v.ends_with(&[40, 30]));
1765 /// assert!(!v.ends_with(&[50]));
1766 /// assert!(!v.ends_with(&[50, 30]));
1769 /// Always returns `true` if `needle` is an empty slice:
1772 /// let v = &[10, 40, 30];
1773 /// assert!(v.ends_with(&[]));
1774 /// let v: &[u8] = &[];
1775 /// assert!(v.ends_with(&[]));
1777 #[stable(feature = "rust1", since = "1.0.0")]
1778 pub fn ends_with(&self, needle: &[T]) -> bool
1782 let (m, n) = (self.len(), needle.len());
1783 m >= n && needle == &self[m - n..]
1786 /// Returns a subslice with the prefix removed.
1788 /// This method returns [`None`] if slice does not start with `prefix`.
1789 /// Also it returns the original slice if `prefix` is an empty slice.
1794 /// #![feature(slice_strip)]
1795 /// let v = &[10, 40, 30];
1796 /// assert_eq!(v.strip_prefix(&[10]), Some(&[40, 30][..]));
1797 /// assert_eq!(v.strip_prefix(&[10, 40]), Some(&[30][..]));
1798 /// assert_eq!(v.strip_prefix(&[50]), None);
1799 /// assert_eq!(v.strip_prefix(&[10, 50]), None);
1801 #[must_use = "returns the subslice without modifying the original"]
1802 #[unstable(feature = "slice_strip", issue = "73413")]
1803 pub fn strip_prefix(&self, prefix: &[T]) -> Option<&[T]>
1807 let n = prefix.len();
1808 if n <= self.len() {
1809 let (head, tail) = self.split_at(n);
1817 /// Returns a subslice with the suffix removed.
1819 /// This method returns [`None`] if slice does not end with `suffix`.
1820 /// Also it returns the original slice if `suffix` is an empty slice
1825 /// #![feature(slice_strip)]
1826 /// let v = &[10, 40, 30];
1827 /// assert_eq!(v.strip_suffix(&[30]), Some(&[10, 40][..]));
1828 /// assert_eq!(v.strip_suffix(&[40, 30]), Some(&[10][..]));
1829 /// assert_eq!(v.strip_suffix(&[50]), None);
1830 /// assert_eq!(v.strip_suffix(&[50, 30]), None);
1832 #[must_use = "returns the subslice without modifying the original"]
1833 #[unstable(feature = "slice_strip", issue = "73413")]
1834 pub fn strip_suffix(&self, suffix: &[T]) -> Option<&[T]>
1838 let (len, n) = (self.len(), suffix.len());
1840 let (head, tail) = self.split_at(len - n);
1848 /// Binary searches this sorted slice for a given element.
1850 /// If the value is found then [`Result::Ok`] is returned, containing the
1851 /// index of the matching element. If there are multiple matches, then any
1852 /// one of the matches could be returned. If the value is not found then
1853 /// [`Result::Err`] is returned, containing the index where a matching
1854 /// element could be inserted while maintaining sorted order.
1858 /// Looks up a series of four elements. The first is found, with a
1859 /// uniquely determined position; the second and third are not
1860 /// found; the fourth could match any position in `[1, 4]`.
1863 /// let s = [0, 1, 1, 1, 1, 2, 3, 5, 8, 13, 21, 34, 55];
1865 /// assert_eq!(s.binary_search(&13), Ok(9));
1866 /// assert_eq!(s.binary_search(&4), Err(7));
1867 /// assert_eq!(s.binary_search(&100), Err(13));
1868 /// let r = s.binary_search(&1);
1869 /// assert!(match r { Ok(1..=4) => true, _ => false, });
1872 /// If you want to insert an item to a sorted vector, while maintaining
1876 /// let mut s = vec![0, 1, 1, 1, 1, 2, 3, 5, 8, 13, 21, 34, 55];
1878 /// let idx = s.binary_search(&num).unwrap_or_else(|x| x);
1879 /// s.insert(idx, num);
1880 /// assert_eq!(s, [0, 1, 1, 1, 1, 2, 3, 5, 8, 13, 21, 34, 42, 55]);
1882 #[stable(feature = "rust1", since = "1.0.0")]
1883 pub fn binary_search(&self, x: &T) -> Result<usize, usize>
1887 self.binary_search_by(|p| p.cmp(x))
1890 /// Binary searches this sorted slice with a comparator function.
1892 /// The comparator function should implement an order consistent
1893 /// with the sort order of the underlying slice, returning an
1894 /// order code that indicates whether its argument is `Less`,
1895 /// `Equal` or `Greater` the desired target.
1897 /// If the value is found then [`Result::Ok`] is returned, containing the
1898 /// index of the matching element. If there are multiple matches, then any
1899 /// one of the matches could be returned. If the value is not found then
1900 /// [`Result::Err`] is returned, containing the index where a matching
1901 /// element could be inserted while maintaining sorted order.
1905 /// Looks up a series of four elements. The first is found, with a
1906 /// uniquely determined position; the second and third are not
1907 /// found; the fourth could match any position in `[1, 4]`.
1910 /// let s = [0, 1, 1, 1, 1, 2, 3, 5, 8, 13, 21, 34, 55];
1913 /// assert_eq!(s.binary_search_by(|probe| probe.cmp(&seek)), Ok(9));
1915 /// assert_eq!(s.binary_search_by(|probe| probe.cmp(&seek)), Err(7));
1917 /// assert_eq!(s.binary_search_by(|probe| probe.cmp(&seek)), Err(13));
1919 /// let r = s.binary_search_by(|probe| probe.cmp(&seek));
1920 /// assert!(match r { Ok(1..=4) => true, _ => false, });
1922 #[stable(feature = "rust1", since = "1.0.0")]
1924 pub fn binary_search_by<'a, F>(&'a self, mut f: F) -> Result<usize, usize>
1926 F: FnMut(&'a T) -> Ordering,
1929 let mut size = s.len();
1933 let mut base = 0usize;
1935 let half = size / 2;
1936 let mid = base + half;
1937 // SAFETY: the call is made safe by the following inconstants:
1938 // - `mid >= 0`: by definition
1939 // - `mid < size`: `mid = size / 2 + size / 4 + size / 8 ...`
1940 let cmp = f(unsafe { s.get_unchecked(mid) });
1941 base = if cmp == Greater { base } else { mid };
1944 // SAFETY: base is always in [0, size) because base <= mid.
1945 let cmp = f(unsafe { s.get_unchecked(base) });
1946 if cmp == Equal { Ok(base) } else { Err(base + (cmp == Less) as usize) }
1949 /// Binary searches this sorted slice with a key extraction function.
1951 /// Assumes that the slice is sorted by the key, for instance with
1952 /// [`sort_by_key`] using the same key extraction function.
1954 /// If the value is found then [`Result::Ok`] is returned, containing the
1955 /// index of the matching element. If there are multiple matches, then any
1956 /// one of the matches could be returned. If the value is not found then
1957 /// [`Result::Err`] is returned, containing the index where a matching
1958 /// element could be inserted while maintaining sorted order.
1960 /// [`sort_by_key`]: #method.sort_by_key
1964 /// Looks up a series of four elements in a slice of pairs sorted by
1965 /// their second elements. The first is found, with a uniquely
1966 /// determined position; the second and third are not found; the
1967 /// fourth could match any position in `[1, 4]`.
1970 /// let s = [(0, 0), (2, 1), (4, 1), (5, 1), (3, 1),
1971 /// (1, 2), (2, 3), (4, 5), (5, 8), (3, 13),
1972 /// (1, 21), (2, 34), (4, 55)];
1974 /// assert_eq!(s.binary_search_by_key(&13, |&(a,b)| b), Ok(9));
1975 /// assert_eq!(s.binary_search_by_key(&4, |&(a,b)| b), Err(7));
1976 /// assert_eq!(s.binary_search_by_key(&100, |&(a,b)| b), Err(13));
1977 /// let r = s.binary_search_by_key(&1, |&(a,b)| b);
1978 /// assert!(match r { Ok(1..=4) => true, _ => false, });
1980 #[stable(feature = "slice_binary_search_by_key", since = "1.10.0")]
1982 pub fn binary_search_by_key<'a, B, F>(&'a self, b: &B, mut f: F) -> Result<usize, usize>
1984 F: FnMut(&'a T) -> B,
1987 self.binary_search_by(|k| f(k).cmp(b))
1990 /// Sorts the slice, but may not preserve the order of equal elements.
1992 /// This sort is unstable (i.e., may reorder equal elements), in-place
1993 /// (i.e., does not allocate), and *O*(*n* \* log(*n*)) worst-case.
1995 /// # Current implementation
1997 /// The current algorithm is based on [pattern-defeating quicksort][pdqsort] by Orson Peters,
1998 /// which combines the fast average case of randomized quicksort with the fast worst case of
1999 /// heapsort, while achieving linear time on slices with certain patterns. It uses some
2000 /// randomization to avoid degenerate cases, but with a fixed seed to always provide
2001 /// deterministic behavior.
2003 /// It is typically faster than stable sorting, except in a few special cases, e.g., when the
2004 /// slice consists of several concatenated sorted sequences.
2009 /// let mut v = [-5, 4, 1, -3, 2];
2011 /// v.sort_unstable();
2012 /// assert!(v == [-5, -3, 1, 2, 4]);
2015 /// [pdqsort]: https://github.com/orlp/pdqsort
2016 #[stable(feature = "sort_unstable", since = "1.20.0")]
2018 pub fn sort_unstable(&mut self)
2022 sort::quicksort(self, |a, b| a.lt(b));
2025 /// Sorts the slice with a comparator function, but may not preserve the order of equal
2028 /// This sort is unstable (i.e., may reorder equal elements), in-place
2029 /// (i.e., does not allocate), and *O*(*n* \* log(*n*)) worst-case.
2031 /// The comparator function must define a total ordering for the elements in the slice. If
2032 /// the ordering is not total, the order of the elements is unspecified. An order is a
2033 /// total order if it is (for all a, b and c):
2035 /// * total and antisymmetric: exactly one of a < b, a == b or a > b is true; and
2036 /// * transitive, a < b and b < c implies a < c. The same must hold for both == and >.
2038 /// For example, while [`f64`] doesn't implement [`Ord`] because `NaN != NaN`, we can use
2039 /// `partial_cmp` as our sort function when we know the slice doesn't contain a `NaN`.
2042 /// let mut floats = [5f64, 4.0, 1.0, 3.0, 2.0];
2043 /// floats.sort_unstable_by(|a, b| a.partial_cmp(b).unwrap());
2044 /// assert_eq!(floats, [1.0, 2.0, 3.0, 4.0, 5.0]);
2047 /// # Current implementation
2049 /// The current algorithm is based on [pattern-defeating quicksort][pdqsort] by Orson Peters,
2050 /// which combines the fast average case of randomized quicksort with the fast worst case of
2051 /// heapsort, while achieving linear time on slices with certain patterns. It uses some
2052 /// randomization to avoid degenerate cases, but with a fixed seed to always provide
2053 /// deterministic behavior.
2055 /// It is typically faster than stable sorting, except in a few special cases, e.g., when the
2056 /// slice consists of several concatenated sorted sequences.
2061 /// let mut v = [5, 4, 1, 3, 2];
2062 /// v.sort_unstable_by(|a, b| a.cmp(b));
2063 /// assert!(v == [1, 2, 3, 4, 5]);
2065 /// // reverse sorting
2066 /// v.sort_unstable_by(|a, b| b.cmp(a));
2067 /// assert!(v == [5, 4, 3, 2, 1]);
2070 /// [pdqsort]: https://github.com/orlp/pdqsort
2071 #[stable(feature = "sort_unstable", since = "1.20.0")]
2073 pub fn sort_unstable_by<F>(&mut self, mut compare: F)
2075 F: FnMut(&T, &T) -> Ordering,
2077 sort::quicksort(self, |a, b| compare(a, b) == Ordering::Less);
2080 /// Sorts the slice with a key extraction function, but may not preserve the order of equal
2083 /// This sort is unstable (i.e., may reorder equal elements), in-place
2084 /// (i.e., does not allocate), and *O*(m \* *n* \* log(*n*)) worst-case, where the key function is
2087 /// # Current implementation
2089 /// The current algorithm is based on [pattern-defeating quicksort][pdqsort] by Orson Peters,
2090 /// which combines the fast average case of randomized quicksort with the fast worst case of
2091 /// heapsort, while achieving linear time on slices with certain patterns. It uses some
2092 /// randomization to avoid degenerate cases, but with a fixed seed to always provide
2093 /// deterministic behavior.
2095 /// Due to its key calling strategy, [`sort_unstable_by_key`](#method.sort_unstable_by_key)
2096 /// is likely to be slower than [`sort_by_cached_key`](#method.sort_by_cached_key) in
2097 /// cases where the key function is expensive.
2102 /// let mut v = [-5i32, 4, 1, -3, 2];
2104 /// v.sort_unstable_by_key(|k| k.abs());
2105 /// assert!(v == [1, 2, -3, 4, -5]);
2108 /// [pdqsort]: https://github.com/orlp/pdqsort
2109 #[stable(feature = "sort_unstable", since = "1.20.0")]
2111 pub fn sort_unstable_by_key<K, F>(&mut self, mut f: F)
2116 sort::quicksort(self, |a, b| f(a).lt(&f(b)));
2119 /// Reorder the slice such that the element at `index` is at its final sorted position.
2121 /// This reordering has the additional property that any value at position `i < index` will be
2122 /// less than or equal to any value at a position `j > index`. Additionally, this reordering is
2123 /// unstable (i.e. any number of equal elements may end up at position `index`), in-place
2124 /// (i.e. does not allocate), and *O*(*n*) worst-case. This function is also/ known as "kth
2125 /// element" in other libraries. It returns a triplet of the following values: all elements less
2126 /// than the one at the given index, the value at the given index, and all elements greater than
2127 /// the one at the given index.
2129 /// # Current implementation
2131 /// The current algorithm is based on the quickselect portion of the same quicksort algorithm
2132 /// used for [`sort_unstable`].
2134 /// [`sort_unstable`]: #method.sort_unstable
2138 /// Panics when `index >= len()`, meaning it always panics on empty slices.
2143 /// #![feature(slice_partition_at_index)]
2145 /// let mut v = [-5i32, 4, 1, -3, 2];
2147 /// // Find the median
2148 /// v.partition_at_index(2);
2150 /// // We are only guaranteed the slice will be one of the following, based on the way we sort
2151 /// // about the specified index.
2152 /// assert!(v == [-3, -5, 1, 2, 4] ||
2153 /// v == [-5, -3, 1, 2, 4] ||
2154 /// v == [-3, -5, 1, 4, 2] ||
2155 /// v == [-5, -3, 1, 4, 2]);
2157 #[unstable(feature = "slice_partition_at_index", issue = "55300")]
2159 pub fn partition_at_index(&mut self, index: usize) -> (&mut [T], &mut T, &mut [T])
2163 let mut f = |a: &T, b: &T| a.lt(b);
2164 sort::partition_at_index(self, index, &mut f)
2167 /// Reorder the slice with a comparator function such that the element at `index` is at its
2168 /// final sorted position.
2170 /// This reordering has the additional property that any value at position `i < index` will be
2171 /// less than or equal to any value at a position `j > index` using the comparator function.
2172 /// Additionally, this reordering is unstable (i.e. any number of equal elements may end up at
2173 /// position `index`), in-place (i.e. does not allocate), and *O*(*n*) worst-case. This function
2174 /// is also known as "kth element" in other libraries. It returns a triplet of the following
2175 /// values: all elements less than the one at the given index, the value at the given index,
2176 /// and all elements greater than the one at the given index, using the provided comparator
2179 /// # Current implementation
2181 /// The current algorithm is based on the quickselect portion of the same quicksort algorithm
2182 /// used for [`sort_unstable`].
2184 /// [`sort_unstable`]: #method.sort_unstable
2188 /// Panics when `index >= len()`, meaning it always panics on empty slices.
2193 /// #![feature(slice_partition_at_index)]
2195 /// let mut v = [-5i32, 4, 1, -3, 2];
2197 /// // Find the median as if the slice were sorted in descending order.
2198 /// v.partition_at_index_by(2, |a, b| b.cmp(a));
2200 /// // We are only guaranteed the slice will be one of the following, based on the way we sort
2201 /// // about the specified index.
2202 /// assert!(v == [2, 4, 1, -5, -3] ||
2203 /// v == [2, 4, 1, -3, -5] ||
2204 /// v == [4, 2, 1, -5, -3] ||
2205 /// v == [4, 2, 1, -3, -5]);
2207 #[unstable(feature = "slice_partition_at_index", issue = "55300")]
2209 pub fn partition_at_index_by<F>(
2213 ) -> (&mut [T], &mut T, &mut [T])
2215 F: FnMut(&T, &T) -> Ordering,
2217 let mut f = |a: &T, b: &T| compare(a, b) == Less;
2218 sort::partition_at_index(self, index, &mut f)
2221 /// Reorder the slice with a key extraction function such that the element at `index` is at its
2222 /// final sorted position.
2224 /// This reordering has the additional property that any value at position `i < index` will be
2225 /// less than or equal to any value at a position `j > index` using the key extraction function.
2226 /// Additionally, this reordering is unstable (i.e. any number of equal elements may end up at
2227 /// position `index`), in-place (i.e. does not allocate), and *O*(*n*) worst-case. This function
2228 /// is also known as "kth element" in other libraries. It returns a triplet of the following
2229 /// values: all elements less than the one at the given index, the value at the given index, and
2230 /// all elements greater than the one at the given index, using the provided key extraction
2233 /// # Current implementation
2235 /// The current algorithm is based on the quickselect portion of the same quicksort algorithm
2236 /// used for [`sort_unstable`].
2238 /// [`sort_unstable`]: #method.sort_unstable
2242 /// Panics when `index >= len()`, meaning it always panics on empty slices.
2247 /// #![feature(slice_partition_at_index)]
2249 /// let mut v = [-5i32, 4, 1, -3, 2];
2251 /// // Return the median as if the array were sorted according to absolute value.
2252 /// v.partition_at_index_by_key(2, |a| a.abs());
2254 /// // We are only guaranteed the slice will be one of the following, based on the way we sort
2255 /// // about the specified index.
2256 /// assert!(v == [1, 2, -3, 4, -5] ||
2257 /// v == [1, 2, -3, -5, 4] ||
2258 /// v == [2, 1, -3, 4, -5] ||
2259 /// v == [2, 1, -3, -5, 4]);
2261 #[unstable(feature = "slice_partition_at_index", issue = "55300")]
2263 pub fn partition_at_index_by_key<K, F>(
2267 ) -> (&mut [T], &mut T, &mut [T])
2272 let mut g = |a: &T, b: &T| f(a).lt(&f(b));
2273 sort::partition_at_index(self, index, &mut g)
2276 /// Moves all consecutive repeated elements to the end of the slice according to the
2277 /// [`PartialEq`] trait implementation.
2279 /// Returns two slices. The first contains no consecutive repeated elements.
2280 /// The second contains all the duplicates in no specified order.
2282 /// If the slice is sorted, the first returned slice contains no duplicates.
2287 /// #![feature(slice_partition_dedup)]
2289 /// let mut slice = [1, 2, 2, 3, 3, 2, 1, 1];
2291 /// let (dedup, duplicates) = slice.partition_dedup();
2293 /// assert_eq!(dedup, [1, 2, 3, 2, 1]);
2294 /// assert_eq!(duplicates, [2, 3, 1]);
2296 #[unstable(feature = "slice_partition_dedup", issue = "54279")]
2298 pub fn partition_dedup(&mut self) -> (&mut [T], &mut [T])
2302 self.partition_dedup_by(|a, b| a == b)
2305 /// Moves all but the first of consecutive elements to the end of the slice satisfying
2306 /// a given equality relation.
2308 /// Returns two slices. The first contains no consecutive repeated elements.
2309 /// The second contains all the duplicates in no specified order.
2311 /// The `same_bucket` function is passed references to two elements from the slice and
2312 /// must determine if the elements compare equal. The elements are passed in opposite order
2313 /// from their order in the slice, so if `same_bucket(a, b)` returns `true`, `a` is moved
2314 /// at the end of the slice.
2316 /// If the slice is sorted, the first returned slice contains no duplicates.
2321 /// #![feature(slice_partition_dedup)]
2323 /// let mut slice = ["foo", "Foo", "BAZ", "Bar", "bar", "baz", "BAZ"];
2325 /// let (dedup, duplicates) = slice.partition_dedup_by(|a, b| a.eq_ignore_ascii_case(b));
2327 /// assert_eq!(dedup, ["foo", "BAZ", "Bar", "baz"]);
2328 /// assert_eq!(duplicates, ["bar", "Foo", "BAZ"]);
2330 #[unstable(feature = "slice_partition_dedup", issue = "54279")]
2332 pub fn partition_dedup_by<F>(&mut self, mut same_bucket: F) -> (&mut [T], &mut [T])
2334 F: FnMut(&mut T, &mut T) -> bool,
2336 // Although we have a mutable reference to `self`, we cannot make
2337 // *arbitrary* changes. The `same_bucket` calls could panic, so we
2338 // must ensure that the slice is in a valid state at all times.
2340 // The way that we handle this is by using swaps; we iterate
2341 // over all the elements, swapping as we go so that at the end
2342 // the elements we wish to keep are in the front, and those we
2343 // wish to reject are at the back. We can then split the slice.
2344 // This operation is still `O(n)`.
2346 // Example: We start in this state, where `r` represents "next
2347 // read" and `w` represents "next_write`.
2350 // +---+---+---+---+---+---+
2351 // | 0 | 1 | 1 | 2 | 3 | 3 |
2352 // +---+---+---+---+---+---+
2355 // Comparing self[r] against self[w-1], this is not a duplicate, so
2356 // we swap self[r] and self[w] (no effect as r==w) and then increment both
2357 // r and w, leaving us with:
2360 // +---+---+---+---+---+---+
2361 // | 0 | 1 | 1 | 2 | 3 | 3 |
2362 // +---+---+---+---+---+---+
2365 // Comparing self[r] against self[w-1], this value is a duplicate,
2366 // so we increment `r` but leave everything else unchanged:
2369 // +---+---+---+---+---+---+
2370 // | 0 | 1 | 1 | 2 | 3 | 3 |
2371 // +---+---+---+---+---+---+
2374 // Comparing self[r] against self[w-1], this is not a duplicate,
2375 // so swap self[r] and self[w] and advance r and w:
2378 // +---+---+---+---+---+---+
2379 // | 0 | 1 | 2 | 1 | 3 | 3 |
2380 // +---+---+---+---+---+---+
2383 // Not a duplicate, repeat:
2386 // +---+---+---+---+---+---+
2387 // | 0 | 1 | 2 | 3 | 1 | 3 |
2388 // +---+---+---+---+---+---+
2391 // Duplicate, advance r. End of slice. Split at w.
2393 let len = self.len();
2395 return (self, &mut []);
2398 let ptr = self.as_mut_ptr();
2399 let mut next_read: usize = 1;
2400 let mut next_write: usize = 1;
2402 // SAFETY: the `while` condition guarantees `next_read` and `next_write`
2403 // are less than `len`, thus are inside `self`. `prev_ptr_write` points to
2404 // one element before `ptr_write`, but `next_write` starts at 1, so
2405 // `prev_ptr_write` is never less than 0 and is inside the slice.
2406 // This fulfils the requirements for dereferencing `ptr_read`, `prev_ptr_write`
2407 // and `ptr_write`, and for using `ptr.add(next_read)`, `ptr.add(next_write - 1)`
2408 // and `prev_ptr_write.offset(1)`.
2410 // `next_write` is also incremented at most once per loop at most meaning
2411 // no element is skipped when it may need to be swapped.
2413 // `ptr_read` and `prev_ptr_write` never point to the same element. This
2414 // is required for `&mut *ptr_read`, `&mut *prev_ptr_write` to be safe.
2415 // The explanation is simply that `next_read >= next_write` is always true,
2416 // thus `next_read > next_write - 1` is too.
2418 // Avoid bounds checks by using raw pointers.
2419 while next_read < len {
2420 let ptr_read = ptr.add(next_read);
2421 let prev_ptr_write = ptr.add(next_write - 1);
2422 if !same_bucket(&mut *ptr_read, &mut *prev_ptr_write) {
2423 if next_read != next_write {
2424 let ptr_write = prev_ptr_write.offset(1);
2425 mem::swap(&mut *ptr_read, &mut *ptr_write);
2433 self.split_at_mut(next_write)
2436 /// Moves all but the first of consecutive elements to the end of the slice that resolve
2437 /// to the same key.
2439 /// Returns two slices. The first contains no consecutive repeated elements.
2440 /// The second contains all the duplicates in no specified order.
2442 /// If the slice is sorted, the first returned slice contains no duplicates.
2447 /// #![feature(slice_partition_dedup)]
2449 /// let mut slice = [10, 20, 21, 30, 30, 20, 11, 13];
2451 /// let (dedup, duplicates) = slice.partition_dedup_by_key(|i| *i / 10);
2453 /// assert_eq!(dedup, [10, 20, 30, 20, 11]);
2454 /// assert_eq!(duplicates, [21, 30, 13]);
2456 #[unstable(feature = "slice_partition_dedup", issue = "54279")]
2458 pub fn partition_dedup_by_key<K, F>(&mut self, mut key: F) -> (&mut [T], &mut [T])
2460 F: FnMut(&mut T) -> K,
2463 self.partition_dedup_by(|a, b| key(a) == key(b))
2466 /// Rotates the slice in-place such that the first `mid` elements of the
2467 /// slice move to the end while the last `self.len() - mid` elements move to
2468 /// the front. After calling `rotate_left`, the element previously at index
2469 /// `mid` will become the first element in the slice.
2473 /// This function will panic if `mid` is greater than the length of the
2474 /// slice. Note that `mid == self.len()` does _not_ panic and is a no-op
2479 /// Takes linear (in `self.len()`) time.
2484 /// let mut a = ['a', 'b', 'c', 'd', 'e', 'f'];
2485 /// a.rotate_left(2);
2486 /// assert_eq!(a, ['c', 'd', 'e', 'f', 'a', 'b']);
2489 /// Rotating a subslice:
2492 /// let mut a = ['a', 'b', 'c', 'd', 'e', 'f'];
2493 /// a[1..5].rotate_left(1);
2494 /// assert_eq!(a, ['a', 'c', 'd', 'e', 'b', 'f']);
2496 #[stable(feature = "slice_rotate", since = "1.26.0")]
2497 pub fn rotate_left(&mut self, mid: usize) {
2498 assert!(mid <= self.len());
2499 let k = self.len() - mid;
2500 let p = self.as_mut_ptr();
2502 // SAFETY: The range `[p.add(mid) - mid, p.add(mid) + k)` is trivially
2503 // valid for reading and writing, as required by `ptr_rotate`.
2505 rotate::ptr_rotate(mid, p.add(mid), k);
2509 /// Rotates the slice in-place such that the first `self.len() - k`
2510 /// elements of the slice move to the end while the last `k` elements move
2511 /// to the front. After calling `rotate_right`, the element previously at
2512 /// index `self.len() - k` will become the first element in the slice.
2516 /// This function will panic if `k` is greater than the length of the
2517 /// slice. Note that `k == self.len()` does _not_ panic and is a no-op
2522 /// Takes linear (in `self.len()`) time.
2527 /// let mut a = ['a', 'b', 'c', 'd', 'e', 'f'];
2528 /// a.rotate_right(2);
2529 /// assert_eq!(a, ['e', 'f', 'a', 'b', 'c', 'd']);
2532 /// Rotate a subslice:
2535 /// let mut a = ['a', 'b', 'c', 'd', 'e', 'f'];
2536 /// a[1..5].rotate_right(1);
2537 /// assert_eq!(a, ['a', 'e', 'b', 'c', 'd', 'f']);
2539 #[stable(feature = "slice_rotate", since = "1.26.0")]
2540 pub fn rotate_right(&mut self, k: usize) {
2541 assert!(k <= self.len());
2542 let mid = self.len() - k;
2543 let p = self.as_mut_ptr();
2545 // SAFETY: The range `[p.add(mid) - mid, p.add(mid) + k)` is trivially
2546 // valid for reading and writing, as required by `ptr_rotate`.
2548 rotate::ptr_rotate(mid, p.add(mid), k);
2552 /// Fills `self` with elements by cloning `value`.
2557 /// #![feature(slice_fill)]
2559 /// let mut buf = vec![0; 10];
2561 /// assert_eq!(buf, vec![1; 10]);
2563 #[unstable(feature = "slice_fill", issue = "70758")]
2564 pub fn fill(&mut self, value: T)
2568 if let Some((last, elems)) = self.split_last_mut() {
2570 el.clone_from(&value);
2577 /// Copies the elements from `src` into `self`.
2579 /// The length of `src` must be the same as `self`.
2581 /// If `T` implements `Copy`, it can be more performant to use
2582 /// [`copy_from_slice`].
2586 /// This function will panic if the two slices have different lengths.
2590 /// Cloning two elements from a slice into another:
2593 /// let src = [1, 2, 3, 4];
2594 /// let mut dst = [0, 0];
2596 /// // Because the slices have to be the same length,
2597 /// // we slice the source slice from four elements
2598 /// // to two. It will panic if we don't do this.
2599 /// dst.clone_from_slice(&src[2..]);
2601 /// assert_eq!(src, [1, 2, 3, 4]);
2602 /// assert_eq!(dst, [3, 4]);
2605 /// Rust enforces that there can only be one mutable reference with no
2606 /// immutable references to a particular piece of data in a particular
2607 /// scope. Because of this, attempting to use `clone_from_slice` on a
2608 /// single slice will result in a compile failure:
2611 /// let mut slice = [1, 2, 3, 4, 5];
2613 /// slice[..2].clone_from_slice(&slice[3..]); // compile fail!
2616 /// To work around this, we can use [`split_at_mut`] to create two distinct
2617 /// sub-slices from a slice:
2620 /// let mut slice = [1, 2, 3, 4, 5];
2623 /// let (left, right) = slice.split_at_mut(2);
2624 /// left.clone_from_slice(&right[1..]);
2627 /// assert_eq!(slice, [4, 5, 3, 4, 5]);
2630 /// [`copy_from_slice`]: #method.copy_from_slice
2631 /// [`split_at_mut`]: #method.split_at_mut
2632 #[stable(feature = "clone_from_slice", since = "1.7.0")]
2633 pub fn clone_from_slice(&mut self, src: &[T])
2637 assert!(self.len() == src.len(), "destination and source slices have different lengths");
2638 // NOTE: We need to explicitly slice them to the same length
2639 // for bounds checking to be elided, and the optimizer will
2640 // generate memcpy for simple cases (for example T = u8).
2641 let len = self.len();
2642 let src = &src[..len];
2644 self[i].clone_from(&src[i]);
2648 /// Copies all elements from `src` into `self`, using a memcpy.
2650 /// The length of `src` must be the same as `self`.
2652 /// If `T` does not implement `Copy`, use [`clone_from_slice`].
2656 /// This function will panic if the two slices have different lengths.
2660 /// Copying two elements from a slice into another:
2663 /// let src = [1, 2, 3, 4];
2664 /// let mut dst = [0, 0];
2666 /// // Because the slices have to be the same length,
2667 /// // we slice the source slice from four elements
2668 /// // to two. It will panic if we don't do this.
2669 /// dst.copy_from_slice(&src[2..]);
2671 /// assert_eq!(src, [1, 2, 3, 4]);
2672 /// assert_eq!(dst, [3, 4]);
2675 /// Rust enforces that there can only be one mutable reference with no
2676 /// immutable references to a particular piece of data in a particular
2677 /// scope. Because of this, attempting to use `copy_from_slice` on a
2678 /// single slice will result in a compile failure:
2681 /// let mut slice = [1, 2, 3, 4, 5];
2683 /// slice[..2].copy_from_slice(&slice[3..]); // compile fail!
2686 /// To work around this, we can use [`split_at_mut`] to create two distinct
2687 /// sub-slices from a slice:
2690 /// let mut slice = [1, 2, 3, 4, 5];
2693 /// let (left, right) = slice.split_at_mut(2);
2694 /// left.copy_from_slice(&right[1..]);
2697 /// assert_eq!(slice, [4, 5, 3, 4, 5]);
2700 /// [`clone_from_slice`]: #method.clone_from_slice
2701 /// [`split_at_mut`]: #method.split_at_mut
2702 #[stable(feature = "copy_from_slice", since = "1.9.0")]
2703 pub fn copy_from_slice(&mut self, src: &[T])
2707 // The panic code path was put into a cold function to not bloat the
2712 fn len_mismatch_fail(dst_len: usize, src_len: usize) -> ! {
2714 "source slice length ({}) does not match destination slice length ({})",
2719 if self.len() != src.len() {
2720 len_mismatch_fail(self.len(), src.len());
2723 // SAFETY: `self` is valid for `self.len()` elements by definition, and `src` was
2724 // checked to have the same length. The slices cannot overlap because
2725 // mutable references are exclusive.
2727 ptr::copy_nonoverlapping(src.as_ptr(), self.as_mut_ptr(), self.len());
2731 /// Copies elements from one part of the slice to another part of itself,
2732 /// using a memmove.
2734 /// `src` is the range within `self` to copy from. `dest` is the starting
2735 /// index of the range within `self` to copy to, which will have the same
2736 /// length as `src`. The two ranges may overlap. The ends of the two ranges
2737 /// must be less than or equal to `self.len()`.
2741 /// This function will panic if either range exceeds the end of the slice,
2742 /// or if the end of `src` is before the start.
2746 /// Copying four bytes within a slice:
2749 /// let mut bytes = *b"Hello, World!";
2751 /// bytes.copy_within(1..5, 8);
2753 /// assert_eq!(&bytes, b"Hello, Wello!");
2755 #[stable(feature = "copy_within", since = "1.37.0")]
2757 pub fn copy_within<R: RangeBounds<usize>>(&mut self, src: R, dest: usize)
2761 let Range { start: src_start, end: src_end } = check_range(self.len(), src);
2762 let count = src_end - src_start;
2763 assert!(dest <= self.len() - count, "dest is out of bounds");
2764 // SAFETY: the conditions for `ptr::copy` have all been checked above,
2765 // as have those for `ptr::add`.
2767 ptr::copy(self.as_ptr().add(src_start), self.as_mut_ptr().add(dest), count);
2771 /// Swaps all elements in `self` with those in `other`.
2773 /// The length of `other` must be the same as `self`.
2777 /// This function will panic if the two slices have different lengths.
2781 /// Swapping two elements across slices:
2784 /// let mut slice1 = [0, 0];
2785 /// let mut slice2 = [1, 2, 3, 4];
2787 /// slice1.swap_with_slice(&mut slice2[2..]);
2789 /// assert_eq!(slice1, [3, 4]);
2790 /// assert_eq!(slice2, [1, 2, 0, 0]);
2793 /// Rust enforces that there can only be one mutable reference to a
2794 /// particular piece of data in a particular scope. Because of this,
2795 /// attempting to use `swap_with_slice` on a single slice will result in
2796 /// a compile failure:
2799 /// let mut slice = [1, 2, 3, 4, 5];
2800 /// slice[..2].swap_with_slice(&mut slice[3..]); // compile fail!
2803 /// To work around this, we can use [`split_at_mut`] to create two distinct
2804 /// mutable sub-slices from a slice:
2807 /// let mut slice = [1, 2, 3, 4, 5];
2810 /// let (left, right) = slice.split_at_mut(2);
2811 /// left.swap_with_slice(&mut right[1..]);
2814 /// assert_eq!(slice, [4, 5, 3, 1, 2]);
2817 /// [`split_at_mut`]: #method.split_at_mut
2818 #[stable(feature = "swap_with_slice", since = "1.27.0")]
2819 pub fn swap_with_slice(&mut self, other: &mut [T]) {
2820 assert!(self.len() == other.len(), "destination and source slices have different lengths");
2821 // SAFETY: `self` is valid for `self.len()` elements by definition, and `src` was
2822 // checked to have the same length. The slices cannot overlap because
2823 // mutable references are exclusive.
2825 ptr::swap_nonoverlapping(self.as_mut_ptr(), other.as_mut_ptr(), self.len());
2829 /// Function to calculate lengths of the middle and trailing slice for `align_to{,_mut}`.
2830 fn align_to_offsets<U>(&self) -> (usize, usize) {
2831 // What we gonna do about `rest` is figure out what multiple of `U`s we can put in a
2832 // lowest number of `T`s. And how many `T`s we need for each such "multiple".
2834 // Consider for example T=u8 U=u16. Then we can put 1 U in 2 Ts. Simple. Now, consider
2835 // for example a case where size_of::<T> = 16, size_of::<U> = 24. We can put 2 Us in
2836 // place of every 3 Ts in the `rest` slice. A bit more complicated.
2838 // Formula to calculate this is:
2840 // Us = lcm(size_of::<T>, size_of::<U>) / size_of::<U>
2841 // Ts = lcm(size_of::<T>, size_of::<U>) / size_of::<T>
2843 // Expanded and simplified:
2845 // Us = size_of::<T> / gcd(size_of::<T>, size_of::<U>)
2846 // Ts = size_of::<U> / gcd(size_of::<T>, size_of::<U>)
2848 // Luckily since all this is constant-evaluated... performance here matters not!
2850 fn gcd(a: usize, b: usize) -> usize {
2851 use crate::intrinsics;
2852 // iterative stein’s algorithm
2853 // We should still make this `const fn` (and revert to recursive algorithm if we do)
2854 // because relying on llvm to consteval all this is… well, it makes me uncomfortable.
2856 // SAFETY: `a` and `b` are checked to be non-zero values.
2857 let (ctz_a, mut ctz_b) = unsafe {
2864 (intrinsics::cttz_nonzero(a), intrinsics::cttz_nonzero(b))
2866 let k = ctz_a.min(ctz_b);
2867 let mut a = a >> ctz_a;
2870 // remove all factors of 2 from b
2873 mem::swap(&mut a, &mut b);
2876 // SAFETY: `b` is checked to be non-zero.
2881 ctz_b = intrinsics::cttz_nonzero(b);
2886 let gcd: usize = gcd(mem::size_of::<T>(), mem::size_of::<U>());
2887 let ts: usize = mem::size_of::<U>() / gcd;
2888 let us: usize = mem::size_of::<T>() / gcd;
2890 // Armed with this knowledge, we can find how many `U`s we can fit!
2891 let us_len = self.len() / ts * us;
2892 // And how many `T`s will be in the trailing slice!
2893 let ts_len = self.len() % ts;
2897 /// Transmute the slice to a slice of another type, ensuring alignment of the types is
2900 /// This method splits the slice into three distinct slices: prefix, correctly aligned middle
2901 /// slice of a new type, and the suffix slice. The method may make the middle slice the greatest
2902 /// length possible for a given type and input slice, but only your algorithm's performance
2903 /// should depend on that, not its correctness. It is permissible for all of the input data to
2904 /// be returned as the prefix or suffix slice.
2906 /// This method has no purpose when either input element `T` or output element `U` are
2907 /// zero-sized and will return the original slice without splitting anything.
2911 /// This method is essentially a `transmute` with respect to the elements in the returned
2912 /// middle slice, so all the usual caveats pertaining to `transmute::<T, U>` also apply here.
2920 /// let bytes: [u8; 7] = [1, 2, 3, 4, 5, 6, 7];
2921 /// let (prefix, shorts, suffix) = bytes.align_to::<u16>();
2922 /// // less_efficient_algorithm_for_bytes(prefix);
2923 /// // more_efficient_algorithm_for_aligned_shorts(shorts);
2924 /// // less_efficient_algorithm_for_bytes(suffix);
2927 #[stable(feature = "slice_align_to", since = "1.30.0")]
2928 pub unsafe fn align_to<U>(&self) -> (&[T], &[U], &[T]) {
2929 // Note that most of this function will be constant-evaluated,
2930 if mem::size_of::<U>() == 0 || mem::size_of::<T>() == 0 {
2931 // handle ZSTs specially, which is – don't handle them at all.
2932 return (self, &[], &[]);
2935 // First, find at what point do we split between the first and 2nd slice. Easy with
2936 // ptr.align_offset.
2937 let ptr = self.as_ptr();
2938 // SAFETY: See the `align_to_mut` method for the detailed safety comment.
2939 let offset = unsafe { crate::ptr::align_offset(ptr, mem::align_of::<U>()) };
2940 if offset > self.len() {
2943 let (left, rest) = self.split_at(offset);
2944 let (us_len, ts_len) = rest.align_to_offsets::<U>();
2945 // SAFETY: now `rest` is definitely aligned, so `from_raw_parts` below is okay,
2946 // since the caller guarantees that we can transmute `T` to `U` safely.
2950 from_raw_parts(rest.as_ptr() as *const U, us_len),
2951 from_raw_parts(rest.as_ptr().add(rest.len() - ts_len), ts_len),
2957 /// Transmute the slice to a slice of another type, ensuring alignment of the types is
2960 /// This method splits the slice into three distinct slices: prefix, correctly aligned middle
2961 /// slice of a new type, and the suffix slice. The method may make the middle slice the greatest
2962 /// length possible for a given type and input slice, but only your algorithm's performance
2963 /// should depend on that, not its correctness. It is permissible for all of the input data to
2964 /// be returned as the prefix or suffix slice.
2966 /// This method has no purpose when either input element `T` or output element `U` are
2967 /// zero-sized and will return the original slice without splitting anything.
2971 /// This method is essentially a `transmute` with respect to the elements in the returned
2972 /// middle slice, so all the usual caveats pertaining to `transmute::<T, U>` also apply here.
2980 /// let mut bytes: [u8; 7] = [1, 2, 3, 4, 5, 6, 7];
2981 /// let (prefix, shorts, suffix) = bytes.align_to_mut::<u16>();
2982 /// // less_efficient_algorithm_for_bytes(prefix);
2983 /// // more_efficient_algorithm_for_aligned_shorts(shorts);
2984 /// // less_efficient_algorithm_for_bytes(suffix);
2987 #[stable(feature = "slice_align_to", since = "1.30.0")]
2988 pub unsafe fn align_to_mut<U>(&mut self) -> (&mut [T], &mut [U], &mut [T]) {
2989 // Note that most of this function will be constant-evaluated,
2990 if mem::size_of::<U>() == 0 || mem::size_of::<T>() == 0 {
2991 // handle ZSTs specially, which is – don't handle them at all.
2992 return (self, &mut [], &mut []);
2995 // First, find at what point do we split between the first and 2nd slice. Easy with
2996 // ptr.align_offset.
2997 let ptr = self.as_ptr();
2998 // SAFETY: Here we are ensuring we will use aligned pointers for U for the
2999 // rest of the method. This is done by passing a pointer to &[T] with an
3000 // alignment targeted for U.
3001 // `crate::ptr::align_offset` is called with a correctly aligned and
3002 // valid pointer `ptr` (it comes from a reference to `self`) and with
3003 // a size that is a power of two (since it comes from the alignement for U),
3004 // satisfying its safety constraints.
3005 let offset = unsafe { crate::ptr::align_offset(ptr, mem::align_of::<U>()) };
3006 if offset > self.len() {
3007 (self, &mut [], &mut [])
3009 let (left, rest) = self.split_at_mut(offset);
3010 let (us_len, ts_len) = rest.align_to_offsets::<U>();
3011 let rest_len = rest.len();
3012 let mut_ptr = rest.as_mut_ptr();
3013 // We can't use `rest` again after this, that would invalidate its alias `mut_ptr`!
3014 // SAFETY: see comments for `align_to`.
3018 from_raw_parts_mut(mut_ptr as *mut U, us_len),
3019 from_raw_parts_mut(mut_ptr.add(rest_len - ts_len), ts_len),
3025 /// Checks if the elements of this slice are sorted.
3027 /// That is, for each element `a` and its following element `b`, `a <= b` must hold. If the
3028 /// slice yields exactly zero or one element, `true` is returned.
3030 /// Note that if `Self::Item` is only `PartialOrd`, but not `Ord`, the above definition
3031 /// implies that this function returns `false` if any two consecutive items are not
3037 /// #![feature(is_sorted)]
3038 /// let empty: [i32; 0] = [];
3040 /// assert!([1, 2, 2, 9].is_sorted());
3041 /// assert!(![1, 3, 2, 4].is_sorted());
3042 /// assert!([0].is_sorted());
3043 /// assert!(empty.is_sorted());
3044 /// assert!(![0.0, 1.0, f32::NAN].is_sorted());
3047 #[unstable(feature = "is_sorted", reason = "new API", issue = "53485")]
3048 pub fn is_sorted(&self) -> bool
3052 self.is_sorted_by(|a, b| a.partial_cmp(b))
3055 /// Checks if the elements of this slice are sorted using the given comparator function.
3057 /// Instead of using `PartialOrd::partial_cmp`, this function uses the given `compare`
3058 /// function to determine the ordering of two elements. Apart from that, it's equivalent to
3059 /// [`is_sorted`]; see its documentation for more information.
3061 /// [`is_sorted`]: #method.is_sorted
3062 #[unstable(feature = "is_sorted", reason = "new API", issue = "53485")]
3063 pub fn is_sorted_by<F>(&self, mut compare: F) -> bool
3065 F: FnMut(&T, &T) -> Option<Ordering>,
3067 self.iter().is_sorted_by(|a, b| compare(*a, *b))
3070 /// Checks if the elements of this slice are sorted using the given key extraction function.
3072 /// Instead of comparing the slice's elements directly, this function compares the keys of the
3073 /// elements, as determined by `f`. Apart from that, it's equivalent to [`is_sorted`]; see its
3074 /// documentation for more information.
3076 /// [`is_sorted`]: #method.is_sorted
3081 /// #![feature(is_sorted)]
3083 /// assert!(["c", "bb", "aaa"].is_sorted_by_key(|s| s.len()));
3084 /// assert!(![-2i32, -1, 0, 3].is_sorted_by_key(|n| n.abs()));
3087 #[unstable(feature = "is_sorted", reason = "new API", issue = "53485")]
3088 pub fn is_sorted_by_key<F, K>(&self, f: F) -> bool
3093 self.iter().is_sorted_by_key(f)
3096 /// Returns the index of the partition point according to the given predicate
3097 /// (the index of the first element of the second partition).
3099 /// The slice is assumed to be partitioned according to the given predicate.
3100 /// This means that all elements for which the predicate returns true are at the start of the slice
3101 /// and all elements for which the predicate returns false are at the end.
3102 /// For example, [7, 15, 3, 5, 4, 12, 6] is a partitioned under the predicate x % 2 != 0
3103 /// (all odd numbers are at the start, all even at the end).
3105 /// If this slice is not partitioned, the returned result is unspecified and meaningless,
3106 /// as this method performs a kind of binary search.
3111 /// #![feature(partition_point)]
3113 /// let v = [1, 2, 3, 3, 5, 6, 7];
3114 /// let i = v.partition_point(|&x| x < 5);
3116 /// assert_eq!(i, 4);
3117 /// assert!(v[..i].iter().all(|&x| x < 5));
3118 /// assert!(v[i..].iter().all(|&x| !(x < 5)));
3120 #[unstable(feature = "partition_point", reason = "new API", issue = "73831")]
3121 pub fn partition_point<P>(&self, mut pred: P) -> usize
3123 P: FnMut(&T) -> bool,
3126 let mut right = self.len();
3128 while left != right {
3129 let mid = left + (right - left) / 2;
3130 // SAFETY: When `left < right`, `left <= mid < right`.
3131 // Therefore `left` always increases and `right` always decreases,
3132 // and either of them is selected. In both cases `left <= right` is
3133 // satisfied. Therefore if `left < right` in a step, `left <= right`
3134 // is satisfied in the next step. Therefore as long as `left != right`,
3135 // `0 <= left < right <= len` is satisfied and if this case
3136 // `0 <= mid < len` is satisfied too.
3137 let value = unsafe { self.get_unchecked(mid) };
3149 #[stable(feature = "rust1", since = "1.0.0")]
3150 impl<T> Default for &[T] {
3151 /// Creates an empty slice.
3152 fn default() -> Self {
3157 #[stable(feature = "mut_slice_default", since = "1.5.0")]
3158 impl<T> Default for &mut [T] {
3159 /// Creates a mutable empty slice.
3160 fn default() -> Self {