1 //! Slice management and manipulation.
3 //! For more details see [`std::slice`].
5 //! [`std::slice`]: ../../std/slice/index.html
7 #![stable(feature = "rust1", since = "1.0.0")]
9 use crate::cmp::Ordering::{self, Greater, Less};
10 use crate::intrinsics::{assert_unsafe_precondition, exact_div};
11 use crate::marker::Copy;
12 use crate::mem::{self, SizedTypeProperties};
13 use crate::num::NonZeroUsize;
14 use crate::ops::{Bound, FnMut, OneSidedRange, Range, RangeBounds};
15 use crate::option::Option;
16 use crate::option::Option::{None, Some};
18 use crate::result::Result;
19 use crate::result::Result::{Err, Ok};
20 use crate::simd::{self, Simd};
24 feature = "slice_internals",
26 reason = "exposed from core to be reused in std; use the memchr crate"
28 /// Pure rust memchr implementation, taken from rust-memchr
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 = "slice_group_by", issue = "80552")]
63 pub use iter::{GroupBy, GroupByMut};
65 #[stable(feature = "split_inclusive", since = "1.51.0")]
66 pub use iter::{SplitInclusive, SplitInclusiveMut};
68 #[stable(feature = "rust1", since = "1.0.0")]
69 pub use raw::{from_raw_parts, from_raw_parts_mut};
71 #[stable(feature = "from_ref", since = "1.28.0")]
72 pub use raw::{from_mut, from_ref};
74 #[unstable(feature = "slice_from_ptr_range", issue = "89792")]
75 pub use raw::{from_mut_ptr_range, from_ptr_range};
77 // This function is public only because there is no other way to unit test heapsort.
78 #[unstable(feature = "sort_internals", reason = "internal to sort module", issue = "none")]
79 pub use sort::heapsort;
81 #[stable(feature = "slice_get_slice", since = "1.28.0")]
82 pub use index::SliceIndex;
84 #[unstable(feature = "slice_range", issue = "76393")]
87 #[stable(feature = "inherent_ascii_escape", since = "1.60.0")]
88 pub use ascii::EscapeAscii;
90 /// Calculates the direction and split point of a one-sided range.
92 /// This is a helper function for `take` and `take_mut` that returns
93 /// the direction of the split (front or back) as well as the index at
94 /// which to split. Returns `None` if the split index would overflow.
96 fn split_point_of(range: impl OneSidedRange<usize>) -> Option<(Direction, usize)> {
99 Some(match (range.start_bound(), range.end_bound()) {
100 (Unbounded, Excluded(i)) => (Direction::Front, *i),
101 (Unbounded, Included(i)) => (Direction::Front, i.checked_add(1)?),
102 (Excluded(i), Unbounded) => (Direction::Back, i.checked_add(1)?),
103 (Included(i), Unbounded) => (Direction::Back, *i),
115 /// Returns the number of elements in the slice.
120 /// let a = [1, 2, 3];
121 /// assert_eq!(a.len(), 3);
123 #[lang = "slice_len_fn"]
124 #[stable(feature = "rust1", since = "1.0.0")]
125 #[rustc_const_stable(feature = "const_slice_len", since = "1.39.0")]
126 #[rustc_allow_const_fn_unstable(ptr_metadata)]
129 pub const fn len(&self) -> usize {
133 /// Returns `true` if the slice has a length of 0.
138 /// let a = [1, 2, 3];
139 /// assert!(!a.is_empty());
141 #[stable(feature = "rust1", since = "1.0.0")]
142 #[rustc_const_stable(feature = "const_slice_is_empty", since = "1.39.0")]
145 pub const fn is_empty(&self) -> bool {
149 /// Returns the first element of the slice, or `None` if it is empty.
154 /// let v = [10, 40, 30];
155 /// assert_eq!(Some(&10), v.first());
157 /// let w: &[i32] = &[];
158 /// assert_eq!(None, w.first());
160 #[stable(feature = "rust1", since = "1.0.0")]
161 #[rustc_const_stable(feature = "const_slice_first_last_not_mut", since = "1.56.0")]
164 pub const fn first(&self) -> Option<&T> {
165 if let [first, ..] = self { Some(first) } else { None }
168 /// Returns a mutable pointer to the first element of the slice, or `None` if it is empty.
173 /// let x = &mut [0, 1, 2];
175 /// if let Some(first) = x.first_mut() {
178 /// assert_eq!(x, &[5, 1, 2]);
180 #[stable(feature = "rust1", since = "1.0.0")]
181 #[rustc_const_unstable(feature = "const_slice_first_last", issue = "83570")]
184 pub const fn first_mut(&mut self) -> Option<&mut T> {
185 if let [first, ..] = self { Some(first) } else { None }
188 /// Returns the first and all the rest of the elements of the slice, or `None` if it is empty.
193 /// let x = &[0, 1, 2];
195 /// if let Some((first, elements)) = x.split_first() {
196 /// assert_eq!(first, &0);
197 /// assert_eq!(elements, &[1, 2]);
200 #[stable(feature = "slice_splits", since = "1.5.0")]
201 #[rustc_const_stable(feature = "const_slice_first_last_not_mut", since = "1.56.0")]
204 pub const fn split_first(&self) -> Option<(&T, &[T])> {
205 if let [first, tail @ ..] = self { Some((first, tail)) } else { None }
208 /// Returns the first and all the rest of the elements of the slice, or `None` if it is empty.
213 /// let x = &mut [0, 1, 2];
215 /// if let Some((first, elements)) = x.split_first_mut() {
220 /// assert_eq!(x, &[3, 4, 5]);
222 #[stable(feature = "slice_splits", since = "1.5.0")]
223 #[rustc_const_unstable(feature = "const_slice_first_last", issue = "83570")]
226 pub const fn split_first_mut(&mut self) -> Option<(&mut T, &mut [T])> {
227 if let [first, tail @ ..] = self { Some((first, tail)) } else { None }
230 /// Returns the last and all the rest of the elements of the slice, or `None` if it is empty.
235 /// let x = &[0, 1, 2];
237 /// if let Some((last, elements)) = x.split_last() {
238 /// assert_eq!(last, &2);
239 /// assert_eq!(elements, &[0, 1]);
242 #[stable(feature = "slice_splits", since = "1.5.0")]
243 #[rustc_const_stable(feature = "const_slice_first_last_not_mut", since = "1.56.0")]
246 pub const fn split_last(&self) -> Option<(&T, &[T])> {
247 if let [init @ .., last] = self { Some((last, init)) } else { None }
250 /// Returns the last and all the rest of the elements of the slice, or `None` if it is empty.
255 /// let x = &mut [0, 1, 2];
257 /// if let Some((last, elements)) = x.split_last_mut() {
262 /// assert_eq!(x, &[4, 5, 3]);
264 #[stable(feature = "slice_splits", since = "1.5.0")]
265 #[rustc_const_unstable(feature = "const_slice_first_last", issue = "83570")]
268 pub const fn split_last_mut(&mut self) -> Option<(&mut T, &mut [T])> {
269 if let [init @ .., last] = self { Some((last, init)) } else { None }
272 /// Returns the last element of the slice, or `None` if it is empty.
277 /// let v = [10, 40, 30];
278 /// assert_eq!(Some(&30), v.last());
280 /// let w: &[i32] = &[];
281 /// assert_eq!(None, w.last());
283 #[stable(feature = "rust1", since = "1.0.0")]
284 #[rustc_const_stable(feature = "const_slice_first_last_not_mut", since = "1.56.0")]
287 pub const fn last(&self) -> Option<&T> {
288 if let [.., last] = self { Some(last) } else { None }
291 /// Returns a mutable pointer to the last item in the slice.
296 /// let x = &mut [0, 1, 2];
298 /// if let Some(last) = x.last_mut() {
301 /// assert_eq!(x, &[0, 1, 10]);
303 #[stable(feature = "rust1", since = "1.0.0")]
304 #[rustc_const_unstable(feature = "const_slice_first_last", issue = "83570")]
307 pub const fn last_mut(&mut self) -> Option<&mut T> {
308 if let [.., last] = self { Some(last) } else { None }
311 /// Returns a reference to an element or subslice depending on the type of
314 /// - If given a position, returns a reference to the element at that
315 /// position or `None` if out of bounds.
316 /// - If given a range, returns the subslice corresponding to that range,
317 /// or `None` if out of bounds.
322 /// let v = [10, 40, 30];
323 /// assert_eq!(Some(&40), v.get(1));
324 /// assert_eq!(Some(&[10, 40][..]), v.get(0..2));
325 /// assert_eq!(None, v.get(3));
326 /// assert_eq!(None, v.get(0..4));
328 #[stable(feature = "rust1", since = "1.0.0")]
329 #[rustc_const_unstable(feature = "const_slice_index", issue = "none")]
332 pub const fn get<I>(&self, index: I) -> Option<&I::Output>
334 I: ~const SliceIndex<Self>,
339 /// Returns a mutable reference to an element or subslice depending on the
340 /// type of index (see [`get`]) or `None` if the index is out of bounds.
342 /// [`get`]: slice::get
347 /// let x = &mut [0, 1, 2];
349 /// if let Some(elem) = x.get_mut(1) {
352 /// assert_eq!(x, &[0, 42, 2]);
354 #[stable(feature = "rust1", since = "1.0.0")]
355 #[rustc_const_unstable(feature = "const_slice_index", issue = "none")]
358 pub const fn get_mut<I>(&mut self, index: I) -> Option<&mut I::Output>
360 I: ~const SliceIndex<Self>,
365 /// Returns a reference to an element or subslice, without doing bounds
368 /// For a safe alternative see [`get`].
372 /// Calling this method with an out-of-bounds index is *[undefined behavior]*
373 /// even if the resulting reference is not used.
375 /// [`get`]: slice::get
376 /// [undefined behavior]: https://doc.rust-lang.org/reference/behavior-considered-undefined.html
381 /// let x = &[1, 2, 4];
384 /// assert_eq!(x.get_unchecked(1), &2);
387 #[stable(feature = "rust1", since = "1.0.0")]
388 #[rustc_const_unstable(feature = "const_slice_index", issue = "none")]
391 pub const unsafe fn get_unchecked<I>(&self, index: I) -> &I::Output
393 I: ~const SliceIndex<Self>,
395 // SAFETY: the caller must uphold most of the safety requirements for `get_unchecked`;
396 // the slice is dereferenceable because `self` is a safe reference.
397 // The returned pointer is safe because impls of `SliceIndex` have to guarantee that it is.
398 unsafe { &*index.get_unchecked(self) }
401 /// Returns a mutable reference to an element or subslice, without doing
404 /// For a safe alternative see [`get_mut`].
408 /// Calling this method with an out-of-bounds index is *[undefined behavior]*
409 /// even if the resulting reference is not used.
411 /// [`get_mut`]: slice::get_mut
412 /// [undefined behavior]: https://doc.rust-lang.org/reference/behavior-considered-undefined.html
417 /// let x = &mut [1, 2, 4];
420 /// let elem = x.get_unchecked_mut(1);
423 /// assert_eq!(x, &[1, 13, 4]);
425 #[stable(feature = "rust1", since = "1.0.0")]
426 #[rustc_const_unstable(feature = "const_slice_index", issue = "none")]
429 pub const unsafe fn get_unchecked_mut<I>(&mut self, index: I) -> &mut I::Output
431 I: ~const SliceIndex<Self>,
433 // SAFETY: the caller must uphold the safety requirements for `get_unchecked_mut`;
434 // the slice is dereferenceable because `self` is a safe reference.
435 // The returned pointer is safe because impls of `SliceIndex` have to guarantee that it is.
436 unsafe { &mut *index.get_unchecked_mut(self) }
439 /// Returns a raw pointer to the slice's buffer.
441 /// The caller must ensure that the slice outlives the pointer this
442 /// function returns, or else it will end up pointing to garbage.
444 /// The caller must also ensure that the memory the pointer (non-transitively) points to
445 /// is never written to (except inside an `UnsafeCell`) using this pointer or any pointer
446 /// derived from it. If you need to mutate the contents of the slice, use [`as_mut_ptr`].
448 /// Modifying the container referenced by this slice may cause its buffer
449 /// to be reallocated, which would also make any pointers to it invalid.
454 /// let x = &[1, 2, 4];
455 /// let x_ptr = x.as_ptr();
458 /// for i in 0..x.len() {
459 /// assert_eq!(x.get_unchecked(i), &*x_ptr.add(i));
464 /// [`as_mut_ptr`]: slice::as_mut_ptr
465 #[stable(feature = "rust1", since = "1.0.0")]
466 #[rustc_const_stable(feature = "const_slice_as_ptr", since = "1.32.0")]
469 pub const fn as_ptr(&self) -> *const T {
470 self as *const [T] as *const T
473 /// Returns an unsafe mutable pointer to the slice's buffer.
475 /// The caller must ensure that the slice outlives the pointer this
476 /// function returns, or else it will end up pointing to garbage.
478 /// Modifying the container referenced by this slice may cause its buffer
479 /// to be reallocated, which would also make any pointers to it invalid.
484 /// let x = &mut [1, 2, 4];
485 /// let x_ptr = x.as_mut_ptr();
488 /// for i in 0..x.len() {
489 /// *x_ptr.add(i) += 2;
492 /// assert_eq!(x, &[3, 4, 6]);
494 #[stable(feature = "rust1", since = "1.0.0")]
495 #[rustc_const_stable(feature = "const_ptr_offset", since = "1.61.0")]
496 #[rustc_allow_const_fn_unstable(const_mut_refs)]
499 pub const fn as_mut_ptr(&mut self) -> *mut T {
500 self as *mut [T] as *mut T
503 /// Returns the two raw pointers spanning the slice.
505 /// The returned range is half-open, which means that the end pointer
506 /// points *one past* the last element of the slice. This way, an empty
507 /// slice is represented by two equal pointers, and the difference between
508 /// the two pointers represents the size of the slice.
510 /// See [`as_ptr`] for warnings on using these pointers. The end pointer
511 /// requires extra caution, as it does not point to a valid element in the
514 /// This function is useful for interacting with foreign interfaces which
515 /// use two pointers to refer to a range of elements in memory, as is
518 /// It can also be useful to check if a pointer to an element refers to an
519 /// element of this slice:
522 /// let a = [1, 2, 3];
523 /// let x = &a[1] as *const _;
524 /// let y = &5 as *const _;
526 /// assert!(a.as_ptr_range().contains(&x));
527 /// assert!(!a.as_ptr_range().contains(&y));
530 /// [`as_ptr`]: slice::as_ptr
531 #[stable(feature = "slice_ptr_range", since = "1.48.0")]
532 #[rustc_const_stable(feature = "const_ptr_offset", since = "1.61.0")]
535 pub const fn as_ptr_range(&self) -> Range<*const T> {
536 let start = self.as_ptr();
537 // SAFETY: The `add` here is safe, because:
539 // - Both pointers are part of the same object, as pointing directly
540 // past the object also counts.
542 // - The size of the slice is never larger than isize::MAX bytes, as
544 // - https://github.com/rust-lang/unsafe-code-guidelines/issues/102#issuecomment-473340447
545 // - https://doc.rust-lang.org/reference/behavior-considered-undefined.html
546 // - https://doc.rust-lang.org/core/slice/fn.from_raw_parts.html#safety
547 // (This doesn't seem normative yet, but the very same assumption is
548 // made in many places, including the Index implementation of slices.)
550 // - There is no wrapping around involved, as slices do not wrap past
551 // the end of the address space.
553 // See the documentation of pointer::add.
554 let end = unsafe { start.add(self.len()) };
558 /// Returns the two unsafe mutable pointers spanning the slice.
560 /// The returned range is half-open, which means that the end pointer
561 /// points *one past* the last element of the slice. This way, an empty
562 /// slice is represented by two equal pointers, and the difference between
563 /// the two pointers represents the size of the slice.
565 /// See [`as_mut_ptr`] for warnings on using these pointers. The end
566 /// pointer requires extra caution, as it does not point to a valid element
569 /// This function is useful for interacting with foreign interfaces which
570 /// use two pointers to refer to a range of elements in memory, as is
573 /// [`as_mut_ptr`]: slice::as_mut_ptr
574 #[stable(feature = "slice_ptr_range", since = "1.48.0")]
575 #[rustc_const_stable(feature = "const_ptr_offset", since = "1.61.0")]
576 #[rustc_allow_const_fn_unstable(const_mut_refs)]
579 pub const fn as_mut_ptr_range(&mut self) -> Range<*mut T> {
580 let start = self.as_mut_ptr();
581 // SAFETY: See as_ptr_range() above for why `add` here is safe.
582 let end = unsafe { start.add(self.len()) };
586 /// Swaps two elements in the slice.
590 /// * a - The index of the first element
591 /// * b - The index of the second element
595 /// Panics if `a` or `b` are out of bounds.
600 /// let mut v = ["a", "b", "c", "d", "e"];
602 /// assert!(v == ["a", "b", "e", "d", "c"]);
604 #[stable(feature = "rust1", since = "1.0.0")]
605 #[rustc_const_unstable(feature = "const_swap", issue = "83163")]
608 pub const fn swap(&mut self, a: usize, b: usize) {
609 // FIXME: use swap_unchecked here (https://github.com/rust-lang/rust/pull/88540#issuecomment-944344343)
610 // Can't take two mutable loans from one vector, so instead use raw pointers.
611 let pa = ptr::addr_of_mut!(self[a]);
612 let pb = ptr::addr_of_mut!(self[b]);
613 // SAFETY: `pa` and `pb` have been created from safe mutable references and refer
614 // to elements in the slice and therefore are guaranteed to be valid and aligned.
615 // Note that accessing the elements behind `a` and `b` is checked and will
616 // panic when out of bounds.
622 /// Swaps two elements in the slice, without doing bounds checking.
624 /// For a safe alternative see [`swap`].
628 /// * a - The index of the first element
629 /// * b - The index of the second element
633 /// Calling this method with an out-of-bounds index is *[undefined behavior]*.
634 /// The caller has to ensure that `a < self.len()` and `b < self.len()`.
639 /// #![feature(slice_swap_unchecked)]
641 /// let mut v = ["a", "b", "c", "d"];
642 /// // SAFETY: we know that 1 and 3 are both indices of the slice
643 /// unsafe { v.swap_unchecked(1, 3) };
644 /// assert!(v == ["a", "d", "c", "b"]);
647 /// [`swap`]: slice::swap
648 /// [undefined behavior]: https://doc.rust-lang.org/reference/behavior-considered-undefined.html
649 #[unstable(feature = "slice_swap_unchecked", issue = "88539")]
650 #[rustc_const_unstable(feature = "const_swap", issue = "83163")]
651 pub const unsafe fn swap_unchecked(&mut self, a: usize, b: usize) {
653 let ptr = this.as_mut_ptr();
654 // SAFETY: caller has to guarantee that `a < self.len()` and `b < self.len()`
656 assert_unsafe_precondition!(
657 "slice::swap_unchecked requires that the indices are within the slice",
658 [T](a: usize, b: usize, this: &mut [T]) => a < this.len() && b < this.len()
660 ptr::swap(ptr.add(a), ptr.add(b));
664 /// Reverses the order of elements in the slice, in place.
669 /// let mut v = [1, 2, 3];
671 /// assert!(v == [3, 2, 1]);
673 #[stable(feature = "rust1", since = "1.0.0")]
674 #[rustc_const_unstable(feature = "const_reverse", issue = "100784")]
676 pub const fn reverse(&mut self) {
677 let half_len = self.len() / 2;
678 let Range { start, end } = self.as_mut_ptr_range();
680 // These slices will skip the middle item for an odd length,
681 // since that one doesn't need to move.
682 let (front_half, back_half) =
683 // SAFETY: Both are subparts of the original slice, so the memory
684 // range is valid, and they don't overlap because they're each only
685 // half (or less) of the original slice.
688 slice::from_raw_parts_mut(start, half_len),
689 slice::from_raw_parts_mut(end.sub(half_len), half_len),
693 // Introducing a function boundary here means that the two halves
694 // get `noalias` markers, allowing better optimization as LLVM
695 // knows that they're disjoint, unlike in the original slice.
696 revswap(front_half, back_half, half_len);
699 const fn revswap<T>(a: &mut [T], b: &mut [T], n: usize) {
700 debug_assert!(a.len() == n);
701 debug_assert!(b.len() == n);
703 // Because this function is first compiled in isolation,
704 // this check tells LLVM that the indexing below is
705 // in-bounds. Then after inlining -- once the actual
706 // lengths of the slices are known -- it's removed.
707 let (a, b) = (&mut a[..n], &mut b[..n]);
711 mem::swap(&mut a[i], &mut b[n - 1 - i]);
717 /// Returns an iterator over the slice.
719 /// The iterator yields all items from start to end.
724 /// let x = &[1, 2, 4];
725 /// let mut iterator = x.iter();
727 /// assert_eq!(iterator.next(), Some(&1));
728 /// assert_eq!(iterator.next(), Some(&2));
729 /// assert_eq!(iterator.next(), Some(&4));
730 /// assert_eq!(iterator.next(), None);
732 #[stable(feature = "rust1", since = "1.0.0")]
734 pub fn iter(&self) -> Iter<'_, T> {
738 /// Returns an iterator that allows modifying each value.
740 /// The iterator yields all items from start to end.
745 /// let x = &mut [1, 2, 4];
746 /// for elem in x.iter_mut() {
749 /// assert_eq!(x, &[3, 4, 6]);
751 #[stable(feature = "rust1", since = "1.0.0")]
753 pub fn iter_mut(&mut self) -> IterMut<'_, T> {
757 /// Returns an iterator over all contiguous windows of length
758 /// `size`. The windows overlap. If the slice is shorter than
759 /// `size`, the iterator returns no values.
763 /// Panics if `size` is 0.
768 /// let slice = ['r', 'u', 's', 't'];
769 /// let mut iter = slice.windows(2);
770 /// assert_eq!(iter.next().unwrap(), &['r', 'u']);
771 /// assert_eq!(iter.next().unwrap(), &['u', 's']);
772 /// assert_eq!(iter.next().unwrap(), &['s', 't']);
773 /// assert!(iter.next().is_none());
776 /// If the slice is shorter than `size`:
779 /// let slice = ['f', 'o', 'o'];
780 /// let mut iter = slice.windows(4);
781 /// assert!(iter.next().is_none());
783 #[stable(feature = "rust1", since = "1.0.0")]
785 pub fn windows(&self, size: usize) -> Windows<'_, T> {
786 let size = NonZeroUsize::new(size).expect("size is zero");
787 Windows::new(self, size)
790 /// Returns an iterator over `chunk_size` elements of the slice at a time, starting at the
791 /// beginning of the slice.
793 /// The chunks are slices and do not overlap. If `chunk_size` does not divide the length of the
794 /// slice, then the last chunk will not have length `chunk_size`.
796 /// See [`chunks_exact`] for a variant of this iterator that returns chunks of always exactly
797 /// `chunk_size` elements, and [`rchunks`] for the same iterator but starting at the end of the
802 /// Panics if `chunk_size` is 0.
807 /// let slice = ['l', 'o', 'r', 'e', 'm'];
808 /// let mut iter = slice.chunks(2);
809 /// assert_eq!(iter.next().unwrap(), &['l', 'o']);
810 /// assert_eq!(iter.next().unwrap(), &['r', 'e']);
811 /// assert_eq!(iter.next().unwrap(), &['m']);
812 /// assert!(iter.next().is_none());
815 /// [`chunks_exact`]: slice::chunks_exact
816 /// [`rchunks`]: slice::rchunks
817 #[stable(feature = "rust1", since = "1.0.0")]
819 pub fn chunks(&self, chunk_size: usize) -> Chunks<'_, T> {
820 assert_ne!(chunk_size, 0, "chunks cannot have a size of zero");
821 Chunks::new(self, chunk_size)
824 /// Returns an iterator over `chunk_size` elements of the slice at a time, starting at the
825 /// beginning of the slice.
827 /// The chunks are mutable slices, and do not overlap. If `chunk_size` does not divide the
828 /// length of the slice, then the last chunk will not have length `chunk_size`.
830 /// See [`chunks_exact_mut`] for a variant of this iterator that returns chunks of always
831 /// exactly `chunk_size` elements, and [`rchunks_mut`] for the same iterator but starting at
832 /// the end of the slice.
836 /// Panics if `chunk_size` is 0.
841 /// let v = &mut [0, 0, 0, 0, 0];
842 /// let mut count = 1;
844 /// for chunk in v.chunks_mut(2) {
845 /// for elem in chunk.iter_mut() {
850 /// assert_eq!(v, &[1, 1, 2, 2, 3]);
853 /// [`chunks_exact_mut`]: slice::chunks_exact_mut
854 /// [`rchunks_mut`]: slice::rchunks_mut
855 #[stable(feature = "rust1", since = "1.0.0")]
857 pub fn chunks_mut(&mut self, chunk_size: usize) -> ChunksMut<'_, T> {
858 assert_ne!(chunk_size, 0, "chunks cannot have a size of zero");
859 ChunksMut::new(self, chunk_size)
862 /// Returns an iterator over `chunk_size` elements of the slice at a time, starting at the
863 /// beginning of the slice.
865 /// The chunks are slices and do not overlap. If `chunk_size` does not divide the length of the
866 /// slice, then the last up to `chunk_size-1` elements will be omitted and can be retrieved
867 /// from the `remainder` function of the iterator.
869 /// Due to each chunk having exactly `chunk_size` elements, the compiler can often optimize the
870 /// resulting code better than in the case of [`chunks`].
872 /// See [`chunks`] for a variant of this iterator that also returns the remainder as a smaller
873 /// chunk, and [`rchunks_exact`] for the same iterator but starting at the end of the slice.
877 /// Panics if `chunk_size` is 0.
882 /// let slice = ['l', 'o', 'r', 'e', 'm'];
883 /// let mut iter = slice.chunks_exact(2);
884 /// assert_eq!(iter.next().unwrap(), &['l', 'o']);
885 /// assert_eq!(iter.next().unwrap(), &['r', 'e']);
886 /// assert!(iter.next().is_none());
887 /// assert_eq!(iter.remainder(), &['m']);
890 /// [`chunks`]: slice::chunks
891 /// [`rchunks_exact`]: slice::rchunks_exact
892 #[stable(feature = "chunks_exact", since = "1.31.0")]
894 pub fn chunks_exact(&self, chunk_size: usize) -> ChunksExact<'_, T> {
895 assert_ne!(chunk_size, 0);
896 ChunksExact::new(self, chunk_size)
899 /// Returns an iterator over `chunk_size` elements of the slice at a time, starting at the
900 /// beginning of the slice.
902 /// The chunks are mutable slices, and do not overlap. If `chunk_size` does not divide the
903 /// length of the slice, then the last up to `chunk_size-1` elements will be omitted and can be
904 /// retrieved from the `into_remainder` function of the iterator.
906 /// Due to each chunk having exactly `chunk_size` elements, the compiler can often optimize the
907 /// resulting code better than in the case of [`chunks_mut`].
909 /// See [`chunks_mut`] for a variant of this iterator that also returns the remainder as a
910 /// smaller chunk, and [`rchunks_exact_mut`] for the same iterator but starting at the end of
915 /// Panics if `chunk_size` is 0.
920 /// let v = &mut [0, 0, 0, 0, 0];
921 /// let mut count = 1;
923 /// for chunk in v.chunks_exact_mut(2) {
924 /// for elem in chunk.iter_mut() {
929 /// assert_eq!(v, &[1, 1, 2, 2, 0]);
932 /// [`chunks_mut`]: slice::chunks_mut
933 /// [`rchunks_exact_mut`]: slice::rchunks_exact_mut
934 #[stable(feature = "chunks_exact", since = "1.31.0")]
936 pub fn chunks_exact_mut(&mut self, chunk_size: usize) -> ChunksExactMut<'_, T> {
937 assert_ne!(chunk_size, 0);
938 ChunksExactMut::new(self, chunk_size)
941 /// Splits the slice into a slice of `N`-element arrays,
942 /// assuming that there's no remainder.
946 /// This may only be called when
947 /// - The slice splits exactly into `N`-element chunks (aka `self.len() % N == 0`).
953 /// #![feature(slice_as_chunks)]
954 /// let slice: &[char] = &['l', 'o', 'r', 'e', 'm', '!'];
955 /// let chunks: &[[char; 1]] =
956 /// // SAFETY: 1-element chunks never have remainder
957 /// unsafe { slice.as_chunks_unchecked() };
958 /// assert_eq!(chunks, &[['l'], ['o'], ['r'], ['e'], ['m'], ['!']]);
959 /// let chunks: &[[char; 3]] =
960 /// // SAFETY: The slice length (6) is a multiple of 3
961 /// unsafe { slice.as_chunks_unchecked() };
962 /// assert_eq!(chunks, &[['l', 'o', 'r'], ['e', 'm', '!']]);
964 /// // These would be unsound:
965 /// // let chunks: &[[_; 5]] = slice.as_chunks_unchecked() // The slice length is not a multiple of 5
966 /// // let chunks: &[[_; 0]] = slice.as_chunks_unchecked() // Zero-length chunks are never allowed
968 #[unstable(feature = "slice_as_chunks", issue = "74985")]
971 pub unsafe fn as_chunks_unchecked<const N: usize>(&self) -> &[[T; N]] {
973 // SAFETY: Caller must guarantee that `N` is nonzero and exactly divides the slice length
974 let new_len = unsafe {
975 assert_unsafe_precondition!(
976 "slice::as_chunks_unchecked requires `N != 0` and the slice to split exactly into `N`-element chunks",
977 [T](this: &[T], N: usize) => N != 0 && this.len() % N == 0
979 exact_div(self.len(), N)
981 // SAFETY: We cast a slice of `new_len * N` elements into
982 // a slice of `new_len` many `N` elements chunks.
983 unsafe { from_raw_parts(self.as_ptr().cast(), new_len) }
986 /// Splits the slice into a slice of `N`-element arrays,
987 /// starting at the beginning of the slice,
988 /// and a remainder slice with length strictly less than `N`.
992 /// Panics if `N` is 0. This check will most probably get changed to a compile time
993 /// error before this method gets stabilized.
998 /// #![feature(slice_as_chunks)]
999 /// let slice = ['l', 'o', 'r', 'e', 'm'];
1000 /// let (chunks, remainder) = slice.as_chunks();
1001 /// assert_eq!(chunks, &[['l', 'o'], ['r', 'e']]);
1002 /// assert_eq!(remainder, &['m']);
1004 #[unstable(feature = "slice_as_chunks", issue = "74985")]
1007 pub fn as_chunks<const N: usize>(&self) -> (&[[T; N]], &[T]) {
1009 let len = self.len() / N;
1010 let (multiple_of_n, remainder) = self.split_at(len * N);
1011 // SAFETY: We already panicked for zero, and ensured by construction
1012 // that the length of the subslice is a multiple of N.
1013 let array_slice = unsafe { multiple_of_n.as_chunks_unchecked() };
1014 (array_slice, remainder)
1017 /// Splits the slice into a slice of `N`-element arrays,
1018 /// starting at the end of the slice,
1019 /// and a remainder slice with length strictly less than `N`.
1023 /// Panics if `N` is 0. This check will most probably get changed to a compile time
1024 /// error before this method gets stabilized.
1029 /// #![feature(slice_as_chunks)]
1030 /// let slice = ['l', 'o', 'r', 'e', 'm'];
1031 /// let (remainder, chunks) = slice.as_rchunks();
1032 /// assert_eq!(remainder, &['l']);
1033 /// assert_eq!(chunks, &[['o', 'r'], ['e', 'm']]);
1035 #[unstable(feature = "slice_as_chunks", issue = "74985")]
1038 pub fn as_rchunks<const N: usize>(&self) -> (&[T], &[[T; N]]) {
1040 let len = self.len() / N;
1041 let (remainder, multiple_of_n) = self.split_at(self.len() - len * N);
1042 // SAFETY: We already panicked for zero, and ensured by construction
1043 // that the length of the subslice is a multiple of N.
1044 let array_slice = unsafe { multiple_of_n.as_chunks_unchecked() };
1045 (remainder, array_slice)
1048 /// Returns an iterator over `N` elements of the slice at a time, starting at the
1049 /// beginning of the slice.
1051 /// The chunks are array references and do not overlap. If `N` does not divide the
1052 /// length of the slice, then the last up to `N-1` elements will be omitted and can be
1053 /// retrieved from the `remainder` function of the iterator.
1055 /// This method is the const generic equivalent of [`chunks_exact`].
1059 /// Panics if `N` is 0. This check will most probably get changed to a compile time
1060 /// error before this method gets stabilized.
1065 /// #![feature(array_chunks)]
1066 /// let slice = ['l', 'o', 'r', 'e', 'm'];
1067 /// let mut iter = slice.array_chunks();
1068 /// assert_eq!(iter.next().unwrap(), &['l', 'o']);
1069 /// assert_eq!(iter.next().unwrap(), &['r', 'e']);
1070 /// assert!(iter.next().is_none());
1071 /// assert_eq!(iter.remainder(), &['m']);
1074 /// [`chunks_exact`]: slice::chunks_exact
1075 #[unstable(feature = "array_chunks", issue = "74985")]
1077 pub fn array_chunks<const N: usize>(&self) -> ArrayChunks<'_, T, N> {
1079 ArrayChunks::new(self)
1082 /// Splits the slice into a slice of `N`-element arrays,
1083 /// assuming that there's no remainder.
1087 /// This may only be called when
1088 /// - The slice splits exactly into `N`-element chunks (aka `self.len() % N == 0`).
1094 /// #![feature(slice_as_chunks)]
1095 /// let slice: &mut [char] = &mut ['l', 'o', 'r', 'e', 'm', '!'];
1096 /// let chunks: &mut [[char; 1]] =
1097 /// // SAFETY: 1-element chunks never have remainder
1098 /// unsafe { slice.as_chunks_unchecked_mut() };
1099 /// chunks[0] = ['L'];
1100 /// assert_eq!(chunks, &[['L'], ['o'], ['r'], ['e'], ['m'], ['!']]);
1101 /// let chunks: &mut [[char; 3]] =
1102 /// // SAFETY: The slice length (6) is a multiple of 3
1103 /// unsafe { slice.as_chunks_unchecked_mut() };
1104 /// chunks[1] = ['a', 'x', '?'];
1105 /// assert_eq!(slice, &['L', 'o', 'r', 'a', 'x', '?']);
1107 /// // These would be unsound:
1108 /// // let chunks: &[[_; 5]] = slice.as_chunks_unchecked_mut() // The slice length is not a multiple of 5
1109 /// // let chunks: &[[_; 0]] = slice.as_chunks_unchecked_mut() // Zero-length chunks are never allowed
1111 #[unstable(feature = "slice_as_chunks", issue = "74985")]
1114 pub unsafe fn as_chunks_unchecked_mut<const N: usize>(&mut self) -> &mut [[T; N]] {
1116 // SAFETY: Caller must guarantee that `N` is nonzero and exactly divides the slice length
1117 let new_len = unsafe {
1118 assert_unsafe_precondition!(
1119 "slice::as_chunks_unchecked_mut requires `N != 0` and the slice to split exactly into `N`-element chunks",
1120 [T](this: &[T], N: usize) => N != 0 && this.len() % N == 0
1122 exact_div(this.len(), N)
1124 // SAFETY: We cast a slice of `new_len * N` elements into
1125 // a slice of `new_len` many `N` elements chunks.
1126 unsafe { from_raw_parts_mut(self.as_mut_ptr().cast(), new_len) }
1129 /// Splits the slice into a slice of `N`-element arrays,
1130 /// starting at the beginning of the slice,
1131 /// and a remainder slice with length strictly less than `N`.
1135 /// Panics if `N` is 0. This check will most probably get changed to a compile time
1136 /// error before this method gets stabilized.
1141 /// #![feature(slice_as_chunks)]
1142 /// let v = &mut [0, 0, 0, 0, 0];
1143 /// let mut count = 1;
1145 /// let (chunks, remainder) = v.as_chunks_mut();
1146 /// remainder[0] = 9;
1147 /// for chunk in chunks {
1148 /// *chunk = [count; 2];
1151 /// assert_eq!(v, &[1, 1, 2, 2, 9]);
1153 #[unstable(feature = "slice_as_chunks", issue = "74985")]
1156 pub fn as_chunks_mut<const N: usize>(&mut self) -> (&mut [[T; N]], &mut [T]) {
1158 let len = self.len() / N;
1159 let (multiple_of_n, remainder) = self.split_at_mut(len * N);
1160 // SAFETY: We already panicked for zero, and ensured by construction
1161 // that the length of the subslice is a multiple of N.
1162 let array_slice = unsafe { multiple_of_n.as_chunks_unchecked_mut() };
1163 (array_slice, remainder)
1166 /// Splits the slice into a slice of `N`-element arrays,
1167 /// starting at the end of the slice,
1168 /// and a remainder slice with length strictly less than `N`.
1172 /// Panics if `N` is 0. This check will most probably get changed to a compile time
1173 /// error before this method gets stabilized.
1178 /// #![feature(slice_as_chunks)]
1179 /// let v = &mut [0, 0, 0, 0, 0];
1180 /// let mut count = 1;
1182 /// let (remainder, chunks) = v.as_rchunks_mut();
1183 /// remainder[0] = 9;
1184 /// for chunk in chunks {
1185 /// *chunk = [count; 2];
1188 /// assert_eq!(v, &[9, 1, 1, 2, 2]);
1190 #[unstable(feature = "slice_as_chunks", issue = "74985")]
1193 pub fn as_rchunks_mut<const N: usize>(&mut self) -> (&mut [T], &mut [[T; N]]) {
1195 let len = self.len() / N;
1196 let (remainder, multiple_of_n) = self.split_at_mut(self.len() - len * N);
1197 // SAFETY: We already panicked for zero, and ensured by construction
1198 // that the length of the subslice is a multiple of N.
1199 let array_slice = unsafe { multiple_of_n.as_chunks_unchecked_mut() };
1200 (remainder, array_slice)
1203 /// Returns an iterator over `N` elements of the slice at a time, starting at the
1204 /// beginning of the slice.
1206 /// The chunks are mutable array references and do not overlap. If `N` does not divide
1207 /// the length of the slice, then the last up to `N-1` elements will be omitted and
1208 /// can be retrieved from the `into_remainder` function of the iterator.
1210 /// This method is the const generic equivalent of [`chunks_exact_mut`].
1214 /// Panics if `N` is 0. This check will most probably get changed to a compile time
1215 /// error before this method gets stabilized.
1220 /// #![feature(array_chunks)]
1221 /// let v = &mut [0, 0, 0, 0, 0];
1222 /// let mut count = 1;
1224 /// for chunk in v.array_chunks_mut() {
1225 /// *chunk = [count; 2];
1228 /// assert_eq!(v, &[1, 1, 2, 2, 0]);
1231 /// [`chunks_exact_mut`]: slice::chunks_exact_mut
1232 #[unstable(feature = "array_chunks", issue = "74985")]
1234 pub fn array_chunks_mut<const N: usize>(&mut self) -> ArrayChunksMut<'_, T, N> {
1236 ArrayChunksMut::new(self)
1239 /// Returns an iterator over overlapping windows of `N` elements of a slice,
1240 /// starting at the beginning of the slice.
1242 /// This is the const generic equivalent of [`windows`].
1244 /// If `N` is greater than the size of the slice, it will return no windows.
1248 /// Panics if `N` is 0. This check will most probably get changed to a compile time
1249 /// error before this method gets stabilized.
1254 /// #![feature(array_windows)]
1255 /// let slice = [0, 1, 2, 3];
1256 /// let mut iter = slice.array_windows();
1257 /// assert_eq!(iter.next().unwrap(), &[0, 1]);
1258 /// assert_eq!(iter.next().unwrap(), &[1, 2]);
1259 /// assert_eq!(iter.next().unwrap(), &[2, 3]);
1260 /// assert!(iter.next().is_none());
1263 /// [`windows`]: slice::windows
1264 #[unstable(feature = "array_windows", issue = "75027")]
1266 pub fn array_windows<const N: usize>(&self) -> ArrayWindows<'_, T, N> {
1268 ArrayWindows::new(self)
1271 /// Returns an iterator over `chunk_size` elements of the slice at a time, starting at the end
1274 /// The chunks are slices and do not overlap. If `chunk_size` does not divide the length of the
1275 /// slice, then the last chunk will not have length `chunk_size`.
1277 /// See [`rchunks_exact`] for a variant of this iterator that returns chunks of always exactly
1278 /// `chunk_size` elements, and [`chunks`] for the same iterator but starting at the beginning
1283 /// Panics if `chunk_size` is 0.
1288 /// let slice = ['l', 'o', 'r', 'e', 'm'];
1289 /// let mut iter = slice.rchunks(2);
1290 /// assert_eq!(iter.next().unwrap(), &['e', 'm']);
1291 /// assert_eq!(iter.next().unwrap(), &['o', 'r']);
1292 /// assert_eq!(iter.next().unwrap(), &['l']);
1293 /// assert!(iter.next().is_none());
1296 /// [`rchunks_exact`]: slice::rchunks_exact
1297 /// [`chunks`]: slice::chunks
1298 #[stable(feature = "rchunks", since = "1.31.0")]
1300 pub fn rchunks(&self, chunk_size: usize) -> RChunks<'_, T> {
1301 assert!(chunk_size != 0);
1302 RChunks::new(self, chunk_size)
1305 /// Returns an iterator over `chunk_size` elements of the slice at a time, starting at the end
1308 /// The chunks are mutable slices, and do not overlap. If `chunk_size` does not divide the
1309 /// length of the slice, then the last chunk will not have length `chunk_size`.
1311 /// See [`rchunks_exact_mut`] for a variant of this iterator that returns chunks of always
1312 /// exactly `chunk_size` elements, and [`chunks_mut`] for the same iterator but starting at the
1313 /// beginning of the slice.
1317 /// Panics if `chunk_size` is 0.
1322 /// let v = &mut [0, 0, 0, 0, 0];
1323 /// let mut count = 1;
1325 /// for chunk in v.rchunks_mut(2) {
1326 /// for elem in chunk.iter_mut() {
1331 /// assert_eq!(v, &[3, 2, 2, 1, 1]);
1334 /// [`rchunks_exact_mut`]: slice::rchunks_exact_mut
1335 /// [`chunks_mut`]: slice::chunks_mut
1336 #[stable(feature = "rchunks", since = "1.31.0")]
1338 pub fn rchunks_mut(&mut self, chunk_size: usize) -> RChunksMut<'_, T> {
1339 assert!(chunk_size != 0);
1340 RChunksMut::new(self, chunk_size)
1343 /// Returns an iterator over `chunk_size` elements of the slice at a time, starting at the
1344 /// end of the slice.
1346 /// The chunks are slices and do not overlap. If `chunk_size` does not divide the length of the
1347 /// slice, then the last up to `chunk_size-1` elements will be omitted and can be retrieved
1348 /// from the `remainder` function of the iterator.
1350 /// Due to each chunk having exactly `chunk_size` elements, the compiler can often optimize the
1351 /// resulting code better than in the case of [`rchunks`].
1353 /// See [`rchunks`] for a variant of this iterator that also returns the remainder as a smaller
1354 /// chunk, and [`chunks_exact`] for the same iterator but starting at the beginning of the
1359 /// Panics if `chunk_size` is 0.
1364 /// let slice = ['l', 'o', 'r', 'e', 'm'];
1365 /// let mut iter = slice.rchunks_exact(2);
1366 /// assert_eq!(iter.next().unwrap(), &['e', 'm']);
1367 /// assert_eq!(iter.next().unwrap(), &['o', 'r']);
1368 /// assert!(iter.next().is_none());
1369 /// assert_eq!(iter.remainder(), &['l']);
1372 /// [`chunks`]: slice::chunks
1373 /// [`rchunks`]: slice::rchunks
1374 /// [`chunks_exact`]: slice::chunks_exact
1375 #[stable(feature = "rchunks", since = "1.31.0")]
1377 pub fn rchunks_exact(&self, chunk_size: usize) -> RChunksExact<'_, T> {
1378 assert!(chunk_size != 0);
1379 RChunksExact::new(self, chunk_size)
1382 /// Returns an iterator over `chunk_size` elements of the slice at a time, starting at the end
1385 /// The chunks are mutable slices, and do not overlap. If `chunk_size` does not divide the
1386 /// length of the slice, then the last up to `chunk_size-1` elements will be omitted and can be
1387 /// retrieved from the `into_remainder` function of the iterator.
1389 /// Due to each chunk having exactly `chunk_size` elements, the compiler can often optimize the
1390 /// resulting code better than in the case of [`chunks_mut`].
1392 /// See [`rchunks_mut`] for a variant of this iterator that also returns the remainder as a
1393 /// smaller chunk, and [`chunks_exact_mut`] for the same iterator but starting at the beginning
1398 /// Panics if `chunk_size` is 0.
1403 /// let v = &mut [0, 0, 0, 0, 0];
1404 /// let mut count = 1;
1406 /// for chunk in v.rchunks_exact_mut(2) {
1407 /// for elem in chunk.iter_mut() {
1412 /// assert_eq!(v, &[0, 2, 2, 1, 1]);
1415 /// [`chunks_mut`]: slice::chunks_mut
1416 /// [`rchunks_mut`]: slice::rchunks_mut
1417 /// [`chunks_exact_mut`]: slice::chunks_exact_mut
1418 #[stable(feature = "rchunks", since = "1.31.0")]
1420 pub fn rchunks_exact_mut(&mut self, chunk_size: usize) -> RChunksExactMut<'_, T> {
1421 assert!(chunk_size != 0);
1422 RChunksExactMut::new(self, chunk_size)
1425 /// Returns an iterator over the slice producing non-overlapping runs
1426 /// of elements using the predicate to separate them.
1428 /// The predicate is called on two elements following themselves,
1429 /// it means the predicate is called on `slice[0]` and `slice[1]`
1430 /// then on `slice[1]` and `slice[2]` and so on.
1435 /// #![feature(slice_group_by)]
1437 /// let slice = &[1, 1, 1, 3, 3, 2, 2, 2];
1439 /// let mut iter = slice.group_by(|a, b| a == b);
1441 /// assert_eq!(iter.next(), Some(&[1, 1, 1][..]));
1442 /// assert_eq!(iter.next(), Some(&[3, 3][..]));
1443 /// assert_eq!(iter.next(), Some(&[2, 2, 2][..]));
1444 /// assert_eq!(iter.next(), None);
1447 /// This method can be used to extract the sorted subslices:
1450 /// #![feature(slice_group_by)]
1452 /// let slice = &[1, 1, 2, 3, 2, 3, 2, 3, 4];
1454 /// let mut iter = slice.group_by(|a, b| a <= b);
1456 /// assert_eq!(iter.next(), Some(&[1, 1, 2, 3][..]));
1457 /// assert_eq!(iter.next(), Some(&[2, 3][..]));
1458 /// assert_eq!(iter.next(), Some(&[2, 3, 4][..]));
1459 /// assert_eq!(iter.next(), None);
1461 #[unstable(feature = "slice_group_by", issue = "80552")]
1463 pub fn group_by<F>(&self, pred: F) -> GroupBy<'_, T, F>
1465 F: FnMut(&T, &T) -> bool,
1467 GroupBy::new(self, pred)
1470 /// Returns an iterator over the slice producing non-overlapping mutable
1471 /// runs of elements using the predicate to separate them.
1473 /// The predicate is called on two elements following themselves,
1474 /// it means the predicate is called on `slice[0]` and `slice[1]`
1475 /// then on `slice[1]` and `slice[2]` and so on.
1480 /// #![feature(slice_group_by)]
1482 /// let slice = &mut [1, 1, 1, 3, 3, 2, 2, 2];
1484 /// let mut iter = slice.group_by_mut(|a, b| a == b);
1486 /// assert_eq!(iter.next(), Some(&mut [1, 1, 1][..]));
1487 /// assert_eq!(iter.next(), Some(&mut [3, 3][..]));
1488 /// assert_eq!(iter.next(), Some(&mut [2, 2, 2][..]));
1489 /// assert_eq!(iter.next(), None);
1492 /// This method can be used to extract the sorted subslices:
1495 /// #![feature(slice_group_by)]
1497 /// let slice = &mut [1, 1, 2, 3, 2, 3, 2, 3, 4];
1499 /// let mut iter = slice.group_by_mut(|a, b| a <= b);
1501 /// assert_eq!(iter.next(), Some(&mut [1, 1, 2, 3][..]));
1502 /// assert_eq!(iter.next(), Some(&mut [2, 3][..]));
1503 /// assert_eq!(iter.next(), Some(&mut [2, 3, 4][..]));
1504 /// assert_eq!(iter.next(), None);
1506 #[unstable(feature = "slice_group_by", issue = "80552")]
1508 pub fn group_by_mut<F>(&mut self, pred: F) -> GroupByMut<'_, T, F>
1510 F: FnMut(&T, &T) -> bool,
1512 GroupByMut::new(self, pred)
1515 /// Divides one slice into two at an index.
1517 /// The first will contain all indices from `[0, mid)` (excluding
1518 /// the index `mid` itself) and the second will contain all
1519 /// indices from `[mid, len)` (excluding the index `len` itself).
1523 /// Panics if `mid > len`.
1528 /// let v = [1, 2, 3, 4, 5, 6];
1531 /// let (left, right) = v.split_at(0);
1532 /// assert_eq!(left, []);
1533 /// assert_eq!(right, [1, 2, 3, 4, 5, 6]);
1537 /// let (left, right) = v.split_at(2);
1538 /// assert_eq!(left, [1, 2]);
1539 /// assert_eq!(right, [3, 4, 5, 6]);
1543 /// let (left, right) = v.split_at(6);
1544 /// assert_eq!(left, [1, 2, 3, 4, 5, 6]);
1545 /// assert_eq!(right, []);
1548 #[stable(feature = "rust1", since = "1.0.0")]
1549 #[rustc_const_unstable(feature = "const_slice_split_at_not_mut", issue = "101158")]
1553 pub const fn split_at(&self, mid: usize) -> (&[T], &[T]) {
1554 assert!(mid <= self.len());
1555 // SAFETY: `[ptr; mid]` and `[mid; len]` are inside `self`, which
1556 // fulfills the requirements of `split_at_unchecked`.
1557 unsafe { self.split_at_unchecked(mid) }
1560 /// Divides one mutable slice into two at an index.
1562 /// The first will contain all indices from `[0, mid)` (excluding
1563 /// the index `mid` itself) and the second will contain all
1564 /// indices from `[mid, len)` (excluding the index `len` itself).
1568 /// Panics if `mid > len`.
1573 /// let mut v = [1, 0, 3, 0, 5, 6];
1574 /// let (left, right) = v.split_at_mut(2);
1575 /// assert_eq!(left, [1, 0]);
1576 /// assert_eq!(right, [3, 0, 5, 6]);
1579 /// assert_eq!(v, [1, 2, 3, 4, 5, 6]);
1581 #[stable(feature = "rust1", since = "1.0.0")]
1585 #[rustc_const_unstable(feature = "const_slice_split_at_mut", issue = "101804")]
1586 pub const fn split_at_mut(&mut self, mid: usize) -> (&mut [T], &mut [T]) {
1587 assert!(mid <= self.len());
1588 // SAFETY: `[ptr; mid]` and `[mid; len]` are inside `self`, which
1589 // fulfills the requirements of `from_raw_parts_mut`.
1590 unsafe { self.split_at_mut_unchecked(mid) }
1593 /// Divides one slice into two at an index, without doing bounds checking.
1595 /// The first will contain all indices from `[0, mid)` (excluding
1596 /// the index `mid` itself) and the second will contain all
1597 /// indices from `[mid, len)` (excluding the index `len` itself).
1599 /// For a safe alternative see [`split_at`].
1603 /// Calling this method with an out-of-bounds index is *[undefined behavior]*
1604 /// even if the resulting reference is not used. The caller has to ensure that
1605 /// `0 <= mid <= self.len()`.
1607 /// [`split_at`]: slice::split_at
1608 /// [undefined behavior]: https://doc.rust-lang.org/reference/behavior-considered-undefined.html
1613 /// #![feature(slice_split_at_unchecked)]
1615 /// let v = [1, 2, 3, 4, 5, 6];
1618 /// let (left, right) = v.split_at_unchecked(0);
1619 /// assert_eq!(left, []);
1620 /// assert_eq!(right, [1, 2, 3, 4, 5, 6]);
1624 /// let (left, right) = v.split_at_unchecked(2);
1625 /// assert_eq!(left, [1, 2]);
1626 /// assert_eq!(right, [3, 4, 5, 6]);
1630 /// let (left, right) = v.split_at_unchecked(6);
1631 /// assert_eq!(left, [1, 2, 3, 4, 5, 6]);
1632 /// assert_eq!(right, []);
1635 #[unstable(feature = "slice_split_at_unchecked", reason = "new API", issue = "76014")]
1636 #[rustc_const_unstable(feature = "slice_split_at_unchecked", issue = "76014")]
1639 pub const unsafe fn split_at_unchecked(&self, mid: usize) -> (&[T], &[T]) {
1640 // HACK: the const function `from_raw_parts` is used to make this
1641 // function const; previously the implementation used
1642 // `(self.get_unchecked(..mid), self.get_unchecked(mid..))`
1644 let len = self.len();
1645 let ptr = self.as_ptr();
1647 // SAFETY: Caller has to check that `0 <= mid <= self.len()`
1648 unsafe { (from_raw_parts(ptr, mid), from_raw_parts(ptr.add(mid), len - mid)) }
1651 /// Divides one mutable slice into two at an index, without doing bounds checking.
1653 /// The first will contain all indices from `[0, mid)` (excluding
1654 /// the index `mid` itself) and the second will contain all
1655 /// indices from `[mid, len)` (excluding the index `len` itself).
1657 /// For a safe alternative see [`split_at_mut`].
1661 /// Calling this method with an out-of-bounds index is *[undefined behavior]*
1662 /// even if the resulting reference is not used. The caller has to ensure that
1663 /// `0 <= mid <= self.len()`.
1665 /// [`split_at_mut`]: slice::split_at_mut
1666 /// [undefined behavior]: https://doc.rust-lang.org/reference/behavior-considered-undefined.html
1671 /// #![feature(slice_split_at_unchecked)]
1673 /// let mut v = [1, 0, 3, 0, 5, 6];
1674 /// // scoped to restrict the lifetime of the borrows
1676 /// let (left, right) = v.split_at_mut_unchecked(2);
1677 /// assert_eq!(left, [1, 0]);
1678 /// assert_eq!(right, [3, 0, 5, 6]);
1682 /// assert_eq!(v, [1, 2, 3, 4, 5, 6]);
1684 #[unstable(feature = "slice_split_at_unchecked", reason = "new API", issue = "76014")]
1685 #[rustc_const_unstable(feature = "const_slice_split_at_mut", issue = "101804")]
1688 pub const unsafe fn split_at_mut_unchecked(&mut self, mid: usize) -> (&mut [T], &mut [T]) {
1689 let len = self.len();
1690 let ptr = self.as_mut_ptr();
1692 // SAFETY: Caller has to check that `0 <= mid <= self.len()`.
1694 // `[ptr; mid]` and `[mid; len]` are not overlapping, so returning a mutable reference
1697 assert_unsafe_precondition!(
1698 "slice::split_at_mut_unchecked requires the index to be within the slice",
1699 (mid: usize, len: usize) => mid <= len
1701 (from_raw_parts_mut(ptr, mid), from_raw_parts_mut(ptr.add(mid), len - mid))
1705 /// Divides one slice into an array and a remainder slice at an index.
1707 /// The array will contain all indices from `[0, N)` (excluding
1708 /// the index `N` itself) and the slice will contain all
1709 /// indices from `[N, len)` (excluding the index `len` itself).
1713 /// Panics if `N > len`.
1718 /// #![feature(split_array)]
1720 /// let v = &[1, 2, 3, 4, 5, 6][..];
1723 /// let (left, right) = v.split_array_ref::<0>();
1724 /// assert_eq!(left, &[]);
1725 /// assert_eq!(right, [1, 2, 3, 4, 5, 6]);
1729 /// let (left, right) = v.split_array_ref::<2>();
1730 /// assert_eq!(left, &[1, 2]);
1731 /// assert_eq!(right, [3, 4, 5, 6]);
1735 /// let (left, right) = v.split_array_ref::<6>();
1736 /// assert_eq!(left, &[1, 2, 3, 4, 5, 6]);
1737 /// assert_eq!(right, []);
1740 #[unstable(feature = "split_array", reason = "new API", issue = "90091")]
1744 pub fn split_array_ref<const N: usize>(&self) -> (&[T; N], &[T]) {
1745 let (a, b) = self.split_at(N);
1746 // SAFETY: a points to [T; N]? Yes it's [T] of length N (checked by split_at)
1747 unsafe { (&*(a.as_ptr() as *const [T; N]), b) }
1750 /// Divides one mutable slice into an array and a remainder slice at an index.
1752 /// The array will contain all indices from `[0, N)` (excluding
1753 /// the index `N` itself) and the slice will contain all
1754 /// indices from `[N, len)` (excluding the index `len` itself).
1758 /// Panics if `N > len`.
1763 /// #![feature(split_array)]
1765 /// let mut v = &mut [1, 0, 3, 0, 5, 6][..];
1766 /// let (left, right) = v.split_array_mut::<2>();
1767 /// assert_eq!(left, &mut [1, 0]);
1768 /// assert_eq!(right, [3, 0, 5, 6]);
1771 /// assert_eq!(v, [1, 2, 3, 4, 5, 6]);
1773 #[unstable(feature = "split_array", reason = "new API", issue = "90091")]
1777 pub fn split_array_mut<const N: usize>(&mut self) -> (&mut [T; N], &mut [T]) {
1778 let (a, b) = self.split_at_mut(N);
1779 // SAFETY: a points to [T; N]? Yes it's [T] of length N (checked by split_at_mut)
1780 unsafe { (&mut *(a.as_mut_ptr() as *mut [T; N]), b) }
1783 /// Divides one slice into an array and a remainder slice at an index from
1786 /// The slice will contain all indices from `[0, len - N)` (excluding
1787 /// the index `len - N` itself) and the array will contain all
1788 /// indices from `[len - N, len)` (excluding the index `len` itself).
1792 /// Panics if `N > len`.
1797 /// #![feature(split_array)]
1799 /// let v = &[1, 2, 3, 4, 5, 6][..];
1802 /// let (left, right) = v.rsplit_array_ref::<0>();
1803 /// assert_eq!(left, [1, 2, 3, 4, 5, 6]);
1804 /// assert_eq!(right, &[]);
1808 /// let (left, right) = v.rsplit_array_ref::<2>();
1809 /// assert_eq!(left, [1, 2, 3, 4]);
1810 /// assert_eq!(right, &[5, 6]);
1814 /// let (left, right) = v.rsplit_array_ref::<6>();
1815 /// assert_eq!(left, []);
1816 /// assert_eq!(right, &[1, 2, 3, 4, 5, 6]);
1819 #[unstable(feature = "split_array", reason = "new API", issue = "90091")]
1822 pub fn rsplit_array_ref<const N: usize>(&self) -> (&[T], &[T; N]) {
1823 assert!(N <= self.len());
1824 let (a, b) = self.split_at(self.len() - N);
1825 // SAFETY: b points to [T; N]? Yes it's [T] of length N (checked by split_at)
1826 unsafe { (a, &*(b.as_ptr() as *const [T; N])) }
1829 /// Divides one mutable slice into an array and a remainder slice at an
1830 /// index from the end.
1832 /// The slice will contain all indices from `[0, len - N)` (excluding
1833 /// the index `N` itself) and the array will contain all
1834 /// indices from `[len - N, len)` (excluding the index `len` itself).
1838 /// Panics if `N > len`.
1843 /// #![feature(split_array)]
1845 /// let mut v = &mut [1, 0, 3, 0, 5, 6][..];
1846 /// let (left, right) = v.rsplit_array_mut::<4>();
1847 /// assert_eq!(left, [1, 0]);
1848 /// assert_eq!(right, &mut [3, 0, 5, 6]);
1851 /// assert_eq!(v, [1, 2, 3, 4, 5, 6]);
1853 #[unstable(feature = "split_array", reason = "new API", issue = "90091")]
1856 pub fn rsplit_array_mut<const N: usize>(&mut self) -> (&mut [T], &mut [T; N]) {
1857 assert!(N <= self.len());
1858 let (a, b) = self.split_at_mut(self.len() - N);
1859 // SAFETY: b points to [T; N]? Yes it's [T] of length N (checked by split_at_mut)
1860 unsafe { (a, &mut *(b.as_mut_ptr() as *mut [T; N])) }
1863 /// Returns an iterator over subslices separated by elements that match
1864 /// `pred`. The matched element is not contained in the subslices.
1869 /// let slice = [10, 40, 33, 20];
1870 /// let mut iter = slice.split(|num| num % 3 == 0);
1872 /// assert_eq!(iter.next().unwrap(), &[10, 40]);
1873 /// assert_eq!(iter.next().unwrap(), &[20]);
1874 /// assert!(iter.next().is_none());
1877 /// If the first element is matched, an empty slice will be the first item
1878 /// returned by the iterator. Similarly, if the last element in the slice
1879 /// is matched, an empty slice will be the last item returned by the
1883 /// let slice = [10, 40, 33];
1884 /// let mut iter = slice.split(|num| num % 3 == 0);
1886 /// assert_eq!(iter.next().unwrap(), &[10, 40]);
1887 /// assert_eq!(iter.next().unwrap(), &[]);
1888 /// assert!(iter.next().is_none());
1891 /// If two matched elements are directly adjacent, an empty slice will be
1892 /// present between them:
1895 /// let slice = [10, 6, 33, 20];
1896 /// let mut iter = slice.split(|num| num % 3 == 0);
1898 /// assert_eq!(iter.next().unwrap(), &[10]);
1899 /// assert_eq!(iter.next().unwrap(), &[]);
1900 /// assert_eq!(iter.next().unwrap(), &[20]);
1901 /// assert!(iter.next().is_none());
1903 #[stable(feature = "rust1", since = "1.0.0")]
1905 pub fn split<F>(&self, pred: F) -> Split<'_, T, F>
1907 F: FnMut(&T) -> bool,
1909 Split::new(self, pred)
1912 /// Returns an iterator over mutable subslices separated by elements that
1913 /// match `pred`. The matched element is not contained in the subslices.
1918 /// let mut v = [10, 40, 30, 20, 60, 50];
1920 /// for group in v.split_mut(|num| *num % 3 == 0) {
1923 /// assert_eq!(v, [1, 40, 30, 1, 60, 1]);
1925 #[stable(feature = "rust1", since = "1.0.0")]
1927 pub fn split_mut<F>(&mut self, pred: F) -> SplitMut<'_, T, F>
1929 F: FnMut(&T) -> bool,
1931 SplitMut::new(self, pred)
1934 /// Returns an iterator over subslices separated by elements that match
1935 /// `pred`. The matched element is contained in the end of the previous
1936 /// subslice as a terminator.
1941 /// let slice = [10, 40, 33, 20];
1942 /// let mut iter = slice.split_inclusive(|num| num % 3 == 0);
1944 /// assert_eq!(iter.next().unwrap(), &[10, 40, 33]);
1945 /// assert_eq!(iter.next().unwrap(), &[20]);
1946 /// assert!(iter.next().is_none());
1949 /// If the last element of the slice is matched,
1950 /// that element will be considered the terminator of the preceding slice.
1951 /// That slice will be the last item returned by the iterator.
1954 /// let slice = [3, 10, 40, 33];
1955 /// let mut iter = slice.split_inclusive(|num| num % 3 == 0);
1957 /// assert_eq!(iter.next().unwrap(), &[3]);
1958 /// assert_eq!(iter.next().unwrap(), &[10, 40, 33]);
1959 /// assert!(iter.next().is_none());
1961 #[stable(feature = "split_inclusive", since = "1.51.0")]
1963 pub fn split_inclusive<F>(&self, pred: F) -> SplitInclusive<'_, T, F>
1965 F: FnMut(&T) -> bool,
1967 SplitInclusive::new(self, pred)
1970 /// Returns an iterator over mutable subslices separated by elements that
1971 /// match `pred`. The matched element is contained in the previous
1972 /// subslice as a terminator.
1977 /// let mut v = [10, 40, 30, 20, 60, 50];
1979 /// for group in v.split_inclusive_mut(|num| *num % 3 == 0) {
1980 /// let terminator_idx = group.len()-1;
1981 /// group[terminator_idx] = 1;
1983 /// assert_eq!(v, [10, 40, 1, 20, 1, 1]);
1985 #[stable(feature = "split_inclusive", since = "1.51.0")]
1987 pub fn split_inclusive_mut<F>(&mut self, pred: F) -> SplitInclusiveMut<'_, T, F>
1989 F: FnMut(&T) -> bool,
1991 SplitInclusiveMut::new(self, pred)
1994 /// Returns an iterator over subslices separated by elements that match
1995 /// `pred`, starting at the end of the slice and working backwards.
1996 /// The matched element is not contained in the subslices.
2001 /// let slice = [11, 22, 33, 0, 44, 55];
2002 /// let mut iter = slice.rsplit(|num| *num == 0);
2004 /// assert_eq!(iter.next().unwrap(), &[44, 55]);
2005 /// assert_eq!(iter.next().unwrap(), &[11, 22, 33]);
2006 /// assert_eq!(iter.next(), None);
2009 /// As with `split()`, if the first or last element is matched, an empty
2010 /// slice will be the first (or last) item returned by the iterator.
2013 /// let v = &[0, 1, 1, 2, 3, 5, 8];
2014 /// let mut it = v.rsplit(|n| *n % 2 == 0);
2015 /// assert_eq!(it.next().unwrap(), &[]);
2016 /// assert_eq!(it.next().unwrap(), &[3, 5]);
2017 /// assert_eq!(it.next().unwrap(), &[1, 1]);
2018 /// assert_eq!(it.next().unwrap(), &[]);
2019 /// assert_eq!(it.next(), None);
2021 #[stable(feature = "slice_rsplit", since = "1.27.0")]
2023 pub fn rsplit<F>(&self, pred: F) -> RSplit<'_, T, F>
2025 F: FnMut(&T) -> bool,
2027 RSplit::new(self, pred)
2030 /// Returns an iterator over mutable subslices separated by elements that
2031 /// match `pred`, starting at the end of the slice and working
2032 /// backwards. The matched element is not contained in the subslices.
2037 /// let mut v = [100, 400, 300, 200, 600, 500];
2039 /// let mut count = 0;
2040 /// for group in v.rsplit_mut(|num| *num % 3 == 0) {
2042 /// group[0] = count;
2044 /// assert_eq!(v, [3, 400, 300, 2, 600, 1]);
2047 #[stable(feature = "slice_rsplit", since = "1.27.0")]
2049 pub fn rsplit_mut<F>(&mut self, pred: F) -> RSplitMut<'_, T, F>
2051 F: FnMut(&T) -> bool,
2053 RSplitMut::new(self, pred)
2056 /// Returns an iterator over subslices separated by elements that match
2057 /// `pred`, limited to returning at most `n` items. The matched element is
2058 /// not contained in the subslices.
2060 /// The last element returned, if any, will contain the remainder of the
2065 /// Print the slice split once by numbers divisible by 3 (i.e., `[10, 40]`,
2066 /// `[20, 60, 50]`):
2069 /// let v = [10, 40, 30, 20, 60, 50];
2071 /// for group in v.splitn(2, |num| *num % 3 == 0) {
2072 /// println!("{group:?}");
2075 #[stable(feature = "rust1", since = "1.0.0")]
2077 pub fn splitn<F>(&self, n: usize, pred: F) -> SplitN<'_, T, F>
2079 F: FnMut(&T) -> bool,
2081 SplitN::new(self.split(pred), n)
2084 /// Returns an iterator over mutable subslices separated by elements that match
2085 /// `pred`, limited to returning at most `n` items. The matched element is
2086 /// not contained in the subslices.
2088 /// The last element returned, if any, will contain the remainder of the
2094 /// let mut v = [10, 40, 30, 20, 60, 50];
2096 /// for group in v.splitn_mut(2, |num| *num % 3 == 0) {
2099 /// assert_eq!(v, [1, 40, 30, 1, 60, 50]);
2101 #[stable(feature = "rust1", since = "1.0.0")]
2103 pub fn splitn_mut<F>(&mut self, n: usize, pred: F) -> SplitNMut<'_, T, F>
2105 F: FnMut(&T) -> bool,
2107 SplitNMut::new(self.split_mut(pred), n)
2110 /// Returns an iterator over subslices separated by elements that match
2111 /// `pred` limited to returning at most `n` items. This starts at the end of
2112 /// the slice and works backwards. The matched element is not contained in
2115 /// The last element returned, if any, will contain the remainder of the
2120 /// Print the slice split once, starting from the end, by numbers divisible
2121 /// by 3 (i.e., `[50]`, `[10, 40, 30, 20]`):
2124 /// let v = [10, 40, 30, 20, 60, 50];
2126 /// for group in v.rsplitn(2, |num| *num % 3 == 0) {
2127 /// println!("{group:?}");
2130 #[stable(feature = "rust1", since = "1.0.0")]
2132 pub fn rsplitn<F>(&self, n: usize, pred: F) -> RSplitN<'_, T, F>
2134 F: FnMut(&T) -> bool,
2136 RSplitN::new(self.rsplit(pred), n)
2139 /// Returns an iterator over subslices separated by elements that match
2140 /// `pred` limited to returning at most `n` items. This starts at the end of
2141 /// the slice and works backwards. The matched element is not contained in
2144 /// The last element returned, if any, will contain the remainder of the
2150 /// let mut s = [10, 40, 30, 20, 60, 50];
2152 /// for group in s.rsplitn_mut(2, |num| *num % 3 == 0) {
2155 /// assert_eq!(s, [1, 40, 30, 20, 60, 1]);
2157 #[stable(feature = "rust1", since = "1.0.0")]
2159 pub fn rsplitn_mut<F>(&mut self, n: usize, pred: F) -> RSplitNMut<'_, T, F>
2161 F: FnMut(&T) -> bool,
2163 RSplitNMut::new(self.rsplit_mut(pred), n)
2166 /// Returns `true` if the slice contains an element with the given value.
2168 /// This operation is *O*(*n*).
2170 /// Note that if you have a sorted slice, [`binary_search`] may be faster.
2172 /// [`binary_search`]: slice::binary_search
2177 /// let v = [10, 40, 30];
2178 /// assert!(v.contains(&30));
2179 /// assert!(!v.contains(&50));
2182 /// If you do not have a `&T`, but some other value that you can compare
2183 /// with one (for example, `String` implements `PartialEq<str>`), you can
2184 /// use `iter().any`:
2187 /// let v = [String::from("hello"), String::from("world")]; // slice of `String`
2188 /// assert!(v.iter().any(|e| e == "hello")); // search with `&str`
2189 /// assert!(!v.iter().any(|e| e == "hi"));
2191 #[stable(feature = "rust1", since = "1.0.0")]
2194 pub fn contains(&self, x: &T) -> bool
2198 cmp::SliceContains::slice_contains(x, self)
2201 /// Returns `true` if `needle` is a prefix of the slice.
2206 /// let v = [10, 40, 30];
2207 /// assert!(v.starts_with(&[10]));
2208 /// assert!(v.starts_with(&[10, 40]));
2209 /// assert!(!v.starts_with(&[50]));
2210 /// assert!(!v.starts_with(&[10, 50]));
2213 /// Always returns `true` if `needle` is an empty slice:
2216 /// let v = &[10, 40, 30];
2217 /// assert!(v.starts_with(&[]));
2218 /// let v: &[u8] = &[];
2219 /// assert!(v.starts_with(&[]));
2221 #[stable(feature = "rust1", since = "1.0.0")]
2223 pub fn starts_with(&self, needle: &[T]) -> bool
2227 let n = needle.len();
2228 self.len() >= n && needle == &self[..n]
2231 /// Returns `true` if `needle` is a suffix of the slice.
2236 /// let v = [10, 40, 30];
2237 /// assert!(v.ends_with(&[30]));
2238 /// assert!(v.ends_with(&[40, 30]));
2239 /// assert!(!v.ends_with(&[50]));
2240 /// assert!(!v.ends_with(&[50, 30]));
2243 /// Always returns `true` if `needle` is an empty slice:
2246 /// let v = &[10, 40, 30];
2247 /// assert!(v.ends_with(&[]));
2248 /// let v: &[u8] = &[];
2249 /// assert!(v.ends_with(&[]));
2251 #[stable(feature = "rust1", since = "1.0.0")]
2253 pub fn ends_with(&self, needle: &[T]) -> bool
2257 let (m, n) = (self.len(), needle.len());
2258 m >= n && needle == &self[m - n..]
2261 /// Returns a subslice with the prefix removed.
2263 /// If the slice starts with `prefix`, returns the subslice after the prefix, wrapped in `Some`.
2264 /// If `prefix` is empty, simply returns the original slice.
2266 /// If the slice does not start with `prefix`, returns `None`.
2271 /// let v = &[10, 40, 30];
2272 /// assert_eq!(v.strip_prefix(&[10]), Some(&[40, 30][..]));
2273 /// assert_eq!(v.strip_prefix(&[10, 40]), Some(&[30][..]));
2274 /// assert_eq!(v.strip_prefix(&[50]), None);
2275 /// assert_eq!(v.strip_prefix(&[10, 50]), None);
2277 /// let prefix : &str = "he";
2278 /// assert_eq!(b"hello".strip_prefix(prefix.as_bytes()),
2279 /// Some(b"llo".as_ref()));
2281 #[must_use = "returns the subslice without modifying the original"]
2282 #[stable(feature = "slice_strip", since = "1.51.0")]
2283 pub fn strip_prefix<P: SlicePattern<Item = T> + ?Sized>(&self, prefix: &P) -> Option<&[T]>
2287 // This function will need rewriting if and when SlicePattern becomes more sophisticated.
2288 let prefix = prefix.as_slice();
2289 let n = prefix.len();
2290 if n <= self.len() {
2291 let (head, tail) = self.split_at(n);
2299 /// Returns a subslice with the suffix removed.
2301 /// If the slice ends with `suffix`, returns the subslice before the suffix, wrapped in `Some`.
2302 /// If `suffix` is empty, simply returns the original slice.
2304 /// If the slice does not end with `suffix`, returns `None`.
2309 /// let v = &[10, 40, 30];
2310 /// assert_eq!(v.strip_suffix(&[30]), Some(&[10, 40][..]));
2311 /// assert_eq!(v.strip_suffix(&[40, 30]), Some(&[10][..]));
2312 /// assert_eq!(v.strip_suffix(&[50]), None);
2313 /// assert_eq!(v.strip_suffix(&[50, 30]), None);
2315 #[must_use = "returns the subslice without modifying the original"]
2316 #[stable(feature = "slice_strip", since = "1.51.0")]
2317 pub fn strip_suffix<P: SlicePattern<Item = T> + ?Sized>(&self, suffix: &P) -> Option<&[T]>
2321 // This function will need rewriting if and when SlicePattern becomes more sophisticated.
2322 let suffix = suffix.as_slice();
2323 let (len, n) = (self.len(), suffix.len());
2325 let (head, tail) = self.split_at(len - n);
2333 /// Binary searches this slice for a given element.
2334 /// This behaves similarly to [`contains`] if this slice is sorted.
2336 /// If the value is found then [`Result::Ok`] is returned, containing the
2337 /// index of the matching element. If there are multiple matches, then any
2338 /// one of the matches could be returned. The index is chosen
2339 /// deterministically, but is subject to change in future versions of Rust.
2340 /// If the value is not found then [`Result::Err`] is returned, containing
2341 /// the index where a matching element could be inserted while maintaining
2344 /// See also [`binary_search_by`], [`binary_search_by_key`], and [`partition_point`].
2346 /// [`contains`]: slice::contains
2347 /// [`binary_search_by`]: slice::binary_search_by
2348 /// [`binary_search_by_key`]: slice::binary_search_by_key
2349 /// [`partition_point`]: slice::partition_point
2353 /// Looks up a series of four elements. The first is found, with a
2354 /// uniquely determined position; the second and third are not
2355 /// found; the fourth could match any position in `[1, 4]`.
2358 /// let s = [0, 1, 1, 1, 1, 2, 3, 5, 8, 13, 21, 34, 55];
2360 /// assert_eq!(s.binary_search(&13), Ok(9));
2361 /// assert_eq!(s.binary_search(&4), Err(7));
2362 /// assert_eq!(s.binary_search(&100), Err(13));
2363 /// let r = s.binary_search(&1);
2364 /// assert!(match r { Ok(1..=4) => true, _ => false, });
2367 /// If you want to find that whole *range* of matching items, rather than
2368 /// an arbitrary matching one, that can be done using [`partition_point`]:
2370 /// let s = [0, 1, 1, 1, 1, 2, 3, 5, 8, 13, 21, 34, 55];
2372 /// let low = s.partition_point(|x| x < &1);
2373 /// assert_eq!(low, 1);
2374 /// let high = s.partition_point(|x| x <= &1);
2375 /// assert_eq!(high, 5);
2376 /// let r = s.binary_search(&1);
2377 /// assert!((low..high).contains(&r.unwrap()));
2379 /// assert!(s[..low].iter().all(|&x| x < 1));
2380 /// assert!(s[low..high].iter().all(|&x| x == 1));
2381 /// assert!(s[high..].iter().all(|&x| x > 1));
2383 /// // For something not found, the "range" of equal items is empty
2384 /// assert_eq!(s.partition_point(|x| x < &11), 9);
2385 /// assert_eq!(s.partition_point(|x| x <= &11), 9);
2386 /// assert_eq!(s.binary_search(&11), Err(9));
2389 /// If you want to insert an item to a sorted vector, while maintaining
2390 /// sort order, consider using [`partition_point`]:
2393 /// let mut s = vec![0, 1, 1, 1, 1, 2, 3, 5, 8, 13, 21, 34, 55];
2395 /// let idx = s.partition_point(|&x| x < num);
2396 /// // The above is equivalent to `let idx = s.binary_search(&num).unwrap_or_else(|x| x);`
2397 /// s.insert(idx, num);
2398 /// assert_eq!(s, [0, 1, 1, 1, 1, 2, 3, 5, 8, 13, 21, 34, 42, 55]);
2400 #[stable(feature = "rust1", since = "1.0.0")]
2401 pub fn binary_search(&self, x: &T) -> Result<usize, usize>
2405 self.binary_search_by(|p| p.cmp(x))
2408 /// Binary searches this slice with a comparator function.
2409 /// This behaves similarly to [`contains`] if this slice is sorted.
2411 /// The comparator function should implement an order consistent
2412 /// with the sort order of the underlying slice, returning an
2413 /// order code that indicates whether its argument is `Less`,
2414 /// `Equal` or `Greater` the desired target.
2416 /// If the value is found then [`Result::Ok`] is returned, containing the
2417 /// index of the matching element. If there are multiple matches, then any
2418 /// one of the matches could be returned. The index is chosen
2419 /// deterministically, but is subject to change in future versions of Rust.
2420 /// If the value is not found then [`Result::Err`] is returned, containing
2421 /// the index where a matching element could be inserted while maintaining
2424 /// See also [`binary_search`], [`binary_search_by_key`], and [`partition_point`].
2426 /// [`contains`]: slice::contains
2427 /// [`binary_search`]: slice::binary_search
2428 /// [`binary_search_by_key`]: slice::binary_search_by_key
2429 /// [`partition_point`]: slice::partition_point
2433 /// Looks up a series of four elements. The first is found, with a
2434 /// uniquely determined position; the second and third are not
2435 /// found; the fourth could match any position in `[1, 4]`.
2438 /// let s = [0, 1, 1, 1, 1, 2, 3, 5, 8, 13, 21, 34, 55];
2441 /// assert_eq!(s.binary_search_by(|probe| probe.cmp(&seek)), Ok(9));
2443 /// assert_eq!(s.binary_search_by(|probe| probe.cmp(&seek)), Err(7));
2445 /// assert_eq!(s.binary_search_by(|probe| probe.cmp(&seek)), Err(13));
2447 /// let r = s.binary_search_by(|probe| probe.cmp(&seek));
2448 /// assert!(match r { Ok(1..=4) => true, _ => false, });
2450 #[stable(feature = "rust1", since = "1.0.0")]
2452 pub fn binary_search_by<'a, F>(&'a self, mut f: F) -> Result<usize, usize>
2454 F: FnMut(&'a T) -> Ordering,
2457 // - 0 <= left <= left + size = right <= self.len()
2458 // - f returns Less for everything in self[..left]
2459 // - f returns Greater for everything in self[right..]
2460 let mut size = self.len();
2462 let mut right = size;
2463 while left < right {
2464 let mid = left + size / 2;
2466 // SAFETY: the while condition means `size` is strictly positive, so
2467 // `size/2 < size`. Thus `left + size/2 < left + size`, which
2468 // coupled with the `left + size <= self.len()` invariant means
2469 // we have `left + size/2 < self.len()`, and this is in-bounds.
2470 let cmp = f(unsafe { self.get_unchecked(mid) });
2472 // The reason why we use if/else control flow rather than match
2473 // is because match reorders comparison operations, which is perf sensitive.
2474 // This is x86 asm for u8: https://rust.godbolt.org/z/8Y8Pra.
2477 } else if cmp == Greater {
2480 // SAFETY: same as the `get_unchecked` above
2481 unsafe { crate::intrinsics::assume(mid < self.len()) };
2485 size = right - left;
2488 // SAFETY: directly true from the overall invariant.
2489 // Note that this is `<=`, unlike the assume in the `Ok` path.
2490 unsafe { crate::intrinsics::assume(left <= self.len()) };
2494 /// Binary searches this slice with a key extraction function.
2495 /// This behaves similarly to [`contains`] if this slice is sorted.
2497 /// Assumes that the slice is sorted by the key, for instance with
2498 /// [`sort_by_key`] using the same key extraction function.
2500 /// If the value is found then [`Result::Ok`] is returned, containing the
2501 /// index of the matching element. If there are multiple matches, then any
2502 /// one of the matches could be returned. The index is chosen
2503 /// deterministically, but is subject to change in future versions of Rust.
2504 /// If the value is not found then [`Result::Err`] is returned, containing
2505 /// the index where a matching element could be inserted while maintaining
2508 /// See also [`binary_search`], [`binary_search_by`], and [`partition_point`].
2510 /// [`contains`]: slice::contains
2511 /// [`sort_by_key`]: slice::sort_by_key
2512 /// [`binary_search`]: slice::binary_search
2513 /// [`binary_search_by`]: slice::binary_search_by
2514 /// [`partition_point`]: slice::partition_point
2518 /// Looks up a series of four elements in a slice of pairs sorted by
2519 /// their second elements. The first is found, with a uniquely
2520 /// determined position; the second and third are not found; the
2521 /// fourth could match any position in `[1, 4]`.
2524 /// let s = [(0, 0), (2, 1), (4, 1), (5, 1), (3, 1),
2525 /// (1, 2), (2, 3), (4, 5), (5, 8), (3, 13),
2526 /// (1, 21), (2, 34), (4, 55)];
2528 /// assert_eq!(s.binary_search_by_key(&13, |&(a, b)| b), Ok(9));
2529 /// assert_eq!(s.binary_search_by_key(&4, |&(a, b)| b), Err(7));
2530 /// assert_eq!(s.binary_search_by_key(&100, |&(a, b)| b), Err(13));
2531 /// let r = s.binary_search_by_key(&1, |&(a, b)| b);
2532 /// assert!(match r { Ok(1..=4) => true, _ => false, });
2534 // Lint rustdoc::broken_intra_doc_links is allowed as `slice::sort_by_key` is
2535 // in crate `alloc`, and as such doesn't exists yet when building `core`: #74481.
2536 // This breaks links when slice is displayed in core, but changing it to use relative links
2537 // would break when the item is re-exported. So allow the core links to be broken for now.
2538 #[allow(rustdoc::broken_intra_doc_links)]
2539 #[stable(feature = "slice_binary_search_by_key", since = "1.10.0")]
2541 pub fn binary_search_by_key<'a, B, F>(&'a self, b: &B, mut f: F) -> Result<usize, usize>
2543 F: FnMut(&'a T) -> B,
2546 self.binary_search_by(|k| f(k).cmp(b))
2549 /// Sorts the slice, but might not preserve the order of equal elements.
2551 /// This sort is unstable (i.e., may reorder equal elements), in-place
2552 /// (i.e., does not allocate), and *O*(*n* \* log(*n*)) worst-case.
2554 /// # Current implementation
2556 /// The current algorithm is based on [pattern-defeating quicksort][pdqsort] by Orson Peters,
2557 /// which combines the fast average case of randomized quicksort with the fast worst case of
2558 /// heapsort, while achieving linear time on slices with certain patterns. It uses some
2559 /// randomization to avoid degenerate cases, but with a fixed seed to always provide
2560 /// deterministic behavior.
2562 /// It is typically faster than stable sorting, except in a few special cases, e.g., when the
2563 /// slice consists of several concatenated sorted sequences.
2568 /// let mut v = [-5, 4, 1, -3, 2];
2570 /// v.sort_unstable();
2571 /// assert!(v == [-5, -3, 1, 2, 4]);
2574 /// [pdqsort]: https://github.com/orlp/pdqsort
2575 #[stable(feature = "sort_unstable", since = "1.20.0")]
2577 pub fn sort_unstable(&mut self)
2581 sort::quicksort(self, T::lt);
2584 /// Sorts the slice with a comparator function, but might not preserve the order of equal
2587 /// This sort is unstable (i.e., may reorder equal elements), in-place
2588 /// (i.e., does not allocate), and *O*(*n* \* log(*n*)) worst-case.
2590 /// The comparator function must define a total ordering for the elements in the slice. If
2591 /// the ordering is not total, the order of the elements is unspecified. An order is a
2592 /// total order if it is (for all `a`, `b` and `c`):
2594 /// * total and antisymmetric: exactly one of `a < b`, `a == b` or `a > b` is true, and
2595 /// * transitive, `a < b` and `b < c` implies `a < c`. The same must hold for both `==` and `>`.
2597 /// For example, while [`f64`] doesn't implement [`Ord`] because `NaN != NaN`, we can use
2598 /// `partial_cmp` as our sort function when we know the slice doesn't contain a `NaN`.
2601 /// let mut floats = [5f64, 4.0, 1.0, 3.0, 2.0];
2602 /// floats.sort_unstable_by(|a, b| a.partial_cmp(b).unwrap());
2603 /// assert_eq!(floats, [1.0, 2.0, 3.0, 4.0, 5.0]);
2606 /// # Current implementation
2608 /// The current algorithm is based on [pattern-defeating quicksort][pdqsort] by Orson Peters,
2609 /// which combines the fast average case of randomized quicksort with the fast worst case of
2610 /// heapsort, while achieving linear time on slices with certain patterns. It uses some
2611 /// randomization to avoid degenerate cases, but with a fixed seed to always provide
2612 /// deterministic behavior.
2614 /// It is typically faster than stable sorting, except in a few special cases, e.g., when the
2615 /// slice consists of several concatenated sorted sequences.
2620 /// let mut v = [5, 4, 1, 3, 2];
2621 /// v.sort_unstable_by(|a, b| a.cmp(b));
2622 /// assert!(v == [1, 2, 3, 4, 5]);
2624 /// // reverse sorting
2625 /// v.sort_unstable_by(|a, b| b.cmp(a));
2626 /// assert!(v == [5, 4, 3, 2, 1]);
2629 /// [pdqsort]: https://github.com/orlp/pdqsort
2630 #[stable(feature = "sort_unstable", since = "1.20.0")]
2632 pub fn sort_unstable_by<F>(&mut self, mut compare: F)
2634 F: FnMut(&T, &T) -> Ordering,
2636 sort::quicksort(self, |a, b| compare(a, b) == Ordering::Less);
2639 /// Sorts the slice with a key extraction function, but might not preserve the order of equal
2642 /// This sort is unstable (i.e., may reorder equal elements), in-place
2643 /// (i.e., does not allocate), and *O*(m \* *n* \* log(*n*)) worst-case, where the key function is
2646 /// # Current implementation
2648 /// The current algorithm is based on [pattern-defeating quicksort][pdqsort] by Orson Peters,
2649 /// which combines the fast average case of randomized quicksort with the fast worst case of
2650 /// heapsort, while achieving linear time on slices with certain patterns. It uses some
2651 /// randomization to avoid degenerate cases, but with a fixed seed to always provide
2652 /// deterministic behavior.
2654 /// Due to its key calling strategy, [`sort_unstable_by_key`](#method.sort_unstable_by_key)
2655 /// is likely to be slower than [`sort_by_cached_key`](#method.sort_by_cached_key) in
2656 /// cases where the key function is expensive.
2661 /// let mut v = [-5i32, 4, 1, -3, 2];
2663 /// v.sort_unstable_by_key(|k| k.abs());
2664 /// assert!(v == [1, 2, -3, 4, -5]);
2667 /// [pdqsort]: https://github.com/orlp/pdqsort
2668 #[stable(feature = "sort_unstable", since = "1.20.0")]
2670 pub fn sort_unstable_by_key<K, F>(&mut self, mut f: F)
2675 sort::quicksort(self, |a, b| f(a).lt(&f(b)));
2678 /// Reorder the slice such that the element at `index` is at its final sorted position.
2680 /// This reordering has the additional property that any value at position `i < index` will be
2681 /// less than or equal to any value at a position `j > index`. Additionally, this reordering is
2682 /// unstable (i.e. any number of equal elements may end up at position `index`), in-place
2683 /// (i.e. does not allocate), and *O*(*n*) worst-case. This function is also/ known as "kth
2684 /// element" in other libraries. It returns a triplet of the following from the reordered slice:
2685 /// the subslice prior to `index`, the element at `index`, and the subslice after `index`;
2686 /// accordingly, the values in those two subslices will respectively all be less-than-or-equal-to
2687 /// and greater-than-or-equal-to the value of the element at `index`.
2689 /// # Current implementation
2691 /// The current algorithm is based on the quickselect portion of the same quicksort algorithm
2692 /// used for [`sort_unstable`].
2694 /// [`sort_unstable`]: slice::sort_unstable
2698 /// Panics when `index >= len()`, meaning it always panics on empty slices.
2703 /// let mut v = [-5i32, 4, 1, -3, 2];
2705 /// // Find the median
2706 /// v.select_nth_unstable(2);
2708 /// // We are only guaranteed the slice will be one of the following, based on the way we sort
2709 /// // about the specified index.
2710 /// assert!(v == [-3, -5, 1, 2, 4] ||
2711 /// v == [-5, -3, 1, 2, 4] ||
2712 /// v == [-3, -5, 1, 4, 2] ||
2713 /// v == [-5, -3, 1, 4, 2]);
2715 #[stable(feature = "slice_select_nth_unstable", since = "1.49.0")]
2717 pub fn select_nth_unstable(&mut self, index: usize) -> (&mut [T], &mut T, &mut [T])
2721 sort::partition_at_index(self, index, T::lt)
2724 /// Reorder the slice with a comparator function such that the element at `index` is at its
2725 /// final sorted position.
2727 /// This reordering has the additional property that any value at position `i < index` will be
2728 /// less than or equal to any value at a position `j > index` using the comparator function.
2729 /// Additionally, this reordering is unstable (i.e. any number of equal elements may end up at
2730 /// position `index`), in-place (i.e. does not allocate), and *O*(*n*) worst-case. This function
2731 /// is also known as "kth element" in other libraries. It returns a triplet of the following from
2732 /// the slice reordered according to the provided comparator function: the subslice prior to
2733 /// `index`, the element at `index`, and the subslice after `index`; accordingly, the values in
2734 /// those two subslices will respectively all be less-than-or-equal-to and greater-than-or-equal-to
2735 /// the value of the element at `index`.
2737 /// # Current implementation
2739 /// The current algorithm is based on the quickselect portion of the same quicksort algorithm
2740 /// used for [`sort_unstable`].
2742 /// [`sort_unstable`]: slice::sort_unstable
2746 /// Panics when `index >= len()`, meaning it always panics on empty slices.
2751 /// let mut v = [-5i32, 4, 1, -3, 2];
2753 /// // Find the median as if the slice were sorted in descending order.
2754 /// v.select_nth_unstable_by(2, |a, b| b.cmp(a));
2756 /// // We are only guaranteed the slice will be one of the following, based on the way we sort
2757 /// // about the specified index.
2758 /// assert!(v == [2, 4, 1, -5, -3] ||
2759 /// v == [2, 4, 1, -3, -5] ||
2760 /// v == [4, 2, 1, -5, -3] ||
2761 /// v == [4, 2, 1, -3, -5]);
2763 #[stable(feature = "slice_select_nth_unstable", since = "1.49.0")]
2765 pub fn select_nth_unstable_by<F>(
2769 ) -> (&mut [T], &mut T, &mut [T])
2771 F: FnMut(&T, &T) -> Ordering,
2773 sort::partition_at_index(self, index, |a: &T, b: &T| compare(a, b) == Less)
2776 /// Reorder the slice with a key extraction function such that the element at `index` is at its
2777 /// final sorted position.
2779 /// This reordering has the additional property that any value at position `i < index` will be
2780 /// less than or equal to any value at a position `j > index` using the key extraction function.
2781 /// Additionally, this reordering is unstable (i.e. any number of equal elements may end up at
2782 /// position `index`), in-place (i.e. does not allocate), and *O*(*n*) worst-case. This function
2783 /// is also known as "kth element" in other libraries. It returns a triplet of the following from
2784 /// the slice reordered according to the provided key extraction function: the subslice prior to
2785 /// `index`, the element at `index`, and the subslice after `index`; accordingly, the values in
2786 /// those two subslices will respectively all be less-than-or-equal-to and greater-than-or-equal-to
2787 /// the value of the element at `index`.
2789 /// # Current implementation
2791 /// The current algorithm is based on the quickselect portion of the same quicksort algorithm
2792 /// used for [`sort_unstable`].
2794 /// [`sort_unstable`]: slice::sort_unstable
2798 /// Panics when `index >= len()`, meaning it always panics on empty slices.
2803 /// let mut v = [-5i32, 4, 1, -3, 2];
2805 /// // Return the median as if the array were sorted according to absolute value.
2806 /// v.select_nth_unstable_by_key(2, |a| a.abs());
2808 /// // We are only guaranteed the slice will be one of the following, based on the way we sort
2809 /// // about the specified index.
2810 /// assert!(v == [1, 2, -3, 4, -5] ||
2811 /// v == [1, 2, -3, -5, 4] ||
2812 /// v == [2, 1, -3, 4, -5] ||
2813 /// v == [2, 1, -3, -5, 4]);
2815 #[stable(feature = "slice_select_nth_unstable", since = "1.49.0")]
2817 pub fn select_nth_unstable_by_key<K, F>(
2821 ) -> (&mut [T], &mut T, &mut [T])
2826 sort::partition_at_index(self, index, |a: &T, b: &T| f(a).lt(&f(b)))
2829 /// Moves all consecutive repeated elements to the end of the slice according to the
2830 /// [`PartialEq`] trait implementation.
2832 /// Returns two slices. The first contains no consecutive repeated elements.
2833 /// The second contains all the duplicates in no specified order.
2835 /// If the slice is sorted, the first returned slice contains no duplicates.
2840 /// #![feature(slice_partition_dedup)]
2842 /// let mut slice = [1, 2, 2, 3, 3, 2, 1, 1];
2844 /// let (dedup, duplicates) = slice.partition_dedup();
2846 /// assert_eq!(dedup, [1, 2, 3, 2, 1]);
2847 /// assert_eq!(duplicates, [2, 3, 1]);
2849 #[unstable(feature = "slice_partition_dedup", issue = "54279")]
2851 pub fn partition_dedup(&mut self) -> (&mut [T], &mut [T])
2855 self.partition_dedup_by(|a, b| a == b)
2858 /// Moves all but the first of consecutive elements to the end of the slice satisfying
2859 /// a given equality relation.
2861 /// Returns two slices. The first contains no consecutive repeated elements.
2862 /// The second contains all the duplicates in no specified order.
2864 /// The `same_bucket` function is passed references to two elements from the slice and
2865 /// must determine if the elements compare equal. The elements are passed in opposite order
2866 /// from their order in the slice, so if `same_bucket(a, b)` returns `true`, `a` is moved
2867 /// at the end of the slice.
2869 /// If the slice is sorted, the first returned slice contains no duplicates.
2874 /// #![feature(slice_partition_dedup)]
2876 /// let mut slice = ["foo", "Foo", "BAZ", "Bar", "bar", "baz", "BAZ"];
2878 /// let (dedup, duplicates) = slice.partition_dedup_by(|a, b| a.eq_ignore_ascii_case(b));
2880 /// assert_eq!(dedup, ["foo", "BAZ", "Bar", "baz"]);
2881 /// assert_eq!(duplicates, ["bar", "Foo", "BAZ"]);
2883 #[unstable(feature = "slice_partition_dedup", issue = "54279")]
2885 pub fn partition_dedup_by<F>(&mut self, mut same_bucket: F) -> (&mut [T], &mut [T])
2887 F: FnMut(&mut T, &mut T) -> bool,
2889 // Although we have a mutable reference to `self`, we cannot make
2890 // *arbitrary* changes. The `same_bucket` calls could panic, so we
2891 // must ensure that the slice is in a valid state at all times.
2893 // The way that we handle this is by using swaps; we iterate
2894 // over all the elements, swapping as we go so that at the end
2895 // the elements we wish to keep are in the front, and those we
2896 // wish to reject are at the back. We can then split the slice.
2897 // This operation is still `O(n)`.
2899 // Example: We start in this state, where `r` represents "next
2900 // read" and `w` represents "next_write`.
2903 // +---+---+---+---+---+---+
2904 // | 0 | 1 | 1 | 2 | 3 | 3 |
2905 // +---+---+---+---+---+---+
2908 // Comparing self[r] against self[w-1], this is not a duplicate, so
2909 // we swap self[r] and self[w] (no effect as r==w) and then increment both
2910 // r and w, leaving us with:
2913 // +---+---+---+---+---+---+
2914 // | 0 | 1 | 1 | 2 | 3 | 3 |
2915 // +---+---+---+---+---+---+
2918 // Comparing self[r] against self[w-1], this value is a duplicate,
2919 // so we increment `r` but leave everything else unchanged:
2922 // +---+---+---+---+---+---+
2923 // | 0 | 1 | 1 | 2 | 3 | 3 |
2924 // +---+---+---+---+---+---+
2927 // Comparing self[r] against self[w-1], this is not a duplicate,
2928 // so swap self[r] and self[w] and advance r and w:
2931 // +---+---+---+---+---+---+
2932 // | 0 | 1 | 2 | 1 | 3 | 3 |
2933 // +---+---+---+---+---+---+
2936 // Not a duplicate, repeat:
2939 // +---+---+---+---+---+---+
2940 // | 0 | 1 | 2 | 3 | 1 | 3 |
2941 // +---+---+---+---+---+---+
2944 // Duplicate, advance r. End of slice. Split at w.
2946 let len = self.len();
2948 return (self, &mut []);
2951 let ptr = self.as_mut_ptr();
2952 let mut next_read: usize = 1;
2953 let mut next_write: usize = 1;
2955 // SAFETY: the `while` condition guarantees `next_read` and `next_write`
2956 // are less than `len`, thus are inside `self`. `prev_ptr_write` points to
2957 // one element before `ptr_write`, but `next_write` starts at 1, so
2958 // `prev_ptr_write` is never less than 0 and is inside the slice.
2959 // This fulfils the requirements for dereferencing `ptr_read`, `prev_ptr_write`
2960 // and `ptr_write`, and for using `ptr.add(next_read)`, `ptr.add(next_write - 1)`
2961 // and `prev_ptr_write.offset(1)`.
2963 // `next_write` is also incremented at most once per loop at most meaning
2964 // no element is skipped when it may need to be swapped.
2966 // `ptr_read` and `prev_ptr_write` never point to the same element. This
2967 // is required for `&mut *ptr_read`, `&mut *prev_ptr_write` to be safe.
2968 // The explanation is simply that `next_read >= next_write` is always true,
2969 // thus `next_read > next_write - 1` is too.
2971 // Avoid bounds checks by using raw pointers.
2972 while next_read < len {
2973 let ptr_read = ptr.add(next_read);
2974 let prev_ptr_write = ptr.add(next_write - 1);
2975 if !same_bucket(&mut *ptr_read, &mut *prev_ptr_write) {
2976 if next_read != next_write {
2977 let ptr_write = prev_ptr_write.add(1);
2978 mem::swap(&mut *ptr_read, &mut *ptr_write);
2986 self.split_at_mut(next_write)
2989 /// Moves all but the first of consecutive elements to the end of the slice that resolve
2990 /// to the same key.
2992 /// Returns two slices. The first contains no consecutive repeated elements.
2993 /// The second contains all the duplicates in no specified order.
2995 /// If the slice is sorted, the first returned slice contains no duplicates.
3000 /// #![feature(slice_partition_dedup)]
3002 /// let mut slice = [10, 20, 21, 30, 30, 20, 11, 13];
3004 /// let (dedup, duplicates) = slice.partition_dedup_by_key(|i| *i / 10);
3006 /// assert_eq!(dedup, [10, 20, 30, 20, 11]);
3007 /// assert_eq!(duplicates, [21, 30, 13]);
3009 #[unstable(feature = "slice_partition_dedup", issue = "54279")]
3011 pub fn partition_dedup_by_key<K, F>(&mut self, mut key: F) -> (&mut [T], &mut [T])
3013 F: FnMut(&mut T) -> K,
3016 self.partition_dedup_by(|a, b| key(a) == key(b))
3019 /// Rotates the slice in-place such that the first `mid` elements of the
3020 /// slice move to the end while the last `self.len() - mid` elements move to
3021 /// the front. After calling `rotate_left`, the element previously at index
3022 /// `mid` will become the first element in the slice.
3026 /// This function will panic if `mid` is greater than the length of the
3027 /// slice. Note that `mid == self.len()` does _not_ panic and is a no-op
3032 /// Takes linear (in `self.len()`) time.
3037 /// let mut a = ['a', 'b', 'c', 'd', 'e', 'f'];
3038 /// a.rotate_left(2);
3039 /// assert_eq!(a, ['c', 'd', 'e', 'f', 'a', 'b']);
3042 /// Rotating a subslice:
3045 /// let mut a = ['a', 'b', 'c', 'd', 'e', 'f'];
3046 /// a[1..5].rotate_left(1);
3047 /// assert_eq!(a, ['a', 'c', 'd', 'e', 'b', 'f']);
3049 #[stable(feature = "slice_rotate", since = "1.26.0")]
3050 pub fn rotate_left(&mut self, mid: usize) {
3051 assert!(mid <= self.len());
3052 let k = self.len() - mid;
3053 let p = self.as_mut_ptr();
3055 // SAFETY: The range `[p.add(mid) - mid, p.add(mid) + k)` is trivially
3056 // valid for reading and writing, as required by `ptr_rotate`.
3058 rotate::ptr_rotate(mid, p.add(mid), k);
3062 /// Rotates the slice in-place such that the first `self.len() - k`
3063 /// elements of the slice move to the end while the last `k` elements move
3064 /// to the front. After calling `rotate_right`, the element previously at
3065 /// index `self.len() - k` will become the first element in the slice.
3069 /// This function will panic if `k` is greater than the length of the
3070 /// slice. Note that `k == self.len()` does _not_ panic and is a no-op
3075 /// Takes linear (in `self.len()`) time.
3080 /// let mut a = ['a', 'b', 'c', 'd', 'e', 'f'];
3081 /// a.rotate_right(2);
3082 /// assert_eq!(a, ['e', 'f', 'a', 'b', 'c', 'd']);
3085 /// Rotate a subslice:
3088 /// let mut a = ['a', 'b', 'c', 'd', 'e', 'f'];
3089 /// a[1..5].rotate_right(1);
3090 /// assert_eq!(a, ['a', 'e', 'b', 'c', 'd', 'f']);
3092 #[stable(feature = "slice_rotate", since = "1.26.0")]
3093 pub fn rotate_right(&mut self, k: usize) {
3094 assert!(k <= self.len());
3095 let mid = self.len() - k;
3096 let p = self.as_mut_ptr();
3098 // SAFETY: The range `[p.add(mid) - mid, p.add(mid) + k)` is trivially
3099 // valid for reading and writing, as required by `ptr_rotate`.
3101 rotate::ptr_rotate(mid, p.add(mid), k);
3105 /// Fills `self` with elements by cloning `value`.
3110 /// let mut buf = vec![0; 10];
3112 /// assert_eq!(buf, vec![1; 10]);
3114 #[doc(alias = "memset")]
3115 #[stable(feature = "slice_fill", since = "1.50.0")]
3116 pub fn fill(&mut self, value: T)
3120 specialize::SpecFill::spec_fill(self, value);
3123 /// Fills `self` with elements returned by calling a closure repeatedly.
3125 /// This method uses a closure to create new values. If you'd rather
3126 /// [`Clone`] a given value, use [`fill`]. If you want to use the [`Default`]
3127 /// trait to generate values, you can pass [`Default::default`] as the
3130 /// [`fill`]: slice::fill
3135 /// let mut buf = vec![1; 10];
3136 /// buf.fill_with(Default::default);
3137 /// assert_eq!(buf, vec![0; 10]);
3139 #[stable(feature = "slice_fill_with", since = "1.51.0")]
3140 pub fn fill_with<F>(&mut self, mut f: F)
3149 /// Copies the elements from `src` into `self`.
3151 /// The length of `src` must be the same as `self`.
3155 /// This function will panic if the two slices have different lengths.
3159 /// Cloning two elements from a slice into another:
3162 /// let src = [1, 2, 3, 4];
3163 /// let mut dst = [0, 0];
3165 /// // Because the slices have to be the same length,
3166 /// // we slice the source slice from four elements
3167 /// // to two. It will panic if we don't do this.
3168 /// dst.clone_from_slice(&src[2..]);
3170 /// assert_eq!(src, [1, 2, 3, 4]);
3171 /// assert_eq!(dst, [3, 4]);
3174 /// Rust enforces that there can only be one mutable reference with no
3175 /// immutable references to a particular piece of data in a particular
3176 /// scope. Because of this, attempting to use `clone_from_slice` on a
3177 /// single slice will result in a compile failure:
3180 /// let mut slice = [1, 2, 3, 4, 5];
3182 /// slice[..2].clone_from_slice(&slice[3..]); // compile fail!
3185 /// To work around this, we can use [`split_at_mut`] to create two distinct
3186 /// sub-slices from a slice:
3189 /// let mut slice = [1, 2, 3, 4, 5];
3192 /// let (left, right) = slice.split_at_mut(2);
3193 /// left.clone_from_slice(&right[1..]);
3196 /// assert_eq!(slice, [4, 5, 3, 4, 5]);
3199 /// [`copy_from_slice`]: slice::copy_from_slice
3200 /// [`split_at_mut`]: slice::split_at_mut
3201 #[stable(feature = "clone_from_slice", since = "1.7.0")]
3203 pub fn clone_from_slice(&mut self, src: &[T])
3207 self.spec_clone_from(src);
3210 /// Copies all elements from `src` into `self`, using a memcpy.
3212 /// The length of `src` must be the same as `self`.
3214 /// If `T` does not implement `Copy`, use [`clone_from_slice`].
3218 /// This function will panic if the two slices have different lengths.
3222 /// Copying two elements from a slice into another:
3225 /// let src = [1, 2, 3, 4];
3226 /// let mut dst = [0, 0];
3228 /// // Because the slices have to be the same length,
3229 /// // we slice the source slice from four elements
3230 /// // to two. It will panic if we don't do this.
3231 /// dst.copy_from_slice(&src[2..]);
3233 /// assert_eq!(src, [1, 2, 3, 4]);
3234 /// assert_eq!(dst, [3, 4]);
3237 /// Rust enforces that there can only be one mutable reference with no
3238 /// immutable references to a particular piece of data in a particular
3239 /// scope. Because of this, attempting to use `copy_from_slice` on a
3240 /// single slice will result in a compile failure:
3243 /// let mut slice = [1, 2, 3, 4, 5];
3245 /// slice[..2].copy_from_slice(&slice[3..]); // compile fail!
3248 /// To work around this, we can use [`split_at_mut`] to create two distinct
3249 /// sub-slices from a slice:
3252 /// let mut slice = [1, 2, 3, 4, 5];
3255 /// let (left, right) = slice.split_at_mut(2);
3256 /// left.copy_from_slice(&right[1..]);
3259 /// assert_eq!(slice, [4, 5, 3, 4, 5]);
3262 /// [`clone_from_slice`]: slice::clone_from_slice
3263 /// [`split_at_mut`]: slice::split_at_mut
3264 #[doc(alias = "memcpy")]
3265 #[stable(feature = "copy_from_slice", since = "1.9.0")]
3267 pub fn copy_from_slice(&mut self, src: &[T])
3271 // The panic code path was put into a cold function to not bloat the
3276 fn len_mismatch_fail(dst_len: usize, src_len: usize) -> ! {
3278 "source slice length ({}) does not match destination slice length ({})",
3283 if self.len() != src.len() {
3284 len_mismatch_fail(self.len(), src.len());
3287 // SAFETY: `self` is valid for `self.len()` elements by definition, and `src` was
3288 // checked to have the same length. The slices cannot overlap because
3289 // mutable references are exclusive.
3291 ptr::copy_nonoverlapping(src.as_ptr(), self.as_mut_ptr(), self.len());
3295 /// Copies elements from one part of the slice to another part of itself,
3296 /// using a memmove.
3298 /// `src` is the range within `self` to copy from. `dest` is the starting
3299 /// index of the range within `self` to copy to, which will have the same
3300 /// length as `src`. The two ranges may overlap. The ends of the two ranges
3301 /// must be less than or equal to `self.len()`.
3305 /// This function will panic if either range exceeds the end of the slice,
3306 /// or if the end of `src` is before the start.
3310 /// Copying four bytes within a slice:
3313 /// let mut bytes = *b"Hello, World!";
3315 /// bytes.copy_within(1..5, 8);
3317 /// assert_eq!(&bytes, b"Hello, Wello!");
3319 #[stable(feature = "copy_within", since = "1.37.0")]
3321 pub fn copy_within<R: RangeBounds<usize>>(&mut self, src: R, dest: usize)
3325 let Range { start: src_start, end: src_end } = slice::range(src, ..self.len());
3326 let count = src_end - src_start;
3327 assert!(dest <= self.len() - count, "dest is out of bounds");
3328 // SAFETY: the conditions for `ptr::copy` have all been checked above,
3329 // as have those for `ptr::add`.
3331 // Derive both `src_ptr` and `dest_ptr` from the same loan
3332 let ptr = self.as_mut_ptr();
3333 let src_ptr = ptr.add(src_start);
3334 let dest_ptr = ptr.add(dest);
3335 ptr::copy(src_ptr, dest_ptr, count);
3339 /// Swaps all elements in `self` with those in `other`.
3341 /// The length of `other` must be the same as `self`.
3345 /// This function will panic if the two slices have different lengths.
3349 /// Swapping two elements across slices:
3352 /// let mut slice1 = [0, 0];
3353 /// let mut slice2 = [1, 2, 3, 4];
3355 /// slice1.swap_with_slice(&mut slice2[2..]);
3357 /// assert_eq!(slice1, [3, 4]);
3358 /// assert_eq!(slice2, [1, 2, 0, 0]);
3361 /// Rust enforces that there can only be one mutable reference to a
3362 /// particular piece of data in a particular scope. Because of this,
3363 /// attempting to use `swap_with_slice` on a single slice will result in
3364 /// a compile failure:
3367 /// let mut slice = [1, 2, 3, 4, 5];
3368 /// slice[..2].swap_with_slice(&mut slice[3..]); // compile fail!
3371 /// To work around this, we can use [`split_at_mut`] to create two distinct
3372 /// mutable sub-slices from a slice:
3375 /// let mut slice = [1, 2, 3, 4, 5];
3378 /// let (left, right) = slice.split_at_mut(2);
3379 /// left.swap_with_slice(&mut right[1..]);
3382 /// assert_eq!(slice, [4, 5, 3, 1, 2]);
3385 /// [`split_at_mut`]: slice::split_at_mut
3386 #[stable(feature = "swap_with_slice", since = "1.27.0")]
3388 pub fn swap_with_slice(&mut self, other: &mut [T]) {
3389 assert!(self.len() == other.len(), "destination and source slices have different lengths");
3390 // SAFETY: `self` is valid for `self.len()` elements by definition, and `src` was
3391 // checked to have the same length. The slices cannot overlap because
3392 // mutable references are exclusive.
3394 ptr::swap_nonoverlapping(self.as_mut_ptr(), other.as_mut_ptr(), self.len());
3398 /// Function to calculate lengths of the middle and trailing slice for `align_to{,_mut}`.
3399 fn align_to_offsets<U>(&self) -> (usize, usize) {
3400 // What we gonna do about `rest` is figure out what multiple of `U`s we can put in a
3401 // lowest number of `T`s. And how many `T`s we need for each such "multiple".
3403 // Consider for example T=u8 U=u16. Then we can put 1 U in 2 Ts. Simple. Now, consider
3404 // for example a case where size_of::<T> = 16, size_of::<U> = 24. We can put 2 Us in
3405 // place of every 3 Ts in the `rest` slice. A bit more complicated.
3407 // Formula to calculate this is:
3409 // Us = lcm(size_of::<T>, size_of::<U>) / size_of::<U>
3410 // Ts = lcm(size_of::<T>, size_of::<U>) / size_of::<T>
3412 // Expanded and simplified:
3414 // Us = size_of::<T> / gcd(size_of::<T>, size_of::<U>)
3415 // Ts = size_of::<U> / gcd(size_of::<T>, size_of::<U>)
3417 // Luckily since all this is constant-evaluated... performance here matters not!
3419 fn gcd(a: usize, b: usize) -> usize {
3420 use crate::intrinsics;
3421 // iterative stein’s algorithm
3422 // We should still make this `const fn` (and revert to recursive algorithm if we do)
3423 // because relying on llvm to consteval all this is… well, it makes me uncomfortable.
3425 // SAFETY: `a` and `b` are checked to be non-zero values.
3426 let (ctz_a, mut ctz_b) = unsafe {
3433 (intrinsics::cttz_nonzero(a), intrinsics::cttz_nonzero(b))
3435 let k = ctz_a.min(ctz_b);
3436 let mut a = a >> ctz_a;
3439 // remove all factors of 2 from b
3442 mem::swap(&mut a, &mut b);
3445 // SAFETY: `b` is checked to be non-zero.
3450 ctz_b = intrinsics::cttz_nonzero(b);
3455 let gcd: usize = gcd(mem::size_of::<T>(), mem::size_of::<U>());
3456 let ts: usize = mem::size_of::<U>() / gcd;
3457 let us: usize = mem::size_of::<T>() / gcd;
3459 // Armed with this knowledge, we can find how many `U`s we can fit!
3460 let us_len = self.len() / ts * us;
3461 // And how many `T`s will be in the trailing slice!
3462 let ts_len = self.len() % ts;
3466 /// Transmute the slice to a slice of another type, ensuring alignment of the types is
3469 /// This method splits the slice into three distinct slices: prefix, correctly aligned middle
3470 /// slice of a new type, and the suffix slice. The method may make the middle slice the greatest
3471 /// length possible for a given type and input slice, but only your algorithm's performance
3472 /// should depend on that, not its correctness. It is permissible for all of the input data to
3473 /// be returned as the prefix or suffix slice.
3475 /// This method has no purpose when either input element `T` or output element `U` are
3476 /// zero-sized and will return the original slice without splitting anything.
3480 /// This method is essentially a `transmute` with respect to the elements in the returned
3481 /// middle slice, so all the usual caveats pertaining to `transmute::<T, U>` also apply here.
3489 /// let bytes: [u8; 7] = [1, 2, 3, 4, 5, 6, 7];
3490 /// let (prefix, shorts, suffix) = bytes.align_to::<u16>();
3491 /// // less_efficient_algorithm_for_bytes(prefix);
3492 /// // more_efficient_algorithm_for_aligned_shorts(shorts);
3493 /// // less_efficient_algorithm_for_bytes(suffix);
3496 #[stable(feature = "slice_align_to", since = "1.30.0")]
3498 pub unsafe fn align_to<U>(&self) -> (&[T], &[U], &[T]) {
3499 // Note that most of this function will be constant-evaluated,
3500 if U::IS_ZST || T::IS_ZST {
3501 // handle ZSTs specially, which is – don't handle them at all.
3502 return (self, &[], &[]);
3505 // First, find at what point do we split between the first and 2nd slice. Easy with
3506 // ptr.align_offset.
3507 let ptr = self.as_ptr();
3508 // SAFETY: See the `align_to_mut` method for the detailed safety comment.
3509 let offset = unsafe { crate::ptr::align_offset(ptr, mem::align_of::<U>()) };
3510 if offset > self.len() {
3513 let (left, rest) = self.split_at(offset);
3514 let (us_len, ts_len) = rest.align_to_offsets::<U>();
3515 // SAFETY: now `rest` is definitely aligned, so `from_raw_parts` below is okay,
3516 // since the caller guarantees that we can transmute `T` to `U` safely.
3520 from_raw_parts(rest.as_ptr() as *const U, us_len),
3521 from_raw_parts(rest.as_ptr().add(rest.len() - ts_len), ts_len),
3527 /// Transmute the mutable slice to a mutable slice of another type, ensuring alignment of the
3528 /// types is maintained.
3530 /// This method splits the slice into three distinct slices: prefix, correctly aligned middle
3531 /// slice of a new type, and the suffix slice. The method may make the middle slice the greatest
3532 /// length possible for a given type and input slice, but only your algorithm's performance
3533 /// should depend on that, not its correctness. It is permissible for all of the input data to
3534 /// be returned as the prefix or suffix slice.
3536 /// This method has no purpose when either input element `T` or output element `U` are
3537 /// zero-sized and will return the original slice without splitting anything.
3541 /// This method is essentially a `transmute` with respect to the elements in the returned
3542 /// middle slice, so all the usual caveats pertaining to `transmute::<T, U>` also apply here.
3550 /// let mut bytes: [u8; 7] = [1, 2, 3, 4, 5, 6, 7];
3551 /// let (prefix, shorts, suffix) = bytes.align_to_mut::<u16>();
3552 /// // less_efficient_algorithm_for_bytes(prefix);
3553 /// // more_efficient_algorithm_for_aligned_shorts(shorts);
3554 /// // less_efficient_algorithm_for_bytes(suffix);
3557 #[stable(feature = "slice_align_to", since = "1.30.0")]
3559 pub unsafe fn align_to_mut<U>(&mut self) -> (&mut [T], &mut [U], &mut [T]) {
3560 // Note that most of this function will be constant-evaluated,
3561 if U::IS_ZST || T::IS_ZST {
3562 // handle ZSTs specially, which is – don't handle them at all.
3563 return (self, &mut [], &mut []);
3566 // First, find at what point do we split between the first and 2nd slice. Easy with
3567 // ptr.align_offset.
3568 let ptr = self.as_ptr();
3569 // SAFETY: Here we are ensuring we will use aligned pointers for U for the
3570 // rest of the method. This is done by passing a pointer to &[T] with an
3571 // alignment targeted for U.
3572 // `crate::ptr::align_offset` is called with a correctly aligned and
3573 // valid pointer `ptr` (it comes from a reference to `self`) and with
3574 // a size that is a power of two (since it comes from the alignment for U),
3575 // satisfying its safety constraints.
3576 let offset = unsafe { crate::ptr::align_offset(ptr, mem::align_of::<U>()) };
3577 if offset > self.len() {
3578 (self, &mut [], &mut [])
3580 let (left, rest) = self.split_at_mut(offset);
3581 let (us_len, ts_len) = rest.align_to_offsets::<U>();
3582 let rest_len = rest.len();
3583 let mut_ptr = rest.as_mut_ptr();
3584 // We can't use `rest` again after this, that would invalidate its alias `mut_ptr`!
3585 // SAFETY: see comments for `align_to`.
3589 from_raw_parts_mut(mut_ptr as *mut U, us_len),
3590 from_raw_parts_mut(mut_ptr.add(rest_len - ts_len), ts_len),
3596 /// Split a slice into a prefix, a middle of aligned SIMD types, and a suffix.
3598 /// This is a safe wrapper around [`slice::align_to`], so has the same weak
3599 /// postconditions as that method. You're only assured that
3600 /// `self.len() == prefix.len() + middle.len() * LANES + suffix.len()`.
3602 /// Notably, all of the following are possible:
3603 /// - `prefix.len() >= LANES`.
3604 /// - `middle.is_empty()` despite `self.len() >= 3 * LANES`.
3605 /// - `suffix.len() >= LANES`.
3607 /// That said, this is a safe method, so if you're only writing safe code,
3608 /// then this can at most cause incorrect logic, not unsoundness.
3612 /// This will panic if the size of the SIMD type is different from
3613 /// `LANES` times that of the scalar.
3615 /// At the time of writing, the trait restrictions on `Simd<T, LANES>` keeps
3616 /// that from ever happening, as only power-of-two numbers of lanes are
3617 /// supported. It's possible that, in the future, those restrictions might
3618 /// be lifted in a way that would make it possible to see panics from this
3619 /// method for something like `LANES == 3`.
3624 /// #![feature(portable_simd)]
3625 /// use core::simd::SimdFloat;
3627 /// let short = &[1, 2, 3];
3628 /// let (prefix, middle, suffix) = short.as_simd::<4>();
3629 /// assert_eq!(middle, []); // Not enough elements for anything in the middle
3631 /// // They might be split in any possible way between prefix and suffix
3632 /// let it = prefix.iter().chain(suffix).copied();
3633 /// assert_eq!(it.collect::<Vec<_>>(), vec![1, 2, 3]);
3635 /// fn basic_simd_sum(x: &[f32]) -> f32 {
3636 /// use std::ops::Add;
3637 /// use std::simd::f32x4;
3638 /// let (prefix, middle, suffix) = x.as_simd();
3639 /// let sums = f32x4::from_array([
3640 /// prefix.iter().copied().sum(),
3643 /// suffix.iter().copied().sum(),
3645 /// let sums = middle.iter().copied().fold(sums, f32x4::add);
3646 /// sums.reduce_sum()
3649 /// let numbers: Vec<f32> = (1..101).map(|x| x as _).collect();
3650 /// assert_eq!(basic_simd_sum(&numbers[1..99]), 4949.0);
3652 #[unstable(feature = "portable_simd", issue = "86656")]
3654 pub fn as_simd<const LANES: usize>(&self) -> (&[T], &[Simd<T, LANES>], &[T])
3656 Simd<T, LANES>: AsRef<[T; LANES]>,
3657 T: simd::SimdElement,
3658 simd::LaneCount<LANES>: simd::SupportedLaneCount,
3660 // These are expected to always match, as vector types are laid out like
3661 // arrays per <https://llvm.org/docs/LangRef.html#vector-type>, but we
3662 // might as well double-check since it'll optimize away anyhow.
3663 assert_eq!(mem::size_of::<Simd<T, LANES>>(), mem::size_of::<[T; LANES]>());
3665 // SAFETY: The simd types have the same layout as arrays, just with
3666 // potentially-higher alignment, so the de-facto transmutes are sound.
3667 unsafe { self.align_to() }
3670 /// Split a mutable slice into a mutable prefix, a middle of aligned SIMD types,
3671 /// and a mutable suffix.
3673 /// This is a safe wrapper around [`slice::align_to_mut`], so has the same weak
3674 /// postconditions as that method. You're only assured that
3675 /// `self.len() == prefix.len() + middle.len() * LANES + suffix.len()`.
3677 /// Notably, all of the following are possible:
3678 /// - `prefix.len() >= LANES`.
3679 /// - `middle.is_empty()` despite `self.len() >= 3 * LANES`.
3680 /// - `suffix.len() >= LANES`.
3682 /// That said, this is a safe method, so if you're only writing safe code,
3683 /// then this can at most cause incorrect logic, not unsoundness.
3685 /// This is the mutable version of [`slice::as_simd`]; see that for examples.
3689 /// This will panic if the size of the SIMD type is different from
3690 /// `LANES` times that of the scalar.
3692 /// At the time of writing, the trait restrictions on `Simd<T, LANES>` keeps
3693 /// that from ever happening, as only power-of-two numbers of lanes are
3694 /// supported. It's possible that, in the future, those restrictions might
3695 /// be lifted in a way that would make it possible to see panics from this
3696 /// method for something like `LANES == 3`.
3697 #[unstable(feature = "portable_simd", issue = "86656")]
3699 pub fn as_simd_mut<const LANES: usize>(&mut self) -> (&mut [T], &mut [Simd<T, LANES>], &mut [T])
3701 Simd<T, LANES>: AsMut<[T; LANES]>,
3702 T: simd::SimdElement,
3703 simd::LaneCount<LANES>: simd::SupportedLaneCount,
3705 // These are expected to always match, as vector types are laid out like
3706 // arrays per <https://llvm.org/docs/LangRef.html#vector-type>, but we
3707 // might as well double-check since it'll optimize away anyhow.
3708 assert_eq!(mem::size_of::<Simd<T, LANES>>(), mem::size_of::<[T; LANES]>());
3710 // SAFETY: The simd types have the same layout as arrays, just with
3711 // potentially-higher alignment, so the de-facto transmutes are sound.
3712 unsafe { self.align_to_mut() }
3715 /// Checks if the elements of this slice are sorted.
3717 /// That is, for each element `a` and its following element `b`, `a <= b` must hold. If the
3718 /// slice yields exactly zero or one element, `true` is returned.
3720 /// Note that if `Self::Item` is only `PartialOrd`, but not `Ord`, the above definition
3721 /// implies that this function returns `false` if any two consecutive items are not
3727 /// #![feature(is_sorted)]
3728 /// let empty: [i32; 0] = [];
3730 /// assert!([1, 2, 2, 9].is_sorted());
3731 /// assert!(![1, 3, 2, 4].is_sorted());
3732 /// assert!([0].is_sorted());
3733 /// assert!(empty.is_sorted());
3734 /// assert!(![0.0, 1.0, f32::NAN].is_sorted());
3737 #[unstable(feature = "is_sorted", reason = "new API", issue = "53485")]
3739 pub fn is_sorted(&self) -> bool
3743 self.is_sorted_by(|a, b| a.partial_cmp(b))
3746 /// Checks if the elements of this slice are sorted using the given comparator function.
3748 /// Instead of using `PartialOrd::partial_cmp`, this function uses the given `compare`
3749 /// function to determine the ordering of two elements. Apart from that, it's equivalent to
3750 /// [`is_sorted`]; see its documentation for more information.
3752 /// [`is_sorted`]: slice::is_sorted
3753 #[unstable(feature = "is_sorted", reason = "new API", issue = "53485")]
3755 pub fn is_sorted_by<'a, F>(&'a self, mut compare: F) -> bool
3757 F: FnMut(&'a T, &'a T) -> Option<Ordering>,
3759 self.iter().is_sorted_by(|a, b| compare(*a, *b))
3762 /// Checks if the elements of this slice are sorted using the given key extraction function.
3764 /// Instead of comparing the slice's elements directly, this function compares the keys of the
3765 /// elements, as determined by `f`. Apart from that, it's equivalent to [`is_sorted`]; see its
3766 /// documentation for more information.
3768 /// [`is_sorted`]: slice::is_sorted
3773 /// #![feature(is_sorted)]
3775 /// assert!(["c", "bb", "aaa"].is_sorted_by_key(|s| s.len()));
3776 /// assert!(![-2i32, -1, 0, 3].is_sorted_by_key(|n| n.abs()));
3779 #[unstable(feature = "is_sorted", reason = "new API", issue = "53485")]
3781 pub fn is_sorted_by_key<'a, F, K>(&'a self, f: F) -> bool
3783 F: FnMut(&'a T) -> K,
3786 self.iter().is_sorted_by_key(f)
3789 /// Returns the index of the partition point according to the given predicate
3790 /// (the index of the first element of the second partition).
3792 /// The slice is assumed to be partitioned according to the given predicate.
3793 /// This means that all elements for which the predicate returns true are at the start of the slice
3794 /// and all elements for which the predicate returns false are at the end.
3795 /// For example, [7, 15, 3, 5, 4, 12, 6] is a partitioned under the predicate x % 2 != 0
3796 /// (all odd numbers are at the start, all even at the end).
3798 /// If this slice is not partitioned, the returned result is unspecified and meaningless,
3799 /// as this method performs a kind of binary search.
3801 /// See also [`binary_search`], [`binary_search_by`], and [`binary_search_by_key`].
3803 /// [`binary_search`]: slice::binary_search
3804 /// [`binary_search_by`]: slice::binary_search_by
3805 /// [`binary_search_by_key`]: slice::binary_search_by_key
3810 /// let v = [1, 2, 3, 3, 5, 6, 7];
3811 /// let i = v.partition_point(|&x| x < 5);
3813 /// assert_eq!(i, 4);
3814 /// assert!(v[..i].iter().all(|&x| x < 5));
3815 /// assert!(v[i..].iter().all(|&x| !(x < 5)));
3818 /// If all elements of the slice match the predicate, including if the slice
3819 /// is empty, then the length of the slice will be returned:
3822 /// let a = [2, 4, 8];
3823 /// assert_eq!(a.partition_point(|x| x < &100), a.len());
3824 /// let a: [i32; 0] = [];
3825 /// assert_eq!(a.partition_point(|x| x < &100), 0);
3828 /// If you want to insert an item to a sorted vector, while maintaining
3832 /// let mut s = vec![0, 1, 1, 1, 1, 2, 3, 5, 8, 13, 21, 34, 55];
3834 /// let idx = s.partition_point(|&x| x < num);
3835 /// s.insert(idx, num);
3836 /// assert_eq!(s, [0, 1, 1, 1, 1, 2, 3, 5, 8, 13, 21, 34, 42, 55]);
3838 #[stable(feature = "partition_point", since = "1.52.0")]
3840 pub fn partition_point<P>(&self, mut pred: P) -> usize
3842 P: FnMut(&T) -> bool,
3844 self.binary_search_by(|x| if pred(x) { Less } else { Greater }).unwrap_or_else(|i| i)
3847 /// Removes the subslice corresponding to the given range
3848 /// and returns a reference to it.
3850 /// Returns `None` and does not modify the slice if the given
3851 /// range is out of bounds.
3853 /// Note that this method only accepts one-sided ranges such as
3854 /// `2..` or `..6`, but not `2..6`.
3858 /// Taking the first three elements of a slice:
3861 /// #![feature(slice_take)]
3863 /// let mut slice: &[_] = &['a', 'b', 'c', 'd'];
3864 /// let mut first_three = slice.take(..3).unwrap();
3866 /// assert_eq!(slice, &['d']);
3867 /// assert_eq!(first_three, &['a', 'b', 'c']);
3870 /// Taking the last two elements of a slice:
3873 /// #![feature(slice_take)]
3875 /// let mut slice: &[_] = &['a', 'b', 'c', 'd'];
3876 /// let mut tail = slice.take(2..).unwrap();
3878 /// assert_eq!(slice, &['a', 'b']);
3879 /// assert_eq!(tail, &['c', 'd']);
3882 /// Getting `None` when `range` is out of bounds:
3885 /// #![feature(slice_take)]
3887 /// let mut slice: &[_] = &['a', 'b', 'c', 'd'];
3889 /// assert_eq!(None, slice.take(5..));
3890 /// assert_eq!(None, slice.take(..5));
3891 /// assert_eq!(None, slice.take(..=4));
3892 /// let expected: &[char] = &['a', 'b', 'c', 'd'];
3893 /// assert_eq!(Some(expected), slice.take(..4));
3896 #[must_use = "method does not modify the slice if the range is out of bounds"]
3897 #[unstable(feature = "slice_take", issue = "62280")]
3898 pub fn take<'a, R: OneSidedRange<usize>>(self: &mut &'a Self, range: R) -> Option<&'a Self> {
3899 let (direction, split_index) = split_point_of(range)?;
3900 if split_index > self.len() {
3903 let (front, back) = self.split_at(split_index);
3905 Direction::Front => {
3909 Direction::Back => {
3916 /// Removes the subslice corresponding to the given range
3917 /// and returns a mutable reference to it.
3919 /// Returns `None` and does not modify the slice if the given
3920 /// range is out of bounds.
3922 /// Note that this method only accepts one-sided ranges such as
3923 /// `2..` or `..6`, but not `2..6`.
3927 /// Taking the first three elements of a slice:
3930 /// #![feature(slice_take)]
3932 /// let mut slice: &mut [_] = &mut ['a', 'b', 'c', 'd'];
3933 /// let mut first_three = slice.take_mut(..3).unwrap();
3935 /// assert_eq!(slice, &mut ['d']);
3936 /// assert_eq!(first_three, &mut ['a', 'b', 'c']);
3939 /// Taking the last two elements of a slice:
3942 /// #![feature(slice_take)]
3944 /// let mut slice: &mut [_] = &mut ['a', 'b', 'c', 'd'];
3945 /// let mut tail = slice.take_mut(2..).unwrap();
3947 /// assert_eq!(slice, &mut ['a', 'b']);
3948 /// assert_eq!(tail, &mut ['c', 'd']);
3951 /// Getting `None` when `range` is out of bounds:
3954 /// #![feature(slice_take)]
3956 /// let mut slice: &mut [_] = &mut ['a', 'b', 'c', 'd'];
3958 /// assert_eq!(None, slice.take_mut(5..));
3959 /// assert_eq!(None, slice.take_mut(..5));
3960 /// assert_eq!(None, slice.take_mut(..=4));
3961 /// let expected: &mut [_] = &mut ['a', 'b', 'c', 'd'];
3962 /// assert_eq!(Some(expected), slice.take_mut(..4));
3965 #[must_use = "method does not modify the slice if the range is out of bounds"]
3966 #[unstable(feature = "slice_take", issue = "62280")]
3967 pub fn take_mut<'a, R: OneSidedRange<usize>>(
3968 self: &mut &'a mut Self,
3970 ) -> Option<&'a mut Self> {
3971 let (direction, split_index) = split_point_of(range)?;
3972 if split_index > self.len() {
3975 let (front, back) = mem::take(self).split_at_mut(split_index);
3977 Direction::Front => {
3981 Direction::Back => {
3988 /// Removes the first element of the slice and returns a reference
3991 /// Returns `None` if the slice is empty.
3996 /// #![feature(slice_take)]
3998 /// let mut slice: &[_] = &['a', 'b', 'c'];
3999 /// let first = slice.take_first().unwrap();
4001 /// assert_eq!(slice, &['b', 'c']);
4002 /// assert_eq!(first, &'a');
4005 #[unstable(feature = "slice_take", issue = "62280")]
4006 pub fn take_first<'a>(self: &mut &'a Self) -> Option<&'a T> {
4007 let (first, rem) = self.split_first()?;
4012 /// Removes the first element of the slice and returns a mutable
4013 /// reference to it.
4015 /// Returns `None` if the slice is empty.
4020 /// #![feature(slice_take)]
4022 /// let mut slice: &mut [_] = &mut ['a', 'b', 'c'];
4023 /// let first = slice.take_first_mut().unwrap();
4026 /// assert_eq!(slice, &['b', 'c']);
4027 /// assert_eq!(first, &'d');
4030 #[unstable(feature = "slice_take", issue = "62280")]
4031 pub fn take_first_mut<'a>(self: &mut &'a mut Self) -> Option<&'a mut T> {
4032 let (first, rem) = mem::take(self).split_first_mut()?;
4037 /// Removes the last element of the slice and returns a reference
4040 /// Returns `None` if the slice is empty.
4045 /// #![feature(slice_take)]
4047 /// let mut slice: &[_] = &['a', 'b', 'c'];
4048 /// let last = slice.take_last().unwrap();
4050 /// assert_eq!(slice, &['a', 'b']);
4051 /// assert_eq!(last, &'c');
4054 #[unstable(feature = "slice_take", issue = "62280")]
4055 pub fn take_last<'a>(self: &mut &'a Self) -> Option<&'a T> {
4056 let (last, rem) = self.split_last()?;
4061 /// Removes the last element of the slice and returns a mutable
4062 /// reference to it.
4064 /// Returns `None` if the slice is empty.
4069 /// #![feature(slice_take)]
4071 /// let mut slice: &mut [_] = &mut ['a', 'b', 'c'];
4072 /// let last = slice.take_last_mut().unwrap();
4075 /// assert_eq!(slice, &['a', 'b']);
4076 /// assert_eq!(last, &'d');
4079 #[unstable(feature = "slice_take", issue = "62280")]
4080 pub fn take_last_mut<'a>(self: &mut &'a mut Self) -> Option<&'a mut T> {
4081 let (last, rem) = mem::take(self).split_last_mut()?;
4087 impl<T, const N: usize> [[T; N]] {
4088 /// Takes a `&[[T; N]]`, and flattens it to a `&[T]`.
4092 /// This panics if the length of the resulting slice would overflow a `usize`.
4094 /// This is only possible when flattening a slice of arrays of zero-sized
4095 /// types, and thus tends to be irrelevant in practice. If
4096 /// `size_of::<T>() > 0`, this will never panic.
4101 /// #![feature(slice_flatten)]
4103 /// assert_eq!([[1, 2, 3], [4, 5, 6]].flatten(), &[1, 2, 3, 4, 5, 6]);
4106 /// [[1, 2, 3], [4, 5, 6]].flatten(),
4107 /// [[1, 2], [3, 4], [5, 6]].flatten(),
4110 /// let slice_of_empty_arrays: &[[i32; 0]] = &[[], [], [], [], []];
4111 /// assert!(slice_of_empty_arrays.flatten().is_empty());
4113 /// let empty_slice_of_arrays: &[[u32; 10]] = &[];
4114 /// assert!(empty_slice_of_arrays.flatten().is_empty());
4116 #[unstable(feature = "slice_flatten", issue = "95629")]
4117 pub fn flatten(&self) -> &[T] {
4118 let len = if T::IS_ZST {
4119 self.len().checked_mul(N).expect("slice len overflow")
4121 // SAFETY: `self.len() * N` cannot overflow because `self` is
4122 // already in the address space.
4123 unsafe { self.len().unchecked_mul(N) }
4125 // SAFETY: `[T]` is layout-identical to `[T; N]`
4126 unsafe { from_raw_parts(self.as_ptr().cast(), len) }
4129 /// Takes a `&mut [[T; N]]`, and flattens it to a `&mut [T]`.
4133 /// This panics if the length of the resulting slice would overflow a `usize`.
4135 /// This is only possible when flattening a slice of arrays of zero-sized
4136 /// types, and thus tends to be irrelevant in practice. If
4137 /// `size_of::<T>() > 0`, this will never panic.
4142 /// #![feature(slice_flatten)]
4144 /// fn add_5_to_all(slice: &mut [i32]) {
4145 /// for i in slice {
4150 /// let mut array = [[1, 2, 3], [4, 5, 6], [7, 8, 9]];
4151 /// add_5_to_all(array.flatten_mut());
4152 /// assert_eq!(array, [[6, 7, 8], [9, 10, 11], [12, 13, 14]]);
4154 #[unstable(feature = "slice_flatten", issue = "95629")]
4155 pub fn flatten_mut(&mut self) -> &mut [T] {
4156 let len = if T::IS_ZST {
4157 self.len().checked_mul(N).expect("slice len overflow")
4159 // SAFETY: `self.len() * N` cannot overflow because `self` is
4160 // already in the address space.
4161 unsafe { self.len().unchecked_mul(N) }
4163 // SAFETY: `[T]` is layout-identical to `[T; N]`
4164 unsafe { from_raw_parts_mut(self.as_mut_ptr().cast(), len) }
4170 /// Sorts the slice of floats.
4172 /// This sort is in-place (i.e. does not allocate), *O*(*n* \* log(*n*)) worst-case, and uses
4173 /// the ordering defined by [`f32::total_cmp`].
4175 /// # Current implementation
4177 /// This uses the same sorting algorithm as [`sort_unstable_by`](slice::sort_unstable_by).
4182 /// #![feature(sort_floats)]
4183 /// let mut v = [2.6, -5e-8, f32::NAN, 8.29, f32::INFINITY, -1.0, 0.0, -f32::INFINITY, -0.0];
4185 /// v.sort_floats();
4186 /// let sorted = [-f32::INFINITY, -1.0, -5e-8, -0.0, 0.0, 2.6, 8.29, f32::INFINITY, f32::NAN];
4187 /// assert_eq!(&v[..8], &sorted[..8]);
4188 /// assert!(v[8].is_nan());
4190 #[unstable(feature = "sort_floats", issue = "93396")]
4192 pub fn sort_floats(&mut self) {
4193 self.sort_unstable_by(f32::total_cmp);
4199 /// Sorts the slice of floats.
4201 /// This sort is in-place (i.e. does not allocate), *O*(*n* \* log(*n*)) worst-case, and uses
4202 /// the ordering defined by [`f64::total_cmp`].
4204 /// # Current implementation
4206 /// This uses the same sorting algorithm as [`sort_unstable_by`](slice::sort_unstable_by).
4211 /// #![feature(sort_floats)]
4212 /// let mut v = [2.6, -5e-8, f64::NAN, 8.29, f64::INFINITY, -1.0, 0.0, -f64::INFINITY, -0.0];
4214 /// v.sort_floats();
4215 /// let sorted = [-f64::INFINITY, -1.0, -5e-8, -0.0, 0.0, 2.6, 8.29, f64::INFINITY, f64::NAN];
4216 /// assert_eq!(&v[..8], &sorted[..8]);
4217 /// assert!(v[8].is_nan());
4219 #[unstable(feature = "sort_floats", issue = "93396")]
4221 pub fn sort_floats(&mut self) {
4222 self.sort_unstable_by(f64::total_cmp);
4226 trait CloneFromSpec<T> {
4227 fn spec_clone_from(&mut self, src: &[T]);
4230 impl<T> CloneFromSpec<T> for [T]
4235 default fn spec_clone_from(&mut self, src: &[T]) {
4236 assert!(self.len() == src.len(), "destination and source slices have different lengths");
4237 // NOTE: We need to explicitly slice them to the same length
4238 // to make it easier for the optimizer to elide bounds checking.
4239 // But since it can't be relied on we also have an explicit specialization for T: Copy.
4240 let len = self.len();
4241 let src = &src[..len];
4243 self[i].clone_from(&src[i]);
4248 impl<T> CloneFromSpec<T> for [T]
4253 fn spec_clone_from(&mut self, src: &[T]) {
4254 self.copy_from_slice(src);
4258 #[stable(feature = "rust1", since = "1.0.0")]
4259 #[rustc_const_unstable(feature = "const_default_impls", issue = "87864")]
4260 impl<T> const Default for &[T] {
4261 /// Creates an empty slice.
4262 fn default() -> Self {
4267 #[stable(feature = "mut_slice_default", since = "1.5.0")]
4268 #[rustc_const_unstable(feature = "const_default_impls", issue = "87864")]
4269 impl<T> const Default for &mut [T] {
4270 /// Creates a mutable empty slice.
4271 fn default() -> Self {
4276 #[unstable(feature = "slice_pattern", reason = "stopgap trait for slice patterns", issue = "56345")]
4277 /// Patterns in slices - currently, only used by `strip_prefix` and `strip_suffix`. At a future
4278 /// point, we hope to generalise `core::str::Pattern` (which at the time of writing is limited to
4279 /// `str`) to slices, and then this trait will be replaced or abolished.
4280 pub trait SlicePattern {
4281 /// The element type of the slice being matched on.
4284 /// Currently, the consumers of `SlicePattern` need a slice.
4285 fn as_slice(&self) -> &[Self::Item];
4288 #[stable(feature = "slice_strip", since = "1.51.0")]
4289 impl<T> SlicePattern for [T] {
4293 fn as_slice(&self) -> &[Self::Item] {
4298 #[stable(feature = "slice_strip", since = "1.51.0")]
4299 impl<T, const N: usize> SlicePattern for [T; N] {
4303 fn as_slice(&self) -> &[Self::Item] {