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};
11 use crate::intrinsics::{assert_unsafe_precondition, exact_div};
12 use crate::marker::Copy;
13 use crate::mem::{self, SizedTypeProperties};
14 use crate::num::NonZeroUsize;
15 use crate::ops::{Bound, FnMut, OneSidedRange, Range, RangeBounds};
16 use crate::option::Option;
17 use crate::option::Option::{None, Some};
19 use crate::result::Result;
20 use crate::result::Result::{Err, Ok};
21 use crate::simd::{self, Simd};
25 feature = "slice_internals",
27 reason = "exposed from core to be reused in std; use the memchr crate"
29 /// Pure rust memchr implementation, taken from rust-memchr
41 #[stable(feature = "rust1", since = "1.0.0")]
42 pub use iter::{Chunks, ChunksMut, Windows};
43 #[stable(feature = "rust1", since = "1.0.0")]
44 pub use iter::{Iter, IterMut};
45 #[stable(feature = "rust1", since = "1.0.0")]
46 pub use iter::{RSplitN, RSplitNMut, Split, SplitMut, SplitN, SplitNMut};
48 #[stable(feature = "slice_rsplit", since = "1.27.0")]
49 pub use iter::{RSplit, RSplitMut};
51 #[stable(feature = "chunks_exact", since = "1.31.0")]
52 pub use iter::{ChunksExact, ChunksExactMut};
54 #[stable(feature = "rchunks", since = "1.31.0")]
55 pub use iter::{RChunks, RChunksExact, RChunksExactMut, RChunksMut};
57 #[unstable(feature = "array_chunks", issue = "74985")]
58 pub use iter::{ArrayChunks, ArrayChunksMut};
60 #[unstable(feature = "array_windows", issue = "75027")]
61 pub use iter::ArrayWindows;
63 #[unstable(feature = "slice_group_by", issue = "80552")]
64 pub use iter::{GroupBy, GroupByMut};
66 #[stable(feature = "split_inclusive", since = "1.51.0")]
67 pub use iter::{SplitInclusive, SplitInclusiveMut};
69 #[stable(feature = "rust1", since = "1.0.0")]
70 pub use raw::{from_raw_parts, from_raw_parts_mut};
72 #[stable(feature = "from_ref", since = "1.28.0")]
73 pub use raw::{from_mut, from_ref};
75 #[unstable(feature = "slice_from_ptr_range", issue = "89792")]
76 pub use raw::{from_mut_ptr_range, from_ptr_range};
78 // This function is public only because there is no other way to unit test heapsort.
79 #[unstable(feature = "sort_internals", reason = "internal to sort module", issue = "none")]
80 pub use sort::heapsort;
82 #[stable(feature = "slice_get_slice", since = "1.28.0")]
83 pub use index::SliceIndex;
85 #[unstable(feature = "slice_range", issue = "76393")]
88 #[stable(feature = "inherent_ascii_escape", since = "1.60.0")]
89 pub use ascii::EscapeAscii;
91 /// Calculates the direction and split point of a one-sided range.
93 /// This is a helper function for `take` and `take_mut` that returns
94 /// the direction of the split (front or back) as well as the index at
95 /// which to split. Returns `None` if the split index would overflow.
97 fn split_point_of(range: impl OneSidedRange<usize>) -> Option<(Direction, usize)> {
100 Some(match (range.start_bound(), range.end_bound()) {
101 (Unbounded, Excluded(i)) => (Direction::Front, *i),
102 (Unbounded, Included(i)) => (Direction::Front, i.checked_add(1)?),
103 (Excluded(i), Unbounded) => (Direction::Back, i.checked_add(1)?),
104 (Included(i), Unbounded) => (Direction::Back, *i),
116 /// Returns the number of elements in the slice.
121 /// let a = [1, 2, 3];
122 /// assert_eq!(a.len(), 3);
124 #[lang = "slice_len_fn"]
125 #[stable(feature = "rust1", since = "1.0.0")]
126 #[rustc_const_stable(feature = "const_slice_len", since = "1.39.0")]
127 #[rustc_allow_const_fn_unstable(ptr_metadata)]
130 pub const fn len(&self) -> usize {
134 /// Returns `true` if the slice has a length of 0.
139 /// let a = [1, 2, 3];
140 /// assert!(!a.is_empty());
142 #[stable(feature = "rust1", since = "1.0.0")]
143 #[rustc_const_stable(feature = "const_slice_is_empty", since = "1.39.0")]
146 pub const fn is_empty(&self) -> bool {
150 /// Returns the first element of the slice, or `None` if it is empty.
155 /// let v = [10, 40, 30];
156 /// assert_eq!(Some(&10), v.first());
158 /// let w: &[i32] = &[];
159 /// assert_eq!(None, w.first());
161 #[stable(feature = "rust1", since = "1.0.0")]
162 #[rustc_const_stable(feature = "const_slice_first_last_not_mut", since = "1.56.0")]
165 pub const fn first(&self) -> Option<&T> {
166 if let [first, ..] = self { Some(first) } else { None }
169 /// Returns a mutable pointer to the first element of the slice, or `None` if it is empty.
174 /// let x = &mut [0, 1, 2];
176 /// if let Some(first) = x.first_mut() {
179 /// assert_eq!(x, &[5, 1, 2]);
181 #[stable(feature = "rust1", since = "1.0.0")]
182 #[rustc_const_unstable(feature = "const_slice_first_last", issue = "83570")]
185 pub const fn first_mut(&mut self) -> Option<&mut T> {
186 if let [first, ..] = self { Some(first) } else { None }
189 /// Returns the first and all the rest of the elements of the slice, or `None` if it is empty.
194 /// let x = &[0, 1, 2];
196 /// if let Some((first, elements)) = x.split_first() {
197 /// assert_eq!(first, &0);
198 /// assert_eq!(elements, &[1, 2]);
201 #[stable(feature = "slice_splits", since = "1.5.0")]
202 #[rustc_const_stable(feature = "const_slice_first_last_not_mut", since = "1.56.0")]
205 pub const fn split_first(&self) -> Option<(&T, &[T])> {
206 if let [first, tail @ ..] = self { Some((first, tail)) } else { None }
209 /// Returns the first and all the rest of the elements of the slice, or `None` if it is empty.
214 /// let x = &mut [0, 1, 2];
216 /// if let Some((first, elements)) = x.split_first_mut() {
221 /// assert_eq!(x, &[3, 4, 5]);
223 #[stable(feature = "slice_splits", since = "1.5.0")]
224 #[rustc_const_unstable(feature = "const_slice_first_last", issue = "83570")]
227 pub const fn split_first_mut(&mut self) -> Option<(&mut T, &mut [T])> {
228 if let [first, tail @ ..] = self { Some((first, tail)) } else { None }
231 /// Returns the last and all the rest of the elements of the slice, or `None` if it is empty.
236 /// let x = &[0, 1, 2];
238 /// if let Some((last, elements)) = x.split_last() {
239 /// assert_eq!(last, &2);
240 /// assert_eq!(elements, &[0, 1]);
243 #[stable(feature = "slice_splits", since = "1.5.0")]
244 #[rustc_const_stable(feature = "const_slice_first_last_not_mut", since = "1.56.0")]
247 pub const fn split_last(&self) -> Option<(&T, &[T])> {
248 if let [init @ .., last] = self { Some((last, init)) } else { None }
251 /// Returns the last and all the rest of the elements of the slice, or `None` if it is empty.
256 /// let x = &mut [0, 1, 2];
258 /// if let Some((last, elements)) = x.split_last_mut() {
263 /// assert_eq!(x, &[4, 5, 3]);
265 #[stable(feature = "slice_splits", since = "1.5.0")]
266 #[rustc_const_unstable(feature = "const_slice_first_last", issue = "83570")]
269 pub const fn split_last_mut(&mut self) -> Option<(&mut T, &mut [T])> {
270 if let [init @ .., last] = self { Some((last, init)) } else { None }
273 /// Returns the last element of the slice, or `None` if it is empty.
278 /// let v = [10, 40, 30];
279 /// assert_eq!(Some(&30), v.last());
281 /// let w: &[i32] = &[];
282 /// assert_eq!(None, w.last());
284 #[stable(feature = "rust1", since = "1.0.0")]
285 #[rustc_const_stable(feature = "const_slice_first_last_not_mut", since = "1.56.0")]
288 pub const fn last(&self) -> Option<&T> {
289 if let [.., last] = self { Some(last) } else { None }
292 /// Returns a mutable pointer to the last item in the slice.
297 /// let x = &mut [0, 1, 2];
299 /// if let Some(last) = x.last_mut() {
302 /// assert_eq!(x, &[0, 1, 10]);
304 #[stable(feature = "rust1", since = "1.0.0")]
305 #[rustc_const_unstable(feature = "const_slice_first_last", issue = "83570")]
308 pub const fn last_mut(&mut self) -> Option<&mut T> {
309 if let [.., last] = self { Some(last) } else { None }
312 /// Returns a reference to an element or subslice depending on the type of
315 /// - If given a position, returns a reference to the element at that
316 /// position or `None` if out of bounds.
317 /// - If given a range, returns the subslice corresponding to that range,
318 /// or `None` if out of bounds.
323 /// let v = [10, 40, 30];
324 /// assert_eq!(Some(&40), v.get(1));
325 /// assert_eq!(Some(&[10, 40][..]), v.get(0..2));
326 /// assert_eq!(None, v.get(3));
327 /// assert_eq!(None, v.get(0..4));
329 #[stable(feature = "rust1", since = "1.0.0")]
330 #[rustc_const_unstable(feature = "const_slice_index", issue = "none")]
333 pub const fn get<I>(&self, index: I) -> Option<&I::Output>
335 I: ~const SliceIndex<Self>,
340 /// Returns a mutable reference to an element or subslice depending on the
341 /// type of index (see [`get`]) or `None` if the index is out of bounds.
343 /// [`get`]: slice::get
348 /// let x = &mut [0, 1, 2];
350 /// if let Some(elem) = x.get_mut(1) {
353 /// assert_eq!(x, &[0, 42, 2]);
355 #[stable(feature = "rust1", since = "1.0.0")]
356 #[rustc_const_unstable(feature = "const_slice_index", issue = "none")]
359 pub const fn get_mut<I>(&mut self, index: I) -> Option<&mut I::Output>
361 I: ~const SliceIndex<Self>,
366 /// Returns a reference to an element or subslice, without doing bounds
369 /// For a safe alternative see [`get`].
373 /// Calling this method with an out-of-bounds index is *[undefined behavior]*
374 /// even if the resulting reference is not used.
376 /// [`get`]: slice::get
377 /// [undefined behavior]: https://doc.rust-lang.org/reference/behavior-considered-undefined.html
382 /// let x = &[1, 2, 4];
385 /// assert_eq!(x.get_unchecked(1), &2);
388 #[stable(feature = "rust1", since = "1.0.0")]
389 #[rustc_const_unstable(feature = "const_slice_index", issue = "none")]
392 pub const unsafe fn get_unchecked<I>(&self, index: I) -> &I::Output
394 I: ~const SliceIndex<Self>,
396 // SAFETY: the caller must uphold most of the safety requirements for `get_unchecked`;
397 // the slice is dereferenceable because `self` is a safe reference.
398 // The returned pointer is safe because impls of `SliceIndex` have to guarantee that it is.
399 unsafe { &*index.get_unchecked(self) }
402 /// Returns a mutable reference to an element or subslice, without doing
405 /// For a safe alternative see [`get_mut`].
409 /// Calling this method with an out-of-bounds index is *[undefined behavior]*
410 /// even if the resulting reference is not used.
412 /// [`get_mut`]: slice::get_mut
413 /// [undefined behavior]: https://doc.rust-lang.org/reference/behavior-considered-undefined.html
418 /// let x = &mut [1, 2, 4];
421 /// let elem = x.get_unchecked_mut(1);
424 /// assert_eq!(x, &[1, 13, 4]);
426 #[stable(feature = "rust1", since = "1.0.0")]
427 #[rustc_const_unstable(feature = "const_slice_index", issue = "none")]
430 pub const unsafe fn get_unchecked_mut<I>(&mut self, index: I) -> &mut I::Output
432 I: ~const SliceIndex<Self>,
434 // SAFETY: the caller must uphold the safety requirements for `get_unchecked_mut`;
435 // the slice is dereferenceable because `self` is a safe reference.
436 // The returned pointer is safe because impls of `SliceIndex` have to guarantee that it is.
437 unsafe { &mut *index.get_unchecked_mut(self) }
440 /// Returns a raw pointer to the slice's buffer.
442 /// The caller must ensure that the slice outlives the pointer this
443 /// function returns, or else it will end up pointing to garbage.
445 /// The caller must also ensure that the memory the pointer (non-transitively) points to
446 /// is never written to (except inside an `UnsafeCell`) using this pointer or any pointer
447 /// derived from it. If you need to mutate the contents of the slice, use [`as_mut_ptr`].
449 /// Modifying the container referenced by this slice may cause its buffer
450 /// to be reallocated, which would also make any pointers to it invalid.
455 /// let x = &[1, 2, 4];
456 /// let x_ptr = x.as_ptr();
459 /// for i in 0..x.len() {
460 /// assert_eq!(x.get_unchecked(i), &*x_ptr.add(i));
465 /// [`as_mut_ptr`]: slice::as_mut_ptr
466 #[stable(feature = "rust1", since = "1.0.0")]
467 #[rustc_const_stable(feature = "const_slice_as_ptr", since = "1.32.0")]
470 pub const fn as_ptr(&self) -> *const T {
471 self as *const [T] as *const T
474 /// Returns an unsafe mutable pointer to the slice's buffer.
476 /// The caller must ensure that the slice outlives the pointer this
477 /// function returns, or else it will end up pointing to garbage.
479 /// Modifying the container referenced by this slice may cause its buffer
480 /// to be reallocated, which would also make any pointers to it invalid.
485 /// let x = &mut [1, 2, 4];
486 /// let x_ptr = x.as_mut_ptr();
489 /// for i in 0..x.len() {
490 /// *x_ptr.add(i) += 2;
493 /// assert_eq!(x, &[3, 4, 6]);
495 #[stable(feature = "rust1", since = "1.0.0")]
496 #[rustc_const_stable(feature = "const_ptr_offset", since = "1.61.0")]
497 #[rustc_allow_const_fn_unstable(const_mut_refs)]
500 pub const fn as_mut_ptr(&mut self) -> *mut T {
501 self as *mut [T] as *mut T
504 /// Returns the two raw pointers spanning the slice.
506 /// The returned range is half-open, which means that the end pointer
507 /// points *one past* the last element of the slice. This way, an empty
508 /// slice is represented by two equal pointers, and the difference between
509 /// the two pointers represents the size of the slice.
511 /// See [`as_ptr`] for warnings on using these pointers. The end pointer
512 /// requires extra caution, as it does not point to a valid element in the
515 /// This function is useful for interacting with foreign interfaces which
516 /// use two pointers to refer to a range of elements in memory, as is
519 /// It can also be useful to check if a pointer to an element refers to an
520 /// element of this slice:
523 /// let a = [1, 2, 3];
524 /// let x = &a[1] as *const _;
525 /// let y = &5 as *const _;
527 /// assert!(a.as_ptr_range().contains(&x));
528 /// assert!(!a.as_ptr_range().contains(&y));
531 /// [`as_ptr`]: slice::as_ptr
532 #[stable(feature = "slice_ptr_range", since = "1.48.0")]
533 #[rustc_const_stable(feature = "const_ptr_offset", since = "1.61.0")]
536 pub const fn as_ptr_range(&self) -> Range<*const T> {
537 let start = self.as_ptr();
538 // SAFETY: The `add` here is safe, because:
540 // - Both pointers are part of the same object, as pointing directly
541 // past the object also counts.
543 // - The size of the slice is never larger than isize::MAX bytes, as
545 // - https://github.com/rust-lang/unsafe-code-guidelines/issues/102#issuecomment-473340447
546 // - https://doc.rust-lang.org/reference/behavior-considered-undefined.html
547 // - https://doc.rust-lang.org/core/slice/fn.from_raw_parts.html#safety
548 // (This doesn't seem normative yet, but the very same assumption is
549 // made in many places, including the Index implementation of slices.)
551 // - There is no wrapping around involved, as slices do not wrap past
552 // the end of the address space.
554 // See the documentation of pointer::add.
555 let end = unsafe { start.add(self.len()) };
559 /// Returns the two unsafe mutable pointers spanning the slice.
561 /// The returned range is half-open, which means that the end pointer
562 /// points *one past* the last element of the slice. This way, an empty
563 /// slice is represented by two equal pointers, and the difference between
564 /// the two pointers represents the size of the slice.
566 /// See [`as_mut_ptr`] for warnings on using these pointers. The end
567 /// pointer requires extra caution, as it does not point to a valid element
570 /// This function is useful for interacting with foreign interfaces which
571 /// use two pointers to refer to a range of elements in memory, as is
574 /// [`as_mut_ptr`]: slice::as_mut_ptr
575 #[stable(feature = "slice_ptr_range", since = "1.48.0")]
576 #[rustc_const_stable(feature = "const_ptr_offset", since = "1.61.0")]
577 #[rustc_allow_const_fn_unstable(const_mut_refs)]
580 pub const fn as_mut_ptr_range(&mut self) -> Range<*mut T> {
581 let start = self.as_mut_ptr();
582 // SAFETY: See as_ptr_range() above for why `add` here is safe.
583 let end = unsafe { start.add(self.len()) };
587 /// Swaps two elements in the slice.
591 /// * a - The index of the first element
592 /// * b - The index of the second element
596 /// Panics if `a` or `b` are out of bounds.
601 /// let mut v = ["a", "b", "c", "d", "e"];
603 /// assert!(v == ["a", "b", "e", "d", "c"]);
605 #[stable(feature = "rust1", since = "1.0.0")]
606 #[rustc_const_unstable(feature = "const_swap", issue = "83163")]
609 pub const fn swap(&mut self, a: usize, b: usize) {
610 // FIXME: use swap_unchecked here (https://github.com/rust-lang/rust/pull/88540#issuecomment-944344343)
611 // Can't take two mutable loans from one vector, so instead use raw pointers.
612 let pa = ptr::addr_of_mut!(self[a]);
613 let pb = ptr::addr_of_mut!(self[b]);
614 // SAFETY: `pa` and `pb` have been created from safe mutable references and refer
615 // to elements in the slice and therefore are guaranteed to be valid and aligned.
616 // Note that accessing the elements behind `a` and `b` is checked and will
617 // panic when out of bounds.
623 /// Swaps two elements in the slice, without doing bounds checking.
625 /// For a safe alternative see [`swap`].
629 /// * a - The index of the first element
630 /// * b - The index of the second element
634 /// Calling this method with an out-of-bounds index is *[undefined behavior]*.
635 /// The caller has to ensure that `a < self.len()` and `b < self.len()`.
640 /// #![feature(slice_swap_unchecked)]
642 /// let mut v = ["a", "b", "c", "d"];
643 /// // SAFETY: we know that 1 and 3 are both indices of the slice
644 /// unsafe { v.swap_unchecked(1, 3) };
645 /// assert!(v == ["a", "d", "c", "b"]);
648 /// [`swap`]: slice::swap
649 /// [undefined behavior]: https://doc.rust-lang.org/reference/behavior-considered-undefined.html
650 #[unstable(feature = "slice_swap_unchecked", issue = "88539")]
651 #[rustc_const_unstable(feature = "const_swap", issue = "83163")]
652 pub const unsafe fn swap_unchecked(&mut self, a: usize, b: usize) {
654 let ptr = this.as_mut_ptr();
655 // SAFETY: caller has to guarantee that `a < self.len()` and `b < self.len()`
657 assert_unsafe_precondition!(
658 "slice::swap_unchecked requires that the indices are within the slice",
659 [T](a: usize, b: usize, this: &mut [T]) => a < this.len() && b < this.len()
661 ptr::swap(ptr.add(a), ptr.add(b));
665 /// Reverses the order of elements in the slice, in place.
670 /// let mut v = [1, 2, 3];
672 /// assert!(v == [3, 2, 1]);
674 #[stable(feature = "rust1", since = "1.0.0")]
675 #[rustc_const_unstable(feature = "const_reverse", issue = "100784")]
677 pub const fn reverse(&mut self) {
678 let half_len = self.len() / 2;
679 let Range { start, end } = self.as_mut_ptr_range();
681 // These slices will skip the middle item for an odd length,
682 // since that one doesn't need to move.
683 let (front_half, back_half) =
684 // SAFETY: Both are subparts of the original slice, so the memory
685 // range is valid, and they don't overlap because they're each only
686 // half (or less) of the original slice.
689 slice::from_raw_parts_mut(start, half_len),
690 slice::from_raw_parts_mut(end.sub(half_len), half_len),
694 // Introducing a function boundary here means that the two halves
695 // get `noalias` markers, allowing better optimization as LLVM
696 // knows that they're disjoint, unlike in the original slice.
697 revswap(front_half, back_half, half_len);
700 const fn revswap<T>(a: &mut [T], b: &mut [T], n: usize) {
701 debug_assert!(a.len() == n);
702 debug_assert!(b.len() == n);
704 // Because this function is first compiled in isolation,
705 // this check tells LLVM that the indexing below is
706 // in-bounds. Then after inlining -- once the actual
707 // lengths of the slices are known -- it's removed.
708 let (a, b) = (&mut a[..n], &mut b[..n]);
712 mem::swap(&mut a[i], &mut b[n - 1 - i]);
718 /// Returns an iterator over the slice.
720 /// The iterator yields all items from start to end.
725 /// let x = &[1, 2, 4];
726 /// let mut iterator = x.iter();
728 /// assert_eq!(iterator.next(), Some(&1));
729 /// assert_eq!(iterator.next(), Some(&2));
730 /// assert_eq!(iterator.next(), Some(&4));
731 /// assert_eq!(iterator.next(), None);
733 #[stable(feature = "rust1", since = "1.0.0")]
735 pub fn iter(&self) -> Iter<'_, T> {
739 /// Returns an iterator that allows modifying each value.
741 /// The iterator yields all items from start to end.
746 /// let x = &mut [1, 2, 4];
747 /// for elem in x.iter_mut() {
750 /// assert_eq!(x, &[3, 4, 6]);
752 #[stable(feature = "rust1", since = "1.0.0")]
754 pub fn iter_mut(&mut self) -> IterMut<'_, T> {
758 /// Returns an iterator over all contiguous windows of length
759 /// `size`. The windows overlap. If the slice is shorter than
760 /// `size`, the iterator returns no values.
764 /// Panics if `size` is 0.
769 /// let slice = ['r', 'u', 's', 't'];
770 /// let mut iter = slice.windows(2);
771 /// assert_eq!(iter.next().unwrap(), &['r', 'u']);
772 /// assert_eq!(iter.next().unwrap(), &['u', 's']);
773 /// assert_eq!(iter.next().unwrap(), &['s', 't']);
774 /// assert!(iter.next().is_none());
777 /// If the slice is shorter than `size`:
780 /// let slice = ['f', 'o', 'o'];
781 /// let mut iter = slice.windows(4);
782 /// assert!(iter.next().is_none());
784 #[stable(feature = "rust1", since = "1.0.0")]
786 pub fn windows(&self, size: usize) -> Windows<'_, T> {
787 let size = NonZeroUsize::new(size).expect("size is zero");
788 Windows::new(self, size)
791 /// Returns an iterator over `chunk_size` elements of the slice at a time, starting at the
792 /// beginning of the slice.
794 /// The chunks are slices and do not overlap. If `chunk_size` does not divide the length of the
795 /// slice, then the last chunk will not have length `chunk_size`.
797 /// See [`chunks_exact`] for a variant of this iterator that returns chunks of always exactly
798 /// `chunk_size` elements, and [`rchunks`] for the same iterator but starting at the end of the
803 /// Panics if `chunk_size` is 0.
808 /// let slice = ['l', 'o', 'r', 'e', 'm'];
809 /// let mut iter = slice.chunks(2);
810 /// assert_eq!(iter.next().unwrap(), &['l', 'o']);
811 /// assert_eq!(iter.next().unwrap(), &['r', 'e']);
812 /// assert_eq!(iter.next().unwrap(), &['m']);
813 /// assert!(iter.next().is_none());
816 /// [`chunks_exact`]: slice::chunks_exact
817 /// [`rchunks`]: slice::rchunks
818 #[stable(feature = "rust1", since = "1.0.0")]
820 pub fn chunks(&self, chunk_size: usize) -> Chunks<'_, T> {
821 assert_ne!(chunk_size, 0, "chunks cannot have a size of zero");
822 Chunks::new(self, chunk_size)
825 /// Returns an iterator over `chunk_size` elements of the slice at a time, starting at the
826 /// beginning of the slice.
828 /// The chunks are mutable slices, and do not overlap. If `chunk_size` does not divide the
829 /// length of the slice, then the last chunk will not have length `chunk_size`.
831 /// See [`chunks_exact_mut`] for a variant of this iterator that returns chunks of always
832 /// exactly `chunk_size` elements, and [`rchunks_mut`] for the same iterator but starting at
833 /// the end of the slice.
837 /// Panics if `chunk_size` is 0.
842 /// let v = &mut [0, 0, 0, 0, 0];
843 /// let mut count = 1;
845 /// for chunk in v.chunks_mut(2) {
846 /// for elem in chunk.iter_mut() {
851 /// assert_eq!(v, &[1, 1, 2, 2, 3]);
854 /// [`chunks_exact_mut`]: slice::chunks_exact_mut
855 /// [`rchunks_mut`]: slice::rchunks_mut
856 #[stable(feature = "rust1", since = "1.0.0")]
858 pub fn chunks_mut(&mut self, chunk_size: usize) -> ChunksMut<'_, T> {
859 assert_ne!(chunk_size, 0, "chunks cannot have a size of zero");
860 ChunksMut::new(self, chunk_size)
863 /// Returns an iterator over `chunk_size` elements of the slice at a time, starting at the
864 /// beginning of the slice.
866 /// The chunks are slices and do not overlap. If `chunk_size` does not divide the length of the
867 /// slice, then the last up to `chunk_size-1` elements will be omitted and can be retrieved
868 /// from the `remainder` function of the iterator.
870 /// Due to each chunk having exactly `chunk_size` elements, the compiler can often optimize the
871 /// resulting code better than in the case of [`chunks`].
873 /// See [`chunks`] for a variant of this iterator that also returns the remainder as a smaller
874 /// chunk, and [`rchunks_exact`] for the same iterator but starting at the end of the slice.
878 /// Panics if `chunk_size` is 0.
883 /// let slice = ['l', 'o', 'r', 'e', 'm'];
884 /// let mut iter = slice.chunks_exact(2);
885 /// assert_eq!(iter.next().unwrap(), &['l', 'o']);
886 /// assert_eq!(iter.next().unwrap(), &['r', 'e']);
887 /// assert!(iter.next().is_none());
888 /// assert_eq!(iter.remainder(), &['m']);
891 /// [`chunks`]: slice::chunks
892 /// [`rchunks_exact`]: slice::rchunks_exact
893 #[stable(feature = "chunks_exact", since = "1.31.0")]
895 pub fn chunks_exact(&self, chunk_size: usize) -> ChunksExact<'_, T> {
896 assert_ne!(chunk_size, 0);
897 ChunksExact::new(self, chunk_size)
900 /// Returns an iterator over `chunk_size` elements of the slice at a time, starting at the
901 /// beginning of the slice.
903 /// The chunks are mutable slices, and do not overlap. If `chunk_size` does not divide the
904 /// length of the slice, then the last up to `chunk_size-1` elements will be omitted and can be
905 /// retrieved from the `into_remainder` function of the iterator.
907 /// Due to each chunk having exactly `chunk_size` elements, the compiler can often optimize the
908 /// resulting code better than in the case of [`chunks_mut`].
910 /// See [`chunks_mut`] for a variant of this iterator that also returns the remainder as a
911 /// smaller chunk, and [`rchunks_exact_mut`] for the same iterator but starting at the end of
916 /// Panics if `chunk_size` is 0.
921 /// let v = &mut [0, 0, 0, 0, 0];
922 /// let mut count = 1;
924 /// for chunk in v.chunks_exact_mut(2) {
925 /// for elem in chunk.iter_mut() {
930 /// assert_eq!(v, &[1, 1, 2, 2, 0]);
933 /// [`chunks_mut`]: slice::chunks_mut
934 /// [`rchunks_exact_mut`]: slice::rchunks_exact_mut
935 #[stable(feature = "chunks_exact", since = "1.31.0")]
937 pub fn chunks_exact_mut(&mut self, chunk_size: usize) -> ChunksExactMut<'_, T> {
938 assert_ne!(chunk_size, 0);
939 ChunksExactMut::new(self, chunk_size)
942 /// Splits the slice into a slice of `N`-element arrays,
943 /// assuming that there's no remainder.
947 /// This may only be called when
948 /// - The slice splits exactly into `N`-element chunks (aka `self.len() % N == 0`).
954 /// #![feature(slice_as_chunks)]
955 /// let slice: &[char] = &['l', 'o', 'r', 'e', 'm', '!'];
956 /// let chunks: &[[char; 1]] =
957 /// // SAFETY: 1-element chunks never have remainder
958 /// unsafe { slice.as_chunks_unchecked() };
959 /// assert_eq!(chunks, &[['l'], ['o'], ['r'], ['e'], ['m'], ['!']]);
960 /// let chunks: &[[char; 3]] =
961 /// // SAFETY: The slice length (6) is a multiple of 3
962 /// unsafe { slice.as_chunks_unchecked() };
963 /// assert_eq!(chunks, &[['l', 'o', 'r'], ['e', 'm', '!']]);
965 /// // These would be unsound:
966 /// // let chunks: &[[_; 5]] = slice.as_chunks_unchecked() // The slice length is not a multiple of 5
967 /// // let chunks: &[[_; 0]] = slice.as_chunks_unchecked() // Zero-length chunks are never allowed
969 #[unstable(feature = "slice_as_chunks", issue = "74985")]
972 pub unsafe fn as_chunks_unchecked<const N: usize>(&self) -> &[[T; N]] {
974 // SAFETY: Caller must guarantee that `N` is nonzero and exactly divides the slice length
975 let new_len = unsafe {
976 assert_unsafe_precondition!(
977 "slice::as_chunks_unchecked requires `N != 0` and the slice to split exactly into `N`-element chunks",
978 [T](this: &[T], N: usize) => N != 0 && this.len() % N == 0
980 exact_div(self.len(), N)
982 // SAFETY: We cast a slice of `new_len * N` elements into
983 // a slice of `new_len` many `N` elements chunks.
984 unsafe { from_raw_parts(self.as_ptr().cast(), new_len) }
987 /// Splits the slice into a slice of `N`-element arrays,
988 /// starting at the beginning of the slice,
989 /// and a remainder slice with length strictly less than `N`.
993 /// Panics if `N` is 0. This check will most probably get changed to a compile time
994 /// error before this method gets stabilized.
999 /// #![feature(slice_as_chunks)]
1000 /// let slice = ['l', 'o', 'r', 'e', 'm'];
1001 /// let (chunks, remainder) = slice.as_chunks();
1002 /// assert_eq!(chunks, &[['l', 'o'], ['r', 'e']]);
1003 /// assert_eq!(remainder, &['m']);
1006 /// If you expect the slice to be an exact multiple, you can combine
1007 /// `let`-`else` with an empty slice pattern:
1009 /// #![feature(slice_as_chunks)]
1010 /// let slice = ['R', 'u', 's', 't'];
1011 /// let (chunks, []) = slice.as_chunks::<2>() else {
1012 /// panic!("slice didn't have even length")
1014 /// assert_eq!(chunks, &[['R', 'u'], ['s', 't']]);
1016 #[unstable(feature = "slice_as_chunks", issue = "74985")]
1019 pub fn as_chunks<const N: usize>(&self) -> (&[[T; N]], &[T]) {
1021 let len = self.len() / N;
1022 let (multiple_of_n, remainder) = self.split_at(len * N);
1023 // SAFETY: We already panicked for zero, and ensured by construction
1024 // that the length of the subslice is a multiple of N.
1025 let array_slice = unsafe { multiple_of_n.as_chunks_unchecked() };
1026 (array_slice, remainder)
1029 /// Splits the slice into a slice of `N`-element arrays,
1030 /// starting at the end of the slice,
1031 /// and a remainder slice with length strictly less than `N`.
1035 /// Panics if `N` is 0. This check will most probably get changed to a compile time
1036 /// error before this method gets stabilized.
1041 /// #![feature(slice_as_chunks)]
1042 /// let slice = ['l', 'o', 'r', 'e', 'm'];
1043 /// let (remainder, chunks) = slice.as_rchunks();
1044 /// assert_eq!(remainder, &['l']);
1045 /// assert_eq!(chunks, &[['o', 'r'], ['e', 'm']]);
1047 #[unstable(feature = "slice_as_chunks", issue = "74985")]
1050 pub fn as_rchunks<const N: usize>(&self) -> (&[T], &[[T; N]]) {
1052 let len = self.len() / N;
1053 let (remainder, multiple_of_n) = self.split_at(self.len() - len * N);
1054 // SAFETY: We already panicked for zero, and ensured by construction
1055 // that the length of the subslice is a multiple of N.
1056 let array_slice = unsafe { multiple_of_n.as_chunks_unchecked() };
1057 (remainder, array_slice)
1060 /// Returns an iterator over `N` elements of the slice at a time, starting at the
1061 /// beginning of the slice.
1063 /// The chunks are array references and do not overlap. If `N` does not divide the
1064 /// length of the slice, then the last up to `N-1` elements will be omitted and can be
1065 /// retrieved from the `remainder` function of the iterator.
1067 /// This method is the const generic equivalent of [`chunks_exact`].
1071 /// Panics if `N` is 0. This check will most probably get changed to a compile time
1072 /// error before this method gets stabilized.
1077 /// #![feature(array_chunks)]
1078 /// let slice = ['l', 'o', 'r', 'e', 'm'];
1079 /// let mut iter = slice.array_chunks();
1080 /// assert_eq!(iter.next().unwrap(), &['l', 'o']);
1081 /// assert_eq!(iter.next().unwrap(), &['r', 'e']);
1082 /// assert!(iter.next().is_none());
1083 /// assert_eq!(iter.remainder(), &['m']);
1086 /// [`chunks_exact`]: slice::chunks_exact
1087 #[unstable(feature = "array_chunks", issue = "74985")]
1089 pub fn array_chunks<const N: usize>(&self) -> ArrayChunks<'_, T, N> {
1091 ArrayChunks::new(self)
1094 /// Splits the slice into a slice of `N`-element arrays,
1095 /// assuming that there's no remainder.
1099 /// This may only be called when
1100 /// - The slice splits exactly into `N`-element chunks (aka `self.len() % N == 0`).
1106 /// #![feature(slice_as_chunks)]
1107 /// let slice: &mut [char] = &mut ['l', 'o', 'r', 'e', 'm', '!'];
1108 /// let chunks: &mut [[char; 1]] =
1109 /// // SAFETY: 1-element chunks never have remainder
1110 /// unsafe { slice.as_chunks_unchecked_mut() };
1111 /// chunks[0] = ['L'];
1112 /// assert_eq!(chunks, &[['L'], ['o'], ['r'], ['e'], ['m'], ['!']]);
1113 /// let chunks: &mut [[char; 3]] =
1114 /// // SAFETY: The slice length (6) is a multiple of 3
1115 /// unsafe { slice.as_chunks_unchecked_mut() };
1116 /// chunks[1] = ['a', 'x', '?'];
1117 /// assert_eq!(slice, &['L', 'o', 'r', 'a', 'x', '?']);
1119 /// // These would be unsound:
1120 /// // let chunks: &[[_; 5]] = slice.as_chunks_unchecked_mut() // The slice length is not a multiple of 5
1121 /// // let chunks: &[[_; 0]] = slice.as_chunks_unchecked_mut() // Zero-length chunks are never allowed
1123 #[unstable(feature = "slice_as_chunks", issue = "74985")]
1126 pub unsafe fn as_chunks_unchecked_mut<const N: usize>(&mut self) -> &mut [[T; N]] {
1128 // SAFETY: Caller must guarantee that `N` is nonzero and exactly divides the slice length
1129 let new_len = unsafe {
1130 assert_unsafe_precondition!(
1131 "slice::as_chunks_unchecked_mut requires `N != 0` and the slice to split exactly into `N`-element chunks",
1132 [T](this: &[T], N: usize) => N != 0 && this.len() % N == 0
1134 exact_div(this.len(), N)
1136 // SAFETY: We cast a slice of `new_len * N` elements into
1137 // a slice of `new_len` many `N` elements chunks.
1138 unsafe { from_raw_parts_mut(self.as_mut_ptr().cast(), new_len) }
1141 /// Splits the slice into a slice of `N`-element arrays,
1142 /// starting at the beginning of the slice,
1143 /// and a remainder slice with length strictly less than `N`.
1147 /// Panics if `N` is 0. This check will most probably get changed to a compile time
1148 /// error before this method gets stabilized.
1153 /// #![feature(slice_as_chunks)]
1154 /// let v = &mut [0, 0, 0, 0, 0];
1155 /// let mut count = 1;
1157 /// let (chunks, remainder) = v.as_chunks_mut();
1158 /// remainder[0] = 9;
1159 /// for chunk in chunks {
1160 /// *chunk = [count; 2];
1163 /// assert_eq!(v, &[1, 1, 2, 2, 9]);
1165 #[unstable(feature = "slice_as_chunks", issue = "74985")]
1168 pub fn as_chunks_mut<const N: usize>(&mut self) -> (&mut [[T; N]], &mut [T]) {
1170 let len = self.len() / N;
1171 let (multiple_of_n, remainder) = self.split_at_mut(len * N);
1172 // SAFETY: We already panicked for zero, and ensured by construction
1173 // that the length of the subslice is a multiple of N.
1174 let array_slice = unsafe { multiple_of_n.as_chunks_unchecked_mut() };
1175 (array_slice, remainder)
1178 /// Splits the slice into a slice of `N`-element arrays,
1179 /// starting at the end of the slice,
1180 /// and a remainder slice with length strictly less than `N`.
1184 /// Panics if `N` is 0. This check will most probably get changed to a compile time
1185 /// error before this method gets stabilized.
1190 /// #![feature(slice_as_chunks)]
1191 /// let v = &mut [0, 0, 0, 0, 0];
1192 /// let mut count = 1;
1194 /// let (remainder, chunks) = v.as_rchunks_mut();
1195 /// remainder[0] = 9;
1196 /// for chunk in chunks {
1197 /// *chunk = [count; 2];
1200 /// assert_eq!(v, &[9, 1, 1, 2, 2]);
1202 #[unstable(feature = "slice_as_chunks", issue = "74985")]
1205 pub fn as_rchunks_mut<const N: usize>(&mut self) -> (&mut [T], &mut [[T; N]]) {
1207 let len = self.len() / N;
1208 let (remainder, multiple_of_n) = self.split_at_mut(self.len() - len * N);
1209 // SAFETY: We already panicked for zero, and ensured by construction
1210 // that the length of the subslice is a multiple of N.
1211 let array_slice = unsafe { multiple_of_n.as_chunks_unchecked_mut() };
1212 (remainder, array_slice)
1215 /// Returns an iterator over `N` elements of the slice at a time, starting at the
1216 /// beginning of the slice.
1218 /// The chunks are mutable array references and do not overlap. If `N` does not divide
1219 /// the length of the slice, then the last up to `N-1` elements will be omitted and
1220 /// can be retrieved from the `into_remainder` function of the iterator.
1222 /// This method is the const generic equivalent of [`chunks_exact_mut`].
1226 /// Panics if `N` is 0. This check will most probably get changed to a compile time
1227 /// error before this method gets stabilized.
1232 /// #![feature(array_chunks)]
1233 /// let v = &mut [0, 0, 0, 0, 0];
1234 /// let mut count = 1;
1236 /// for chunk in v.array_chunks_mut() {
1237 /// *chunk = [count; 2];
1240 /// assert_eq!(v, &[1, 1, 2, 2, 0]);
1243 /// [`chunks_exact_mut`]: slice::chunks_exact_mut
1244 #[unstable(feature = "array_chunks", issue = "74985")]
1246 pub fn array_chunks_mut<const N: usize>(&mut self) -> ArrayChunksMut<'_, T, N> {
1248 ArrayChunksMut::new(self)
1251 /// Returns an iterator over overlapping windows of `N` elements of a slice,
1252 /// starting at the beginning of the slice.
1254 /// This is the const generic equivalent of [`windows`].
1256 /// If `N` is greater than the size of the slice, it will return no windows.
1260 /// Panics if `N` is 0. This check will most probably get changed to a compile time
1261 /// error before this method gets stabilized.
1266 /// #![feature(array_windows)]
1267 /// let slice = [0, 1, 2, 3];
1268 /// let mut iter = slice.array_windows();
1269 /// assert_eq!(iter.next().unwrap(), &[0, 1]);
1270 /// assert_eq!(iter.next().unwrap(), &[1, 2]);
1271 /// assert_eq!(iter.next().unwrap(), &[2, 3]);
1272 /// assert!(iter.next().is_none());
1275 /// [`windows`]: slice::windows
1276 #[unstable(feature = "array_windows", issue = "75027")]
1278 pub fn array_windows<const N: usize>(&self) -> ArrayWindows<'_, T, N> {
1280 ArrayWindows::new(self)
1283 /// Returns an iterator over `chunk_size` elements of the slice at a time, starting at the end
1286 /// The chunks are slices and do not overlap. If `chunk_size` does not divide the length of the
1287 /// slice, then the last chunk will not have length `chunk_size`.
1289 /// See [`rchunks_exact`] for a variant of this iterator that returns chunks of always exactly
1290 /// `chunk_size` elements, and [`chunks`] for the same iterator but starting at the beginning
1295 /// Panics if `chunk_size` is 0.
1300 /// let slice = ['l', 'o', 'r', 'e', 'm'];
1301 /// let mut iter = slice.rchunks(2);
1302 /// assert_eq!(iter.next().unwrap(), &['e', 'm']);
1303 /// assert_eq!(iter.next().unwrap(), &['o', 'r']);
1304 /// assert_eq!(iter.next().unwrap(), &['l']);
1305 /// assert!(iter.next().is_none());
1308 /// [`rchunks_exact`]: slice::rchunks_exact
1309 /// [`chunks`]: slice::chunks
1310 #[stable(feature = "rchunks", since = "1.31.0")]
1312 pub fn rchunks(&self, chunk_size: usize) -> RChunks<'_, T> {
1313 assert!(chunk_size != 0);
1314 RChunks::new(self, chunk_size)
1317 /// Returns an iterator over `chunk_size` elements of the slice at a time, starting at the end
1320 /// The chunks are mutable slices, and do not overlap. If `chunk_size` does not divide the
1321 /// length of the slice, then the last chunk will not have length `chunk_size`.
1323 /// See [`rchunks_exact_mut`] for a variant of this iterator that returns chunks of always
1324 /// exactly `chunk_size` elements, and [`chunks_mut`] for the same iterator but starting at the
1325 /// beginning of the slice.
1329 /// Panics if `chunk_size` is 0.
1334 /// let v = &mut [0, 0, 0, 0, 0];
1335 /// let mut count = 1;
1337 /// for chunk in v.rchunks_mut(2) {
1338 /// for elem in chunk.iter_mut() {
1343 /// assert_eq!(v, &[3, 2, 2, 1, 1]);
1346 /// [`rchunks_exact_mut`]: slice::rchunks_exact_mut
1347 /// [`chunks_mut`]: slice::chunks_mut
1348 #[stable(feature = "rchunks", since = "1.31.0")]
1350 pub fn rchunks_mut(&mut self, chunk_size: usize) -> RChunksMut<'_, T> {
1351 assert!(chunk_size != 0);
1352 RChunksMut::new(self, chunk_size)
1355 /// Returns an iterator over `chunk_size` elements of the slice at a time, starting at the
1356 /// end of the slice.
1358 /// The chunks are slices and do not overlap. If `chunk_size` does not divide the length of the
1359 /// slice, then the last up to `chunk_size-1` elements will be omitted and can be retrieved
1360 /// from the `remainder` function of the iterator.
1362 /// Due to each chunk having exactly `chunk_size` elements, the compiler can often optimize the
1363 /// resulting code better than in the case of [`rchunks`].
1365 /// See [`rchunks`] for a variant of this iterator that also returns the remainder as a smaller
1366 /// chunk, and [`chunks_exact`] for the same iterator but starting at the beginning of the
1371 /// Panics if `chunk_size` is 0.
1376 /// let slice = ['l', 'o', 'r', 'e', 'm'];
1377 /// let mut iter = slice.rchunks_exact(2);
1378 /// assert_eq!(iter.next().unwrap(), &['e', 'm']);
1379 /// assert_eq!(iter.next().unwrap(), &['o', 'r']);
1380 /// assert!(iter.next().is_none());
1381 /// assert_eq!(iter.remainder(), &['l']);
1384 /// [`chunks`]: slice::chunks
1385 /// [`rchunks`]: slice::rchunks
1386 /// [`chunks_exact`]: slice::chunks_exact
1387 #[stable(feature = "rchunks", since = "1.31.0")]
1389 pub fn rchunks_exact(&self, chunk_size: usize) -> RChunksExact<'_, T> {
1390 assert!(chunk_size != 0);
1391 RChunksExact::new(self, chunk_size)
1394 /// Returns an iterator over `chunk_size` elements of the slice at a time, starting at the end
1397 /// The chunks are mutable slices, and do not overlap. If `chunk_size` does not divide the
1398 /// length of the slice, then the last up to `chunk_size-1` elements will be omitted and can be
1399 /// retrieved from the `into_remainder` function of the iterator.
1401 /// Due to each chunk having exactly `chunk_size` elements, the compiler can often optimize the
1402 /// resulting code better than in the case of [`chunks_mut`].
1404 /// See [`rchunks_mut`] for a variant of this iterator that also returns the remainder as a
1405 /// smaller chunk, and [`chunks_exact_mut`] for the same iterator but starting at the beginning
1410 /// Panics if `chunk_size` is 0.
1415 /// let v = &mut [0, 0, 0, 0, 0];
1416 /// let mut count = 1;
1418 /// for chunk in v.rchunks_exact_mut(2) {
1419 /// for elem in chunk.iter_mut() {
1424 /// assert_eq!(v, &[0, 2, 2, 1, 1]);
1427 /// [`chunks_mut`]: slice::chunks_mut
1428 /// [`rchunks_mut`]: slice::rchunks_mut
1429 /// [`chunks_exact_mut`]: slice::chunks_exact_mut
1430 #[stable(feature = "rchunks", since = "1.31.0")]
1432 pub fn rchunks_exact_mut(&mut self, chunk_size: usize) -> RChunksExactMut<'_, T> {
1433 assert!(chunk_size != 0);
1434 RChunksExactMut::new(self, chunk_size)
1437 /// Returns an iterator over the slice producing non-overlapping runs
1438 /// of elements using the predicate to separate them.
1440 /// The predicate is called on two elements following themselves,
1441 /// it means the predicate is called on `slice[0]` and `slice[1]`
1442 /// then on `slice[1]` and `slice[2]` and so on.
1447 /// #![feature(slice_group_by)]
1449 /// let slice = &[1, 1, 1, 3, 3, 2, 2, 2];
1451 /// let mut iter = slice.group_by(|a, b| a == b);
1453 /// assert_eq!(iter.next(), Some(&[1, 1, 1][..]));
1454 /// assert_eq!(iter.next(), Some(&[3, 3][..]));
1455 /// assert_eq!(iter.next(), Some(&[2, 2, 2][..]));
1456 /// assert_eq!(iter.next(), None);
1459 /// This method can be used to extract the sorted subslices:
1462 /// #![feature(slice_group_by)]
1464 /// let slice = &[1, 1, 2, 3, 2, 3, 2, 3, 4];
1466 /// let mut iter = slice.group_by(|a, b| a <= b);
1468 /// assert_eq!(iter.next(), Some(&[1, 1, 2, 3][..]));
1469 /// assert_eq!(iter.next(), Some(&[2, 3][..]));
1470 /// assert_eq!(iter.next(), Some(&[2, 3, 4][..]));
1471 /// assert_eq!(iter.next(), None);
1473 #[unstable(feature = "slice_group_by", issue = "80552")]
1475 pub fn group_by<F>(&self, pred: F) -> GroupBy<'_, T, F>
1477 F: FnMut(&T, &T) -> bool,
1479 GroupBy::new(self, pred)
1482 /// Returns an iterator over the slice producing non-overlapping mutable
1483 /// runs of elements using the predicate to separate them.
1485 /// The predicate is called on two elements following themselves,
1486 /// it means the predicate is called on `slice[0]` and `slice[1]`
1487 /// then on `slice[1]` and `slice[2]` and so on.
1492 /// #![feature(slice_group_by)]
1494 /// let slice = &mut [1, 1, 1, 3, 3, 2, 2, 2];
1496 /// let mut iter = slice.group_by_mut(|a, b| a == b);
1498 /// assert_eq!(iter.next(), Some(&mut [1, 1, 1][..]));
1499 /// assert_eq!(iter.next(), Some(&mut [3, 3][..]));
1500 /// assert_eq!(iter.next(), Some(&mut [2, 2, 2][..]));
1501 /// assert_eq!(iter.next(), None);
1504 /// This method can be used to extract the sorted subslices:
1507 /// #![feature(slice_group_by)]
1509 /// let slice = &mut [1, 1, 2, 3, 2, 3, 2, 3, 4];
1511 /// let mut iter = slice.group_by_mut(|a, b| a <= b);
1513 /// assert_eq!(iter.next(), Some(&mut [1, 1, 2, 3][..]));
1514 /// assert_eq!(iter.next(), Some(&mut [2, 3][..]));
1515 /// assert_eq!(iter.next(), Some(&mut [2, 3, 4][..]));
1516 /// assert_eq!(iter.next(), None);
1518 #[unstable(feature = "slice_group_by", issue = "80552")]
1520 pub fn group_by_mut<F>(&mut self, pred: F) -> GroupByMut<'_, T, F>
1522 F: FnMut(&T, &T) -> bool,
1524 GroupByMut::new(self, pred)
1527 /// Divides one slice into two at an index.
1529 /// The first will contain all indices from `[0, mid)` (excluding
1530 /// the index `mid` itself) and the second will contain all
1531 /// indices from `[mid, len)` (excluding the index `len` itself).
1535 /// Panics if `mid > len`.
1540 /// let v = [1, 2, 3, 4, 5, 6];
1543 /// let (left, right) = v.split_at(0);
1544 /// assert_eq!(left, []);
1545 /// assert_eq!(right, [1, 2, 3, 4, 5, 6]);
1549 /// let (left, right) = v.split_at(2);
1550 /// assert_eq!(left, [1, 2]);
1551 /// assert_eq!(right, [3, 4, 5, 6]);
1555 /// let (left, right) = v.split_at(6);
1556 /// assert_eq!(left, [1, 2, 3, 4, 5, 6]);
1557 /// assert_eq!(right, []);
1560 #[stable(feature = "rust1", since = "1.0.0")]
1561 #[rustc_const_unstable(feature = "const_slice_split_at_not_mut", issue = "101158")]
1565 pub const fn split_at(&self, mid: usize) -> (&[T], &[T]) {
1566 assert!(mid <= self.len());
1567 // SAFETY: `[ptr; mid]` and `[mid; len]` are inside `self`, which
1568 // fulfills the requirements of `split_at_unchecked`.
1569 unsafe { self.split_at_unchecked(mid) }
1572 /// Divides one mutable slice into two at an index.
1574 /// The first will contain all indices from `[0, mid)` (excluding
1575 /// the index `mid` itself) and the second will contain all
1576 /// indices from `[mid, len)` (excluding the index `len` itself).
1580 /// Panics if `mid > len`.
1585 /// let mut v = [1, 0, 3, 0, 5, 6];
1586 /// let (left, right) = v.split_at_mut(2);
1587 /// assert_eq!(left, [1, 0]);
1588 /// assert_eq!(right, [3, 0, 5, 6]);
1591 /// assert_eq!(v, [1, 2, 3, 4, 5, 6]);
1593 #[stable(feature = "rust1", since = "1.0.0")]
1597 #[rustc_const_unstable(feature = "const_slice_split_at_mut", issue = "101804")]
1598 pub const fn split_at_mut(&mut self, mid: usize) -> (&mut [T], &mut [T]) {
1599 assert!(mid <= self.len());
1600 // SAFETY: `[ptr; mid]` and `[mid; len]` are inside `self`, which
1601 // fulfills the requirements of `from_raw_parts_mut`.
1602 unsafe { self.split_at_mut_unchecked(mid) }
1605 /// Divides one slice into two at an index, without doing bounds checking.
1607 /// The first will contain all indices from `[0, mid)` (excluding
1608 /// the index `mid` itself) and the second will contain all
1609 /// indices from `[mid, len)` (excluding the index `len` itself).
1611 /// For a safe alternative see [`split_at`].
1615 /// Calling this method with an out-of-bounds index is *[undefined behavior]*
1616 /// even if the resulting reference is not used. The caller has to ensure that
1617 /// `0 <= mid <= self.len()`.
1619 /// [`split_at`]: slice::split_at
1620 /// [undefined behavior]: https://doc.rust-lang.org/reference/behavior-considered-undefined.html
1625 /// #![feature(slice_split_at_unchecked)]
1627 /// let v = [1, 2, 3, 4, 5, 6];
1630 /// let (left, right) = v.split_at_unchecked(0);
1631 /// assert_eq!(left, []);
1632 /// assert_eq!(right, [1, 2, 3, 4, 5, 6]);
1636 /// let (left, right) = v.split_at_unchecked(2);
1637 /// assert_eq!(left, [1, 2]);
1638 /// assert_eq!(right, [3, 4, 5, 6]);
1642 /// let (left, right) = v.split_at_unchecked(6);
1643 /// assert_eq!(left, [1, 2, 3, 4, 5, 6]);
1644 /// assert_eq!(right, []);
1647 #[unstable(feature = "slice_split_at_unchecked", reason = "new API", issue = "76014")]
1648 #[rustc_const_unstable(feature = "slice_split_at_unchecked", issue = "76014")]
1651 pub const unsafe fn split_at_unchecked(&self, mid: usize) -> (&[T], &[T]) {
1652 // HACK: the const function `from_raw_parts` is used to make this
1653 // function const; previously the implementation used
1654 // `(self.get_unchecked(..mid), self.get_unchecked(mid..))`
1656 let len = self.len();
1657 let ptr = self.as_ptr();
1659 // SAFETY: Caller has to check that `0 <= mid <= self.len()`
1660 unsafe { (from_raw_parts(ptr, mid), from_raw_parts(ptr.add(mid), len - mid)) }
1663 /// Divides one mutable slice into two at an index, without doing bounds checking.
1665 /// The first will contain all indices from `[0, mid)` (excluding
1666 /// the index `mid` itself) and the second will contain all
1667 /// indices from `[mid, len)` (excluding the index `len` itself).
1669 /// For a safe alternative see [`split_at_mut`].
1673 /// Calling this method with an out-of-bounds index is *[undefined behavior]*
1674 /// even if the resulting reference is not used. The caller has to ensure that
1675 /// `0 <= mid <= self.len()`.
1677 /// [`split_at_mut`]: slice::split_at_mut
1678 /// [undefined behavior]: https://doc.rust-lang.org/reference/behavior-considered-undefined.html
1683 /// #![feature(slice_split_at_unchecked)]
1685 /// let mut v = [1, 0, 3, 0, 5, 6];
1686 /// // scoped to restrict the lifetime of the borrows
1688 /// let (left, right) = v.split_at_mut_unchecked(2);
1689 /// assert_eq!(left, [1, 0]);
1690 /// assert_eq!(right, [3, 0, 5, 6]);
1694 /// assert_eq!(v, [1, 2, 3, 4, 5, 6]);
1696 #[unstable(feature = "slice_split_at_unchecked", reason = "new API", issue = "76014")]
1697 #[rustc_const_unstable(feature = "const_slice_split_at_mut", issue = "101804")]
1700 pub const unsafe fn split_at_mut_unchecked(&mut self, mid: usize) -> (&mut [T], &mut [T]) {
1701 let len = self.len();
1702 let ptr = self.as_mut_ptr();
1704 // SAFETY: Caller has to check that `0 <= mid <= self.len()`.
1706 // `[ptr; mid]` and `[mid; len]` are not overlapping, so returning a mutable reference
1709 assert_unsafe_precondition!(
1710 "slice::split_at_mut_unchecked requires the index to be within the slice",
1711 (mid: usize, len: usize) => mid <= len
1713 (from_raw_parts_mut(ptr, mid), from_raw_parts_mut(ptr.add(mid), len - mid))
1717 /// Divides one slice into an array and a remainder slice at an index.
1719 /// The array will contain all indices from `[0, N)` (excluding
1720 /// the index `N` itself) and the slice will contain all
1721 /// indices from `[N, len)` (excluding the index `len` itself).
1725 /// Panics if `N > len`.
1730 /// #![feature(split_array)]
1732 /// let v = &[1, 2, 3, 4, 5, 6][..];
1735 /// let (left, right) = v.split_array_ref::<0>();
1736 /// assert_eq!(left, &[]);
1737 /// assert_eq!(right, [1, 2, 3, 4, 5, 6]);
1741 /// let (left, right) = v.split_array_ref::<2>();
1742 /// assert_eq!(left, &[1, 2]);
1743 /// assert_eq!(right, [3, 4, 5, 6]);
1747 /// let (left, right) = v.split_array_ref::<6>();
1748 /// assert_eq!(left, &[1, 2, 3, 4, 5, 6]);
1749 /// assert_eq!(right, []);
1752 #[unstable(feature = "split_array", reason = "new API", issue = "90091")]
1756 pub fn split_array_ref<const N: usize>(&self) -> (&[T; N], &[T]) {
1757 let (a, b) = self.split_at(N);
1758 // SAFETY: a points to [T; N]? Yes it's [T] of length N (checked by split_at)
1759 unsafe { (&*(a.as_ptr() as *const [T; N]), b) }
1762 /// Divides one mutable slice into an array and a remainder slice at an index.
1764 /// The array will contain all indices from `[0, N)` (excluding
1765 /// the index `N` itself) and the slice will contain all
1766 /// indices from `[N, len)` (excluding the index `len` itself).
1770 /// Panics if `N > len`.
1775 /// #![feature(split_array)]
1777 /// let mut v = &mut [1, 0, 3, 0, 5, 6][..];
1778 /// let (left, right) = v.split_array_mut::<2>();
1779 /// assert_eq!(left, &mut [1, 0]);
1780 /// assert_eq!(right, [3, 0, 5, 6]);
1783 /// assert_eq!(v, [1, 2, 3, 4, 5, 6]);
1785 #[unstable(feature = "split_array", reason = "new API", issue = "90091")]
1789 pub fn split_array_mut<const N: usize>(&mut self) -> (&mut [T; N], &mut [T]) {
1790 let (a, b) = self.split_at_mut(N);
1791 // SAFETY: a points to [T; N]? Yes it's [T] of length N (checked by split_at_mut)
1792 unsafe { (&mut *(a.as_mut_ptr() as *mut [T; N]), b) }
1795 /// Divides one slice into an array and a remainder slice at an index from
1798 /// The slice will contain all indices from `[0, len - N)` (excluding
1799 /// the index `len - N` itself) and the array will contain all
1800 /// indices from `[len - N, len)` (excluding the index `len` itself).
1804 /// Panics if `N > len`.
1809 /// #![feature(split_array)]
1811 /// let v = &[1, 2, 3, 4, 5, 6][..];
1814 /// let (left, right) = v.rsplit_array_ref::<0>();
1815 /// assert_eq!(left, [1, 2, 3, 4, 5, 6]);
1816 /// assert_eq!(right, &[]);
1820 /// let (left, right) = v.rsplit_array_ref::<2>();
1821 /// assert_eq!(left, [1, 2, 3, 4]);
1822 /// assert_eq!(right, &[5, 6]);
1826 /// let (left, right) = v.rsplit_array_ref::<6>();
1827 /// assert_eq!(left, []);
1828 /// assert_eq!(right, &[1, 2, 3, 4, 5, 6]);
1831 #[unstable(feature = "split_array", reason = "new API", issue = "90091")]
1834 pub fn rsplit_array_ref<const N: usize>(&self) -> (&[T], &[T; N]) {
1835 assert!(N <= self.len());
1836 let (a, b) = self.split_at(self.len() - N);
1837 // SAFETY: b points to [T; N]? Yes it's [T] of length N (checked by split_at)
1838 unsafe { (a, &*(b.as_ptr() as *const [T; N])) }
1841 /// Divides one mutable slice into an array and a remainder slice at an
1842 /// index from the end.
1844 /// The slice will contain all indices from `[0, len - N)` (excluding
1845 /// the index `N` itself) and the array will contain all
1846 /// indices from `[len - N, len)` (excluding the index `len` itself).
1850 /// Panics if `N > len`.
1855 /// #![feature(split_array)]
1857 /// let mut v = &mut [1, 0, 3, 0, 5, 6][..];
1858 /// let (left, right) = v.rsplit_array_mut::<4>();
1859 /// assert_eq!(left, [1, 0]);
1860 /// assert_eq!(right, &mut [3, 0, 5, 6]);
1863 /// assert_eq!(v, [1, 2, 3, 4, 5, 6]);
1865 #[unstable(feature = "split_array", reason = "new API", issue = "90091")]
1868 pub fn rsplit_array_mut<const N: usize>(&mut self) -> (&mut [T], &mut [T; N]) {
1869 assert!(N <= self.len());
1870 let (a, b) = self.split_at_mut(self.len() - N);
1871 // SAFETY: b points to [T; N]? Yes it's [T] of length N (checked by split_at_mut)
1872 unsafe { (a, &mut *(b.as_mut_ptr() as *mut [T; N])) }
1875 /// Returns an iterator over subslices separated by elements that match
1876 /// `pred`. The matched element is not contained in the subslices.
1881 /// let slice = [10, 40, 33, 20];
1882 /// let mut iter = slice.split(|num| num % 3 == 0);
1884 /// assert_eq!(iter.next().unwrap(), &[10, 40]);
1885 /// assert_eq!(iter.next().unwrap(), &[20]);
1886 /// assert!(iter.next().is_none());
1889 /// If the first element is matched, an empty slice will be the first item
1890 /// returned by the iterator. Similarly, if the last element in the slice
1891 /// is matched, an empty slice will be the last item returned by the
1895 /// let slice = [10, 40, 33];
1896 /// let mut iter = slice.split(|num| num % 3 == 0);
1898 /// assert_eq!(iter.next().unwrap(), &[10, 40]);
1899 /// assert_eq!(iter.next().unwrap(), &[]);
1900 /// assert!(iter.next().is_none());
1903 /// If two matched elements are directly adjacent, an empty slice will be
1904 /// present between them:
1907 /// let slice = [10, 6, 33, 20];
1908 /// let mut iter = slice.split(|num| num % 3 == 0);
1910 /// assert_eq!(iter.next().unwrap(), &[10]);
1911 /// assert_eq!(iter.next().unwrap(), &[]);
1912 /// assert_eq!(iter.next().unwrap(), &[20]);
1913 /// assert!(iter.next().is_none());
1915 #[stable(feature = "rust1", since = "1.0.0")]
1917 pub fn split<F>(&self, pred: F) -> Split<'_, T, F>
1919 F: FnMut(&T) -> bool,
1921 Split::new(self, pred)
1924 /// Returns an iterator over mutable subslices separated by elements that
1925 /// match `pred`. The matched element is not contained in the subslices.
1930 /// let mut v = [10, 40, 30, 20, 60, 50];
1932 /// for group in v.split_mut(|num| *num % 3 == 0) {
1935 /// assert_eq!(v, [1, 40, 30, 1, 60, 1]);
1937 #[stable(feature = "rust1", since = "1.0.0")]
1939 pub fn split_mut<F>(&mut self, pred: F) -> SplitMut<'_, T, F>
1941 F: FnMut(&T) -> bool,
1943 SplitMut::new(self, pred)
1946 /// Returns an iterator over subslices separated by elements that match
1947 /// `pred`. The matched element is contained in the end of the previous
1948 /// subslice as a terminator.
1953 /// let slice = [10, 40, 33, 20];
1954 /// let mut iter = slice.split_inclusive(|num| num % 3 == 0);
1956 /// assert_eq!(iter.next().unwrap(), &[10, 40, 33]);
1957 /// assert_eq!(iter.next().unwrap(), &[20]);
1958 /// assert!(iter.next().is_none());
1961 /// If the last element of the slice is matched,
1962 /// that element will be considered the terminator of the preceding slice.
1963 /// That slice will be the last item returned by the iterator.
1966 /// let slice = [3, 10, 40, 33];
1967 /// let mut iter = slice.split_inclusive(|num| num % 3 == 0);
1969 /// assert_eq!(iter.next().unwrap(), &[3]);
1970 /// assert_eq!(iter.next().unwrap(), &[10, 40, 33]);
1971 /// assert!(iter.next().is_none());
1973 #[stable(feature = "split_inclusive", since = "1.51.0")]
1975 pub fn split_inclusive<F>(&self, pred: F) -> SplitInclusive<'_, T, F>
1977 F: FnMut(&T) -> bool,
1979 SplitInclusive::new(self, pred)
1982 /// Returns an iterator over mutable subslices separated by elements that
1983 /// match `pred`. The matched element is contained in the previous
1984 /// subslice as a terminator.
1989 /// let mut v = [10, 40, 30, 20, 60, 50];
1991 /// for group in v.split_inclusive_mut(|num| *num % 3 == 0) {
1992 /// let terminator_idx = group.len()-1;
1993 /// group[terminator_idx] = 1;
1995 /// assert_eq!(v, [10, 40, 1, 20, 1, 1]);
1997 #[stable(feature = "split_inclusive", since = "1.51.0")]
1999 pub fn split_inclusive_mut<F>(&mut self, pred: F) -> SplitInclusiveMut<'_, T, F>
2001 F: FnMut(&T) -> bool,
2003 SplitInclusiveMut::new(self, pred)
2006 /// Returns an iterator over subslices separated by elements that match
2007 /// `pred`, starting at the end of the slice and working backwards.
2008 /// The matched element is not contained in the subslices.
2013 /// let slice = [11, 22, 33, 0, 44, 55];
2014 /// let mut iter = slice.rsplit(|num| *num == 0);
2016 /// assert_eq!(iter.next().unwrap(), &[44, 55]);
2017 /// assert_eq!(iter.next().unwrap(), &[11, 22, 33]);
2018 /// assert_eq!(iter.next(), None);
2021 /// As with `split()`, if the first or last element is matched, an empty
2022 /// slice will be the first (or last) item returned by the iterator.
2025 /// let v = &[0, 1, 1, 2, 3, 5, 8];
2026 /// let mut it = v.rsplit(|n| *n % 2 == 0);
2027 /// assert_eq!(it.next().unwrap(), &[]);
2028 /// assert_eq!(it.next().unwrap(), &[3, 5]);
2029 /// assert_eq!(it.next().unwrap(), &[1, 1]);
2030 /// assert_eq!(it.next().unwrap(), &[]);
2031 /// assert_eq!(it.next(), None);
2033 #[stable(feature = "slice_rsplit", since = "1.27.0")]
2035 pub fn rsplit<F>(&self, pred: F) -> RSplit<'_, T, F>
2037 F: FnMut(&T) -> bool,
2039 RSplit::new(self, pred)
2042 /// Returns an iterator over mutable subslices separated by elements that
2043 /// match `pred`, starting at the end of the slice and working
2044 /// backwards. The matched element is not contained in the subslices.
2049 /// let mut v = [100, 400, 300, 200, 600, 500];
2051 /// let mut count = 0;
2052 /// for group in v.rsplit_mut(|num| *num % 3 == 0) {
2054 /// group[0] = count;
2056 /// assert_eq!(v, [3, 400, 300, 2, 600, 1]);
2059 #[stable(feature = "slice_rsplit", since = "1.27.0")]
2061 pub fn rsplit_mut<F>(&mut self, pred: F) -> RSplitMut<'_, T, F>
2063 F: FnMut(&T) -> bool,
2065 RSplitMut::new(self, pred)
2068 /// Returns an iterator over subslices separated by elements that match
2069 /// `pred`, limited to returning at most `n` items. The matched element is
2070 /// not contained in the subslices.
2072 /// The last element returned, if any, will contain the remainder of the
2077 /// Print the slice split once by numbers divisible by 3 (i.e., `[10, 40]`,
2078 /// `[20, 60, 50]`):
2081 /// let v = [10, 40, 30, 20, 60, 50];
2083 /// for group in v.splitn(2, |num| *num % 3 == 0) {
2084 /// println!("{group:?}");
2087 #[stable(feature = "rust1", since = "1.0.0")]
2089 pub fn splitn<F>(&self, n: usize, pred: F) -> SplitN<'_, T, F>
2091 F: FnMut(&T) -> bool,
2093 SplitN::new(self.split(pred), n)
2096 /// Returns an iterator over mutable subslices separated by elements that match
2097 /// `pred`, limited to returning at most `n` items. The matched element is
2098 /// not contained in the subslices.
2100 /// The last element returned, if any, will contain the remainder of the
2106 /// let mut v = [10, 40, 30, 20, 60, 50];
2108 /// for group in v.splitn_mut(2, |num| *num % 3 == 0) {
2111 /// assert_eq!(v, [1, 40, 30, 1, 60, 50]);
2113 #[stable(feature = "rust1", since = "1.0.0")]
2115 pub fn splitn_mut<F>(&mut self, n: usize, pred: F) -> SplitNMut<'_, T, F>
2117 F: FnMut(&T) -> bool,
2119 SplitNMut::new(self.split_mut(pred), n)
2122 /// Returns an iterator over subslices separated by elements that match
2123 /// `pred` limited to returning at most `n` items. This starts at the end of
2124 /// the slice and works backwards. The matched element is not contained in
2127 /// The last element returned, if any, will contain the remainder of the
2132 /// Print the slice split once, starting from the end, by numbers divisible
2133 /// by 3 (i.e., `[50]`, `[10, 40, 30, 20]`):
2136 /// let v = [10, 40, 30, 20, 60, 50];
2138 /// for group in v.rsplitn(2, |num| *num % 3 == 0) {
2139 /// println!("{group:?}");
2142 #[stable(feature = "rust1", since = "1.0.0")]
2144 pub fn rsplitn<F>(&self, n: usize, pred: F) -> RSplitN<'_, T, F>
2146 F: FnMut(&T) -> bool,
2148 RSplitN::new(self.rsplit(pred), n)
2151 /// Returns an iterator over subslices separated by elements that match
2152 /// `pred` limited to returning at most `n` items. This starts at the end of
2153 /// the slice and works backwards. The matched element is not contained in
2156 /// The last element returned, if any, will contain the remainder of the
2162 /// let mut s = [10, 40, 30, 20, 60, 50];
2164 /// for group in s.rsplitn_mut(2, |num| *num % 3 == 0) {
2167 /// assert_eq!(s, [1, 40, 30, 20, 60, 1]);
2169 #[stable(feature = "rust1", since = "1.0.0")]
2171 pub fn rsplitn_mut<F>(&mut self, n: usize, pred: F) -> RSplitNMut<'_, T, F>
2173 F: FnMut(&T) -> bool,
2175 RSplitNMut::new(self.rsplit_mut(pred), n)
2178 /// Returns `true` if the slice contains an element with the given value.
2180 /// This operation is *O*(*n*).
2182 /// Note that if you have a sorted slice, [`binary_search`] may be faster.
2184 /// [`binary_search`]: slice::binary_search
2189 /// let v = [10, 40, 30];
2190 /// assert!(v.contains(&30));
2191 /// assert!(!v.contains(&50));
2194 /// If you do not have a `&T`, but some other value that you can compare
2195 /// with one (for example, `String` implements `PartialEq<str>`), you can
2196 /// use `iter().any`:
2199 /// let v = [String::from("hello"), String::from("world")]; // slice of `String`
2200 /// assert!(v.iter().any(|e| e == "hello")); // search with `&str`
2201 /// assert!(!v.iter().any(|e| e == "hi"));
2203 #[stable(feature = "rust1", since = "1.0.0")]
2206 pub fn contains(&self, x: &T) -> bool
2210 cmp::SliceContains::slice_contains(x, self)
2213 /// Returns `true` if `needle` is a prefix of the slice.
2218 /// let v = [10, 40, 30];
2219 /// assert!(v.starts_with(&[10]));
2220 /// assert!(v.starts_with(&[10, 40]));
2221 /// assert!(!v.starts_with(&[50]));
2222 /// assert!(!v.starts_with(&[10, 50]));
2225 /// Always returns `true` if `needle` is an empty slice:
2228 /// let v = &[10, 40, 30];
2229 /// assert!(v.starts_with(&[]));
2230 /// let v: &[u8] = &[];
2231 /// assert!(v.starts_with(&[]));
2233 #[stable(feature = "rust1", since = "1.0.0")]
2235 pub fn starts_with(&self, needle: &[T]) -> bool
2239 let n = needle.len();
2240 self.len() >= n && needle == &self[..n]
2243 /// Returns `true` if `needle` is a suffix of the slice.
2248 /// let v = [10, 40, 30];
2249 /// assert!(v.ends_with(&[30]));
2250 /// assert!(v.ends_with(&[40, 30]));
2251 /// assert!(!v.ends_with(&[50]));
2252 /// assert!(!v.ends_with(&[50, 30]));
2255 /// Always returns `true` if `needle` is an empty slice:
2258 /// let v = &[10, 40, 30];
2259 /// assert!(v.ends_with(&[]));
2260 /// let v: &[u8] = &[];
2261 /// assert!(v.ends_with(&[]));
2263 #[stable(feature = "rust1", since = "1.0.0")]
2265 pub fn ends_with(&self, needle: &[T]) -> bool
2269 let (m, n) = (self.len(), needle.len());
2270 m >= n && needle == &self[m - n..]
2273 /// Returns a subslice with the prefix removed.
2275 /// If the slice starts with `prefix`, returns the subslice after the prefix, wrapped in `Some`.
2276 /// If `prefix` is empty, simply returns the original slice.
2278 /// If the slice does not start with `prefix`, returns `None`.
2283 /// let v = &[10, 40, 30];
2284 /// assert_eq!(v.strip_prefix(&[10]), Some(&[40, 30][..]));
2285 /// assert_eq!(v.strip_prefix(&[10, 40]), Some(&[30][..]));
2286 /// assert_eq!(v.strip_prefix(&[50]), None);
2287 /// assert_eq!(v.strip_prefix(&[10, 50]), None);
2289 /// let prefix : &str = "he";
2290 /// assert_eq!(b"hello".strip_prefix(prefix.as_bytes()),
2291 /// Some(b"llo".as_ref()));
2293 #[must_use = "returns the subslice without modifying the original"]
2294 #[stable(feature = "slice_strip", since = "1.51.0")]
2295 pub fn strip_prefix<P: SlicePattern<Item = T> + ?Sized>(&self, prefix: &P) -> Option<&[T]>
2299 // This function will need rewriting if and when SlicePattern becomes more sophisticated.
2300 let prefix = prefix.as_slice();
2301 let n = prefix.len();
2302 if n <= self.len() {
2303 let (head, tail) = self.split_at(n);
2311 /// Returns a subslice with the suffix removed.
2313 /// If the slice ends with `suffix`, returns the subslice before the suffix, wrapped in `Some`.
2314 /// If `suffix` is empty, simply returns the original slice.
2316 /// If the slice does not end with `suffix`, returns `None`.
2321 /// let v = &[10, 40, 30];
2322 /// assert_eq!(v.strip_suffix(&[30]), Some(&[10, 40][..]));
2323 /// assert_eq!(v.strip_suffix(&[40, 30]), Some(&[10][..]));
2324 /// assert_eq!(v.strip_suffix(&[50]), None);
2325 /// assert_eq!(v.strip_suffix(&[50, 30]), None);
2327 #[must_use = "returns the subslice without modifying the original"]
2328 #[stable(feature = "slice_strip", since = "1.51.0")]
2329 pub fn strip_suffix<P: SlicePattern<Item = T> + ?Sized>(&self, suffix: &P) -> Option<&[T]>
2333 // This function will need rewriting if and when SlicePattern becomes more sophisticated.
2334 let suffix = suffix.as_slice();
2335 let (len, n) = (self.len(), suffix.len());
2337 let (head, tail) = self.split_at(len - n);
2345 /// Binary searches this slice for a given element.
2346 /// This behaves similarly to [`contains`] if this slice is sorted.
2348 /// If the value is found then [`Result::Ok`] is returned, containing the
2349 /// index of the matching element. If there are multiple matches, then any
2350 /// one of the matches could be returned. The index is chosen
2351 /// deterministically, but is subject to change in future versions of Rust.
2352 /// If the value is not found then [`Result::Err`] is returned, containing
2353 /// the index where a matching element could be inserted while maintaining
2356 /// See also [`binary_search_by`], [`binary_search_by_key`], and [`partition_point`].
2358 /// [`contains`]: slice::contains
2359 /// [`binary_search_by`]: slice::binary_search_by
2360 /// [`binary_search_by_key`]: slice::binary_search_by_key
2361 /// [`partition_point`]: slice::partition_point
2365 /// Looks up a series of four elements. The first is found, with a
2366 /// uniquely determined position; the second and third are not
2367 /// found; the fourth could match any position in `[1, 4]`.
2370 /// let s = [0, 1, 1, 1, 1, 2, 3, 5, 8, 13, 21, 34, 55];
2372 /// assert_eq!(s.binary_search(&13), Ok(9));
2373 /// assert_eq!(s.binary_search(&4), Err(7));
2374 /// assert_eq!(s.binary_search(&100), Err(13));
2375 /// let r = s.binary_search(&1);
2376 /// assert!(match r { Ok(1..=4) => true, _ => false, });
2379 /// If you want to find that whole *range* of matching items, rather than
2380 /// an arbitrary matching one, that can be done using [`partition_point`]:
2382 /// let s = [0, 1, 1, 1, 1, 2, 3, 5, 8, 13, 21, 34, 55];
2384 /// let low = s.partition_point(|x| x < &1);
2385 /// assert_eq!(low, 1);
2386 /// let high = s.partition_point(|x| x <= &1);
2387 /// assert_eq!(high, 5);
2388 /// let r = s.binary_search(&1);
2389 /// assert!((low..high).contains(&r.unwrap()));
2391 /// assert!(s[..low].iter().all(|&x| x < 1));
2392 /// assert!(s[low..high].iter().all(|&x| x == 1));
2393 /// assert!(s[high..].iter().all(|&x| x > 1));
2395 /// // For something not found, the "range" of equal items is empty
2396 /// assert_eq!(s.partition_point(|x| x < &11), 9);
2397 /// assert_eq!(s.partition_point(|x| x <= &11), 9);
2398 /// assert_eq!(s.binary_search(&11), Err(9));
2401 /// If you want to insert an item to a sorted vector, while maintaining
2402 /// sort order, consider using [`partition_point`]:
2405 /// let mut s = vec![0, 1, 1, 1, 1, 2, 3, 5, 8, 13, 21, 34, 55];
2407 /// let idx = s.partition_point(|&x| x < num);
2408 /// // The above is equivalent to `let idx = s.binary_search(&num).unwrap_or_else(|x| x);`
2409 /// s.insert(idx, num);
2410 /// assert_eq!(s, [0, 1, 1, 1, 1, 2, 3, 5, 8, 13, 21, 34, 42, 55]);
2412 #[stable(feature = "rust1", since = "1.0.0")]
2413 pub fn binary_search(&self, x: &T) -> Result<usize, usize>
2417 self.binary_search_by(|p| p.cmp(x))
2420 /// Binary searches this slice with a comparator function.
2421 /// This behaves similarly to [`contains`] if this slice is sorted.
2423 /// The comparator function should implement an order consistent
2424 /// with the sort order of the underlying slice, returning an
2425 /// order code that indicates whether its argument is `Less`,
2426 /// `Equal` or `Greater` the desired target.
2428 /// If the value is found then [`Result::Ok`] is returned, containing the
2429 /// index of the matching element. If there are multiple matches, then any
2430 /// one of the matches could be returned. The index is chosen
2431 /// deterministically, but is subject to change in future versions of Rust.
2432 /// If the value is not found then [`Result::Err`] is returned, containing
2433 /// the index where a matching element could be inserted while maintaining
2436 /// See also [`binary_search`], [`binary_search_by_key`], and [`partition_point`].
2438 /// [`contains`]: slice::contains
2439 /// [`binary_search`]: slice::binary_search
2440 /// [`binary_search_by_key`]: slice::binary_search_by_key
2441 /// [`partition_point`]: slice::partition_point
2445 /// Looks up a series of four elements. The first is found, with a
2446 /// uniquely determined position; the second and third are not
2447 /// found; the fourth could match any position in `[1, 4]`.
2450 /// let s = [0, 1, 1, 1, 1, 2, 3, 5, 8, 13, 21, 34, 55];
2453 /// assert_eq!(s.binary_search_by(|probe| probe.cmp(&seek)), Ok(9));
2455 /// assert_eq!(s.binary_search_by(|probe| probe.cmp(&seek)), Err(7));
2457 /// assert_eq!(s.binary_search_by(|probe| probe.cmp(&seek)), Err(13));
2459 /// let r = s.binary_search_by(|probe| probe.cmp(&seek));
2460 /// assert!(match r { Ok(1..=4) => true, _ => false, });
2462 #[stable(feature = "rust1", since = "1.0.0")]
2464 pub fn binary_search_by<'a, F>(&'a self, mut f: F) -> Result<usize, usize>
2466 F: FnMut(&'a T) -> Ordering,
2469 // - 0 <= left <= left + size = right <= self.len()
2470 // - f returns Less for everything in self[..left]
2471 // - f returns Greater for everything in self[right..]
2472 let mut size = self.len();
2474 let mut right = size;
2475 while left < right {
2476 let mid = left + size / 2;
2478 // SAFETY: the while condition means `size` is strictly positive, so
2479 // `size/2 < size`. Thus `left + size/2 < left + size`, which
2480 // coupled with the `left + size <= self.len()` invariant means
2481 // we have `left + size/2 < self.len()`, and this is in-bounds.
2482 let cmp = f(unsafe { self.get_unchecked(mid) });
2484 // The reason why we use if/else control flow rather than match
2485 // is because match reorders comparison operations, which is perf sensitive.
2486 // This is x86 asm for u8: https://rust.godbolt.org/z/8Y8Pra.
2489 } else if cmp == Greater {
2492 // SAFETY: same as the `get_unchecked` above
2493 unsafe { crate::intrinsics::assume(mid < self.len()) };
2497 size = right - left;
2500 // SAFETY: directly true from the overall invariant.
2501 // Note that this is `<=`, unlike the assume in the `Ok` path.
2502 unsafe { crate::intrinsics::assume(left <= self.len()) };
2506 /// Binary searches this slice with a key extraction function.
2507 /// This behaves similarly to [`contains`] if this slice is sorted.
2509 /// Assumes that the slice is sorted by the key, for instance with
2510 /// [`sort_by_key`] using the same key extraction function.
2512 /// If the value is found then [`Result::Ok`] is returned, containing the
2513 /// index of the matching element. If there are multiple matches, then any
2514 /// one of the matches could be returned. The index is chosen
2515 /// deterministically, but is subject to change in future versions of Rust.
2516 /// If the value is not found then [`Result::Err`] is returned, containing
2517 /// the index where a matching element could be inserted while maintaining
2520 /// See also [`binary_search`], [`binary_search_by`], and [`partition_point`].
2522 /// [`contains`]: slice::contains
2523 /// [`sort_by_key`]: slice::sort_by_key
2524 /// [`binary_search`]: slice::binary_search
2525 /// [`binary_search_by`]: slice::binary_search_by
2526 /// [`partition_point`]: slice::partition_point
2530 /// Looks up a series of four elements in a slice of pairs sorted by
2531 /// their second elements. The first is found, with a uniquely
2532 /// determined position; the second and third are not found; the
2533 /// fourth could match any position in `[1, 4]`.
2536 /// let s = [(0, 0), (2, 1), (4, 1), (5, 1), (3, 1),
2537 /// (1, 2), (2, 3), (4, 5), (5, 8), (3, 13),
2538 /// (1, 21), (2, 34), (4, 55)];
2540 /// assert_eq!(s.binary_search_by_key(&13, |&(a, b)| b), Ok(9));
2541 /// assert_eq!(s.binary_search_by_key(&4, |&(a, b)| b), Err(7));
2542 /// assert_eq!(s.binary_search_by_key(&100, |&(a, b)| b), Err(13));
2543 /// let r = s.binary_search_by_key(&1, |&(a, b)| b);
2544 /// assert!(match r { Ok(1..=4) => true, _ => false, });
2546 // Lint rustdoc::broken_intra_doc_links is allowed as `slice::sort_by_key` is
2547 // in crate `alloc`, and as such doesn't exists yet when building `core`: #74481.
2548 // This breaks links when slice is displayed in core, but changing it to use relative links
2549 // would break when the item is re-exported. So allow the core links to be broken for now.
2550 #[allow(rustdoc::broken_intra_doc_links)]
2551 #[stable(feature = "slice_binary_search_by_key", since = "1.10.0")]
2553 pub fn binary_search_by_key<'a, B, F>(&'a self, b: &B, mut f: F) -> Result<usize, usize>
2555 F: FnMut(&'a T) -> B,
2558 self.binary_search_by(|k| f(k).cmp(b))
2561 /// Sorts the slice, but might not preserve the order of equal elements.
2563 /// This sort is unstable (i.e., may reorder equal elements), in-place
2564 /// (i.e., does not allocate), and *O*(*n* \* log(*n*)) worst-case.
2566 /// # Current implementation
2568 /// The current algorithm is based on [pattern-defeating quicksort][pdqsort] by Orson Peters,
2569 /// which combines the fast average case of randomized quicksort with the fast worst case of
2570 /// heapsort, while achieving linear time on slices with certain patterns. It uses some
2571 /// randomization to avoid degenerate cases, but with a fixed seed to always provide
2572 /// deterministic behavior.
2574 /// It is typically faster than stable sorting, except in a few special cases, e.g., when the
2575 /// slice consists of several concatenated sorted sequences.
2580 /// let mut v = [-5, 4, 1, -3, 2];
2582 /// v.sort_unstable();
2583 /// assert!(v == [-5, -3, 1, 2, 4]);
2586 /// [pdqsort]: https://github.com/orlp/pdqsort
2587 #[stable(feature = "sort_unstable", since = "1.20.0")]
2589 pub fn sort_unstable(&mut self)
2593 sort::quicksort(self, T::lt);
2596 /// Sorts the slice with a comparator function, but might not preserve the order of equal
2599 /// This sort is unstable (i.e., may reorder equal elements), in-place
2600 /// (i.e., does not allocate), and *O*(*n* \* log(*n*)) worst-case.
2602 /// The comparator function must define a total ordering for the elements in the slice. If
2603 /// the ordering is not total, the order of the elements is unspecified. An order is a
2604 /// total order if it is (for all `a`, `b` and `c`):
2606 /// * total and antisymmetric: exactly one of `a < b`, `a == b` or `a > b` is true, and
2607 /// * transitive, `a < b` and `b < c` implies `a < c`. The same must hold for both `==` and `>`.
2609 /// For example, while [`f64`] doesn't implement [`Ord`] because `NaN != NaN`, we can use
2610 /// `partial_cmp` as our sort function when we know the slice doesn't contain a `NaN`.
2613 /// let mut floats = [5f64, 4.0, 1.0, 3.0, 2.0];
2614 /// floats.sort_unstable_by(|a, b| a.partial_cmp(b).unwrap());
2615 /// assert_eq!(floats, [1.0, 2.0, 3.0, 4.0, 5.0]);
2618 /// # Current implementation
2620 /// The current algorithm is based on [pattern-defeating quicksort][pdqsort] by Orson Peters,
2621 /// which combines the fast average case of randomized quicksort with the fast worst case of
2622 /// heapsort, while achieving linear time on slices with certain patterns. It uses some
2623 /// randomization to avoid degenerate cases, but with a fixed seed to always provide
2624 /// deterministic behavior.
2626 /// It is typically faster than stable sorting, except in a few special cases, e.g., when the
2627 /// slice consists of several concatenated sorted sequences.
2632 /// let mut v = [5, 4, 1, 3, 2];
2633 /// v.sort_unstable_by(|a, b| a.cmp(b));
2634 /// assert!(v == [1, 2, 3, 4, 5]);
2636 /// // reverse sorting
2637 /// v.sort_unstable_by(|a, b| b.cmp(a));
2638 /// assert!(v == [5, 4, 3, 2, 1]);
2641 /// [pdqsort]: https://github.com/orlp/pdqsort
2642 #[stable(feature = "sort_unstable", since = "1.20.0")]
2644 pub fn sort_unstable_by<F>(&mut self, mut compare: F)
2646 F: FnMut(&T, &T) -> Ordering,
2648 sort::quicksort(self, |a, b| compare(a, b) == Ordering::Less);
2651 /// Sorts the slice with a key extraction function, but might not preserve the order of equal
2654 /// This sort is unstable (i.e., may reorder equal elements), in-place
2655 /// (i.e., does not allocate), and *O*(m \* *n* \* log(*n*)) worst-case, where the key function is
2658 /// # Current implementation
2660 /// The current algorithm is based on [pattern-defeating quicksort][pdqsort] by Orson Peters,
2661 /// which combines the fast average case of randomized quicksort with the fast worst case of
2662 /// heapsort, while achieving linear time on slices with certain patterns. It uses some
2663 /// randomization to avoid degenerate cases, but with a fixed seed to always provide
2664 /// deterministic behavior.
2666 /// Due to its key calling strategy, [`sort_unstable_by_key`](#method.sort_unstable_by_key)
2667 /// is likely to be slower than [`sort_by_cached_key`](#method.sort_by_cached_key) in
2668 /// cases where the key function is expensive.
2673 /// let mut v = [-5i32, 4, 1, -3, 2];
2675 /// v.sort_unstable_by_key(|k| k.abs());
2676 /// assert!(v == [1, 2, -3, 4, -5]);
2679 /// [pdqsort]: https://github.com/orlp/pdqsort
2680 #[stable(feature = "sort_unstable", since = "1.20.0")]
2682 pub fn sort_unstable_by_key<K, F>(&mut self, mut f: F)
2687 sort::quicksort(self, |a, b| f(a).lt(&f(b)));
2690 /// Reorder the slice such that the element at `index` is at its final sorted position.
2692 /// This reordering has the additional property that any value at position `i < index` will be
2693 /// less than or equal to any value at a position `j > index`. Additionally, this reordering is
2694 /// unstable (i.e. any number of equal elements may end up at position `index`), in-place
2695 /// (i.e. does not allocate), and *O*(*n*) worst-case. This function is also/ known as "kth
2696 /// element" in other libraries. It returns a triplet of the following from the reordered slice:
2697 /// the subslice prior to `index`, the element at `index`, and the subslice after `index`;
2698 /// accordingly, the values in those two subslices will respectively all be less-than-or-equal-to
2699 /// and greater-than-or-equal-to the value of the element at `index`.
2701 /// # Current implementation
2703 /// The current algorithm is based on the quickselect portion of the same quicksort algorithm
2704 /// used for [`sort_unstable`].
2706 /// [`sort_unstable`]: slice::sort_unstable
2710 /// Panics when `index >= len()`, meaning it always panics on empty slices.
2715 /// let mut v = [-5i32, 4, 1, -3, 2];
2717 /// // Find the median
2718 /// v.select_nth_unstable(2);
2720 /// // We are only guaranteed the slice will be one of the following, based on the way we sort
2721 /// // about the specified index.
2722 /// assert!(v == [-3, -5, 1, 2, 4] ||
2723 /// v == [-5, -3, 1, 2, 4] ||
2724 /// v == [-3, -5, 1, 4, 2] ||
2725 /// v == [-5, -3, 1, 4, 2]);
2727 #[stable(feature = "slice_select_nth_unstable", since = "1.49.0")]
2729 pub fn select_nth_unstable(&mut self, index: usize) -> (&mut [T], &mut T, &mut [T])
2733 sort::partition_at_index(self, index, T::lt)
2736 /// Reorder the slice with a comparator function such that the element at `index` is at its
2737 /// final sorted position.
2739 /// This reordering has the additional property that any value at position `i < index` will be
2740 /// less than or equal to any value at a position `j > index` using the comparator function.
2741 /// Additionally, this reordering is unstable (i.e. any number of equal elements may end up at
2742 /// position `index`), in-place (i.e. does not allocate), and *O*(*n*) worst-case. This function
2743 /// is also known as "kth element" in other libraries. It returns a triplet of the following from
2744 /// the slice reordered according to the provided comparator function: the subslice prior to
2745 /// `index`, the element at `index`, and the subslice after `index`; accordingly, the values in
2746 /// those two subslices will respectively all be less-than-or-equal-to and greater-than-or-equal-to
2747 /// the value of the element at `index`.
2749 /// # Current implementation
2751 /// The current algorithm is based on the quickselect portion of the same quicksort algorithm
2752 /// used for [`sort_unstable`].
2754 /// [`sort_unstable`]: slice::sort_unstable
2758 /// Panics when `index >= len()`, meaning it always panics on empty slices.
2763 /// let mut v = [-5i32, 4, 1, -3, 2];
2765 /// // Find the median as if the slice were sorted in descending order.
2766 /// v.select_nth_unstable_by(2, |a, b| b.cmp(a));
2768 /// // We are only guaranteed the slice will be one of the following, based on the way we sort
2769 /// // about the specified index.
2770 /// assert!(v == [2, 4, 1, -5, -3] ||
2771 /// v == [2, 4, 1, -3, -5] ||
2772 /// v == [4, 2, 1, -5, -3] ||
2773 /// v == [4, 2, 1, -3, -5]);
2775 #[stable(feature = "slice_select_nth_unstable", since = "1.49.0")]
2777 pub fn select_nth_unstable_by<F>(
2781 ) -> (&mut [T], &mut T, &mut [T])
2783 F: FnMut(&T, &T) -> Ordering,
2785 sort::partition_at_index(self, index, |a: &T, b: &T| compare(a, b) == Less)
2788 /// Reorder the slice with a key extraction function such that the element at `index` is at its
2789 /// final sorted position.
2791 /// This reordering has the additional property that any value at position `i < index` will be
2792 /// less than or equal to any value at a position `j > index` using the key extraction function.
2793 /// Additionally, this reordering is unstable (i.e. any number of equal elements may end up at
2794 /// position `index`), in-place (i.e. does not allocate), and *O*(*n*) worst-case. This function
2795 /// is also known as "kth element" in other libraries. It returns a triplet of the following from
2796 /// the slice reordered according to the provided key extraction function: the subslice prior to
2797 /// `index`, the element at `index`, and the subslice after `index`; accordingly, the values in
2798 /// those two subslices will respectively all be less-than-or-equal-to and greater-than-or-equal-to
2799 /// the value of the element at `index`.
2801 /// # Current implementation
2803 /// The current algorithm is based on the quickselect portion of the same quicksort algorithm
2804 /// used for [`sort_unstable`].
2806 /// [`sort_unstable`]: slice::sort_unstable
2810 /// Panics when `index >= len()`, meaning it always panics on empty slices.
2815 /// let mut v = [-5i32, 4, 1, -3, 2];
2817 /// // Return the median as if the array were sorted according to absolute value.
2818 /// v.select_nth_unstable_by_key(2, |a| a.abs());
2820 /// // We are only guaranteed the slice will be one of the following, based on the way we sort
2821 /// // about the specified index.
2822 /// assert!(v == [1, 2, -3, 4, -5] ||
2823 /// v == [1, 2, -3, -5, 4] ||
2824 /// v == [2, 1, -3, 4, -5] ||
2825 /// v == [2, 1, -3, -5, 4]);
2827 #[stable(feature = "slice_select_nth_unstable", since = "1.49.0")]
2829 pub fn select_nth_unstable_by_key<K, F>(
2833 ) -> (&mut [T], &mut T, &mut [T])
2838 sort::partition_at_index(self, index, |a: &T, b: &T| f(a).lt(&f(b)))
2841 /// Moves all consecutive repeated elements to the end of the slice according to the
2842 /// [`PartialEq`] trait implementation.
2844 /// Returns two slices. The first contains no consecutive repeated elements.
2845 /// The second contains all the duplicates in no specified order.
2847 /// If the slice is sorted, the first returned slice contains no duplicates.
2852 /// #![feature(slice_partition_dedup)]
2854 /// let mut slice = [1, 2, 2, 3, 3, 2, 1, 1];
2856 /// let (dedup, duplicates) = slice.partition_dedup();
2858 /// assert_eq!(dedup, [1, 2, 3, 2, 1]);
2859 /// assert_eq!(duplicates, [2, 3, 1]);
2861 #[unstable(feature = "slice_partition_dedup", issue = "54279")]
2863 pub fn partition_dedup(&mut self) -> (&mut [T], &mut [T])
2867 self.partition_dedup_by(|a, b| a == b)
2870 /// Moves all but the first of consecutive elements to the end of the slice satisfying
2871 /// a given equality relation.
2873 /// Returns two slices. The first contains no consecutive repeated elements.
2874 /// The second contains all the duplicates in no specified order.
2876 /// The `same_bucket` function is passed references to two elements from the slice and
2877 /// must determine if the elements compare equal. The elements are passed in opposite order
2878 /// from their order in the slice, so if `same_bucket(a, b)` returns `true`, `a` is moved
2879 /// at the end of the slice.
2881 /// If the slice is sorted, the first returned slice contains no duplicates.
2886 /// #![feature(slice_partition_dedup)]
2888 /// let mut slice = ["foo", "Foo", "BAZ", "Bar", "bar", "baz", "BAZ"];
2890 /// let (dedup, duplicates) = slice.partition_dedup_by(|a, b| a.eq_ignore_ascii_case(b));
2892 /// assert_eq!(dedup, ["foo", "BAZ", "Bar", "baz"]);
2893 /// assert_eq!(duplicates, ["bar", "Foo", "BAZ"]);
2895 #[unstable(feature = "slice_partition_dedup", issue = "54279")]
2897 pub fn partition_dedup_by<F>(&mut self, mut same_bucket: F) -> (&mut [T], &mut [T])
2899 F: FnMut(&mut T, &mut T) -> bool,
2901 // Although we have a mutable reference to `self`, we cannot make
2902 // *arbitrary* changes. The `same_bucket` calls could panic, so we
2903 // must ensure that the slice is in a valid state at all times.
2905 // The way that we handle this is by using swaps; we iterate
2906 // over all the elements, swapping as we go so that at the end
2907 // the elements we wish to keep are in the front, and those we
2908 // wish to reject are at the back. We can then split the slice.
2909 // This operation is still `O(n)`.
2911 // Example: We start in this state, where `r` represents "next
2912 // read" and `w` represents "next_write`.
2915 // +---+---+---+---+---+---+
2916 // | 0 | 1 | 1 | 2 | 3 | 3 |
2917 // +---+---+---+---+---+---+
2920 // Comparing self[r] against self[w-1], this is not a duplicate, so
2921 // we swap self[r] and self[w] (no effect as r==w) and then increment both
2922 // r and w, leaving us with:
2925 // +---+---+---+---+---+---+
2926 // | 0 | 1 | 1 | 2 | 3 | 3 |
2927 // +---+---+---+---+---+---+
2930 // Comparing self[r] against self[w-1], this value is a duplicate,
2931 // so we increment `r` but leave everything else unchanged:
2934 // +---+---+---+---+---+---+
2935 // | 0 | 1 | 1 | 2 | 3 | 3 |
2936 // +---+---+---+---+---+---+
2939 // Comparing self[r] against self[w-1], this is not a duplicate,
2940 // so swap self[r] and self[w] and advance r and w:
2943 // +---+---+---+---+---+---+
2944 // | 0 | 1 | 2 | 1 | 3 | 3 |
2945 // +---+---+---+---+---+---+
2948 // Not a duplicate, repeat:
2951 // +---+---+---+---+---+---+
2952 // | 0 | 1 | 2 | 3 | 1 | 3 |
2953 // +---+---+---+---+---+---+
2956 // Duplicate, advance r. End of slice. Split at w.
2958 let len = self.len();
2960 return (self, &mut []);
2963 let ptr = self.as_mut_ptr();
2964 let mut next_read: usize = 1;
2965 let mut next_write: usize = 1;
2967 // SAFETY: the `while` condition guarantees `next_read` and `next_write`
2968 // are less than `len`, thus are inside `self`. `prev_ptr_write` points to
2969 // one element before `ptr_write`, but `next_write` starts at 1, so
2970 // `prev_ptr_write` is never less than 0 and is inside the slice.
2971 // This fulfils the requirements for dereferencing `ptr_read`, `prev_ptr_write`
2972 // and `ptr_write`, and for using `ptr.add(next_read)`, `ptr.add(next_write - 1)`
2973 // and `prev_ptr_write.offset(1)`.
2975 // `next_write` is also incremented at most once per loop at most meaning
2976 // no element is skipped when it may need to be swapped.
2978 // `ptr_read` and `prev_ptr_write` never point to the same element. This
2979 // is required for `&mut *ptr_read`, `&mut *prev_ptr_write` to be safe.
2980 // The explanation is simply that `next_read >= next_write` is always true,
2981 // thus `next_read > next_write - 1` is too.
2983 // Avoid bounds checks by using raw pointers.
2984 while next_read < len {
2985 let ptr_read = ptr.add(next_read);
2986 let prev_ptr_write = ptr.add(next_write - 1);
2987 if !same_bucket(&mut *ptr_read, &mut *prev_ptr_write) {
2988 if next_read != next_write {
2989 let ptr_write = prev_ptr_write.add(1);
2990 mem::swap(&mut *ptr_read, &mut *ptr_write);
2998 self.split_at_mut(next_write)
3001 /// Moves all but the first of consecutive elements to the end of the slice that resolve
3002 /// to the same key.
3004 /// Returns two slices. The first contains no consecutive repeated elements.
3005 /// The second contains all the duplicates in no specified order.
3007 /// If the slice is sorted, the first returned slice contains no duplicates.
3012 /// #![feature(slice_partition_dedup)]
3014 /// let mut slice = [10, 20, 21, 30, 30, 20, 11, 13];
3016 /// let (dedup, duplicates) = slice.partition_dedup_by_key(|i| *i / 10);
3018 /// assert_eq!(dedup, [10, 20, 30, 20, 11]);
3019 /// assert_eq!(duplicates, [21, 30, 13]);
3021 #[unstable(feature = "slice_partition_dedup", issue = "54279")]
3023 pub fn partition_dedup_by_key<K, F>(&mut self, mut key: F) -> (&mut [T], &mut [T])
3025 F: FnMut(&mut T) -> K,
3028 self.partition_dedup_by(|a, b| key(a) == key(b))
3031 /// Rotates the slice in-place such that the first `mid` elements of the
3032 /// slice move to the end while the last `self.len() - mid` elements move to
3033 /// the front. After calling `rotate_left`, the element previously at index
3034 /// `mid` will become the first element in the slice.
3038 /// This function will panic if `mid` is greater than the length of the
3039 /// slice. Note that `mid == self.len()` does _not_ panic and is a no-op
3044 /// Takes linear (in `self.len()`) time.
3049 /// let mut a = ['a', 'b', 'c', 'd', 'e', 'f'];
3050 /// a.rotate_left(2);
3051 /// assert_eq!(a, ['c', 'd', 'e', 'f', 'a', 'b']);
3054 /// Rotating a subslice:
3057 /// let mut a = ['a', 'b', 'c', 'd', 'e', 'f'];
3058 /// a[1..5].rotate_left(1);
3059 /// assert_eq!(a, ['a', 'c', 'd', 'e', 'b', 'f']);
3061 #[stable(feature = "slice_rotate", since = "1.26.0")]
3062 pub fn rotate_left(&mut self, mid: usize) {
3063 assert!(mid <= self.len());
3064 let k = self.len() - mid;
3065 let p = self.as_mut_ptr();
3067 // SAFETY: The range `[p.add(mid) - mid, p.add(mid) + k)` is trivially
3068 // valid for reading and writing, as required by `ptr_rotate`.
3070 rotate::ptr_rotate(mid, p.add(mid), k);
3074 /// Rotates the slice in-place such that the first `self.len() - k`
3075 /// elements of the slice move to the end while the last `k` elements move
3076 /// to the front. After calling `rotate_right`, the element previously at
3077 /// index `self.len() - k` will become the first element in the slice.
3081 /// This function will panic if `k` is greater than the length of the
3082 /// slice. Note that `k == self.len()` does _not_ panic and is a no-op
3087 /// Takes linear (in `self.len()`) time.
3092 /// let mut a = ['a', 'b', 'c', 'd', 'e', 'f'];
3093 /// a.rotate_right(2);
3094 /// assert_eq!(a, ['e', 'f', 'a', 'b', 'c', 'd']);
3097 /// Rotate a subslice:
3100 /// let mut a = ['a', 'b', 'c', 'd', 'e', 'f'];
3101 /// a[1..5].rotate_right(1);
3102 /// assert_eq!(a, ['a', 'e', 'b', 'c', 'd', 'f']);
3104 #[stable(feature = "slice_rotate", since = "1.26.0")]
3105 pub fn rotate_right(&mut self, k: usize) {
3106 assert!(k <= self.len());
3107 let mid = self.len() - k;
3108 let p = self.as_mut_ptr();
3110 // SAFETY: The range `[p.add(mid) - mid, p.add(mid) + k)` is trivially
3111 // valid for reading and writing, as required by `ptr_rotate`.
3113 rotate::ptr_rotate(mid, p.add(mid), k);
3117 /// Fills `self` with elements by cloning `value`.
3122 /// let mut buf = vec![0; 10];
3124 /// assert_eq!(buf, vec![1; 10]);
3126 #[doc(alias = "memset")]
3127 #[stable(feature = "slice_fill", since = "1.50.0")]
3128 pub fn fill(&mut self, value: T)
3132 specialize::SpecFill::spec_fill(self, value);
3135 /// Fills `self` with elements returned by calling a closure repeatedly.
3137 /// This method uses a closure to create new values. If you'd rather
3138 /// [`Clone`] a given value, use [`fill`]. If you want to use the [`Default`]
3139 /// trait to generate values, you can pass [`Default::default`] as the
3142 /// [`fill`]: slice::fill
3147 /// let mut buf = vec![1; 10];
3148 /// buf.fill_with(Default::default);
3149 /// assert_eq!(buf, vec![0; 10]);
3151 #[stable(feature = "slice_fill_with", since = "1.51.0")]
3152 pub fn fill_with<F>(&mut self, mut f: F)
3161 /// Copies the elements from `src` into `self`.
3163 /// The length of `src` must be the same as `self`.
3167 /// This function will panic if the two slices have different lengths.
3171 /// Cloning two elements from a slice into another:
3174 /// let src = [1, 2, 3, 4];
3175 /// let mut dst = [0, 0];
3177 /// // Because the slices have to be the same length,
3178 /// // we slice the source slice from four elements
3179 /// // to two. It will panic if we don't do this.
3180 /// dst.clone_from_slice(&src[2..]);
3182 /// assert_eq!(src, [1, 2, 3, 4]);
3183 /// assert_eq!(dst, [3, 4]);
3186 /// Rust enforces that there can only be one mutable reference with no
3187 /// immutable references to a particular piece of data in a particular
3188 /// scope. Because of this, attempting to use `clone_from_slice` on a
3189 /// single slice will result in a compile failure:
3192 /// let mut slice = [1, 2, 3, 4, 5];
3194 /// slice[..2].clone_from_slice(&slice[3..]); // compile fail!
3197 /// To work around this, we can use [`split_at_mut`] to create two distinct
3198 /// sub-slices from a slice:
3201 /// let mut slice = [1, 2, 3, 4, 5];
3204 /// let (left, right) = slice.split_at_mut(2);
3205 /// left.clone_from_slice(&right[1..]);
3208 /// assert_eq!(slice, [4, 5, 3, 4, 5]);
3211 /// [`copy_from_slice`]: slice::copy_from_slice
3212 /// [`split_at_mut`]: slice::split_at_mut
3213 #[stable(feature = "clone_from_slice", since = "1.7.0")]
3215 pub fn clone_from_slice(&mut self, src: &[T])
3219 self.spec_clone_from(src);
3222 /// Copies all elements from `src` into `self`, using a memcpy.
3224 /// The length of `src` must be the same as `self`.
3226 /// If `T` does not implement `Copy`, use [`clone_from_slice`].
3230 /// This function will panic if the two slices have different lengths.
3234 /// Copying two elements from a slice into another:
3237 /// let src = [1, 2, 3, 4];
3238 /// let mut dst = [0, 0];
3240 /// // Because the slices have to be the same length,
3241 /// // we slice the source slice from four elements
3242 /// // to two. It will panic if we don't do this.
3243 /// dst.copy_from_slice(&src[2..]);
3245 /// assert_eq!(src, [1, 2, 3, 4]);
3246 /// assert_eq!(dst, [3, 4]);
3249 /// Rust enforces that there can only be one mutable reference with no
3250 /// immutable references to a particular piece of data in a particular
3251 /// scope. Because of this, attempting to use `copy_from_slice` on a
3252 /// single slice will result in a compile failure:
3255 /// let mut slice = [1, 2, 3, 4, 5];
3257 /// slice[..2].copy_from_slice(&slice[3..]); // compile fail!
3260 /// To work around this, we can use [`split_at_mut`] to create two distinct
3261 /// sub-slices from a slice:
3264 /// let mut slice = [1, 2, 3, 4, 5];
3267 /// let (left, right) = slice.split_at_mut(2);
3268 /// left.copy_from_slice(&right[1..]);
3271 /// assert_eq!(slice, [4, 5, 3, 4, 5]);
3274 /// [`clone_from_slice`]: slice::clone_from_slice
3275 /// [`split_at_mut`]: slice::split_at_mut
3276 #[doc(alias = "memcpy")]
3277 #[stable(feature = "copy_from_slice", since = "1.9.0")]
3279 pub fn copy_from_slice(&mut self, src: &[T])
3283 // The panic code path was put into a cold function to not bloat the
3288 fn len_mismatch_fail(dst_len: usize, src_len: usize) -> ! {
3290 "source slice length ({}) does not match destination slice length ({})",
3295 if self.len() != src.len() {
3296 len_mismatch_fail(self.len(), src.len());
3299 // SAFETY: `self` is valid for `self.len()` elements by definition, and `src` was
3300 // checked to have the same length. The slices cannot overlap because
3301 // mutable references are exclusive.
3303 ptr::copy_nonoverlapping(src.as_ptr(), self.as_mut_ptr(), self.len());
3307 /// Copies elements from one part of the slice to another part of itself,
3308 /// using a memmove.
3310 /// `src` is the range within `self` to copy from. `dest` is the starting
3311 /// index of the range within `self` to copy to, which will have the same
3312 /// length as `src`. The two ranges may overlap. The ends of the two ranges
3313 /// must be less than or equal to `self.len()`.
3317 /// This function will panic if either range exceeds the end of the slice,
3318 /// or if the end of `src` is before the start.
3322 /// Copying four bytes within a slice:
3325 /// let mut bytes = *b"Hello, World!";
3327 /// bytes.copy_within(1..5, 8);
3329 /// assert_eq!(&bytes, b"Hello, Wello!");
3331 #[stable(feature = "copy_within", since = "1.37.0")]
3333 pub fn copy_within<R: RangeBounds<usize>>(&mut self, src: R, dest: usize)
3337 let Range { start: src_start, end: src_end } = slice::range(src, ..self.len());
3338 let count = src_end - src_start;
3339 assert!(dest <= self.len() - count, "dest is out of bounds");
3340 // SAFETY: the conditions for `ptr::copy` have all been checked above,
3341 // as have those for `ptr::add`.
3343 // Derive both `src_ptr` and `dest_ptr` from the same loan
3344 let ptr = self.as_mut_ptr();
3345 let src_ptr = ptr.add(src_start);
3346 let dest_ptr = ptr.add(dest);
3347 ptr::copy(src_ptr, dest_ptr, count);
3351 /// Swaps all elements in `self` with those in `other`.
3353 /// The length of `other` must be the same as `self`.
3357 /// This function will panic if the two slices have different lengths.
3361 /// Swapping two elements across slices:
3364 /// let mut slice1 = [0, 0];
3365 /// let mut slice2 = [1, 2, 3, 4];
3367 /// slice1.swap_with_slice(&mut slice2[2..]);
3369 /// assert_eq!(slice1, [3, 4]);
3370 /// assert_eq!(slice2, [1, 2, 0, 0]);
3373 /// Rust enforces that there can only be one mutable reference to a
3374 /// particular piece of data in a particular scope. Because of this,
3375 /// attempting to use `swap_with_slice` on a single slice will result in
3376 /// a compile failure:
3379 /// let mut slice = [1, 2, 3, 4, 5];
3380 /// slice[..2].swap_with_slice(&mut slice[3..]); // compile fail!
3383 /// To work around this, we can use [`split_at_mut`] to create two distinct
3384 /// mutable sub-slices from a slice:
3387 /// let mut slice = [1, 2, 3, 4, 5];
3390 /// let (left, right) = slice.split_at_mut(2);
3391 /// left.swap_with_slice(&mut right[1..]);
3394 /// assert_eq!(slice, [4, 5, 3, 1, 2]);
3397 /// [`split_at_mut`]: slice::split_at_mut
3398 #[stable(feature = "swap_with_slice", since = "1.27.0")]
3400 pub fn swap_with_slice(&mut self, other: &mut [T]) {
3401 assert!(self.len() == other.len(), "destination and source slices have different lengths");
3402 // SAFETY: `self` is valid for `self.len()` elements by definition, and `src` was
3403 // checked to have the same length. The slices cannot overlap because
3404 // mutable references are exclusive.
3406 ptr::swap_nonoverlapping(self.as_mut_ptr(), other.as_mut_ptr(), self.len());
3410 /// Function to calculate lengths of the middle and trailing slice for `align_to{,_mut}`.
3411 fn align_to_offsets<U>(&self) -> (usize, usize) {
3412 // What we gonna do about `rest` is figure out what multiple of `U`s we can put in a
3413 // lowest number of `T`s. And how many `T`s we need for each such "multiple".
3415 // Consider for example T=u8 U=u16. Then we can put 1 U in 2 Ts. Simple. Now, consider
3416 // for example a case where size_of::<T> = 16, size_of::<U> = 24. We can put 2 Us in
3417 // place of every 3 Ts in the `rest` slice. A bit more complicated.
3419 // Formula to calculate this is:
3421 // Us = lcm(size_of::<T>, size_of::<U>) / size_of::<U>
3422 // Ts = lcm(size_of::<T>, size_of::<U>) / size_of::<T>
3424 // Expanded and simplified:
3426 // Us = size_of::<T> / gcd(size_of::<T>, size_of::<U>)
3427 // Ts = size_of::<U> / gcd(size_of::<T>, size_of::<U>)
3429 // Luckily since all this is constant-evaluated... performance here matters not!
3431 fn gcd(a: usize, b: usize) -> usize {
3432 use crate::intrinsics;
3433 // iterative stein’s algorithm
3434 // We should still make this `const fn` (and revert to recursive algorithm if we do)
3435 // because relying on llvm to consteval all this is… well, it makes me uncomfortable.
3437 // SAFETY: `a` and `b` are checked to be non-zero values.
3438 let (ctz_a, mut ctz_b) = unsafe {
3445 (intrinsics::cttz_nonzero(a), intrinsics::cttz_nonzero(b))
3447 let k = ctz_a.min(ctz_b);
3448 let mut a = a >> ctz_a;
3451 // remove all factors of 2 from b
3454 mem::swap(&mut a, &mut b);
3457 // SAFETY: `b` is checked to be non-zero.
3462 ctz_b = intrinsics::cttz_nonzero(b);
3467 let gcd: usize = gcd(mem::size_of::<T>(), mem::size_of::<U>());
3468 let ts: usize = mem::size_of::<U>() / gcd;
3469 let us: usize = mem::size_of::<T>() / gcd;
3471 // Armed with this knowledge, we can find how many `U`s we can fit!
3472 let us_len = self.len() / ts * us;
3473 // And how many `T`s will be in the trailing slice!
3474 let ts_len = self.len() % ts;
3478 /// Transmute the slice to a slice of another type, ensuring alignment of the types is
3481 /// This method splits the slice into three distinct slices: prefix, correctly aligned middle
3482 /// slice of a new type, and the suffix slice. How exactly the slice is split up is not
3483 /// specified; the middle part may be smaller than necessary. However, if this fails to return a
3484 /// maximal middle part, that is because code is running in a context where performance does not
3485 /// matter, such as a sanitizer attempting to find alignment bugs. Regular code running
3486 /// in a default (debug or release) execution *will* return a maximal middle part.
3488 /// This method has no purpose when either input element `T` or output element `U` are
3489 /// zero-sized and will return the original slice without splitting anything.
3493 /// This method is essentially a `transmute` with respect to the elements in the returned
3494 /// middle slice, so all the usual caveats pertaining to `transmute::<T, U>` also apply here.
3502 /// let bytes: [u8; 7] = [1, 2, 3, 4, 5, 6, 7];
3503 /// let (prefix, shorts, suffix) = bytes.align_to::<u16>();
3504 /// // less_efficient_algorithm_for_bytes(prefix);
3505 /// // more_efficient_algorithm_for_aligned_shorts(shorts);
3506 /// // less_efficient_algorithm_for_bytes(suffix);
3509 #[stable(feature = "slice_align_to", since = "1.30.0")]
3511 pub unsafe fn align_to<U>(&self) -> (&[T], &[U], &[T]) {
3512 // Note that most of this function will be constant-evaluated,
3513 if U::IS_ZST || T::IS_ZST {
3514 // handle ZSTs specially, which is – don't handle them at all.
3515 return (self, &[], &[]);
3518 // First, find at what point do we split between the first and 2nd slice. Easy with
3519 // ptr.align_offset.
3520 let ptr = self.as_ptr();
3521 // SAFETY: See the `align_to_mut` method for the detailed safety comment.
3522 let offset = unsafe { crate::ptr::align_offset(ptr, mem::align_of::<U>()) };
3523 if offset > self.len() {
3526 let (left, rest) = self.split_at(offset);
3527 let (us_len, ts_len) = rest.align_to_offsets::<U>();
3528 // SAFETY: now `rest` is definitely aligned, so `from_raw_parts` below is okay,
3529 // since the caller guarantees that we can transmute `T` to `U` safely.
3533 from_raw_parts(rest.as_ptr() as *const U, us_len),
3534 from_raw_parts(rest.as_ptr().add(rest.len() - ts_len), ts_len),
3540 /// Transmute the mutable slice to a mutable slice of another type, ensuring alignment of the
3541 /// types is maintained.
3543 /// This method splits the slice into three distinct slices: prefix, correctly aligned middle
3544 /// slice of a new type, and the suffix slice. How exactly the slice is split up is not
3545 /// specified; the middle part may be smaller than necessary. However, if this fails to return a
3546 /// maximal middle part, that is because code is running in a context where performance does not
3547 /// matter, such as a sanitizer attempting to find alignment bugs. Regular code running
3548 /// in a default (debug or release) execution *will* return a maximal middle part.
3550 /// This method has no purpose when either input element `T` or output element `U` are
3551 /// zero-sized and will return the original slice without splitting anything.
3555 /// This method is essentially a `transmute` with respect to the elements in the returned
3556 /// middle slice, so all the usual caveats pertaining to `transmute::<T, U>` also apply here.
3564 /// let mut bytes: [u8; 7] = [1, 2, 3, 4, 5, 6, 7];
3565 /// let (prefix, shorts, suffix) = bytes.align_to_mut::<u16>();
3566 /// // less_efficient_algorithm_for_bytes(prefix);
3567 /// // more_efficient_algorithm_for_aligned_shorts(shorts);
3568 /// // less_efficient_algorithm_for_bytes(suffix);
3571 #[stable(feature = "slice_align_to", since = "1.30.0")]
3573 pub unsafe fn align_to_mut<U>(&mut self) -> (&mut [T], &mut [U], &mut [T]) {
3574 // Note that most of this function will be constant-evaluated,
3575 if U::IS_ZST || T::IS_ZST {
3576 // handle ZSTs specially, which is – don't handle them at all.
3577 return (self, &mut [], &mut []);
3580 // First, find at what point do we split between the first and 2nd slice. Easy with
3581 // ptr.align_offset.
3582 let ptr = self.as_ptr();
3583 // SAFETY: Here we are ensuring we will use aligned pointers for U for the
3584 // rest of the method. This is done by passing a pointer to &[T] with an
3585 // alignment targeted for U.
3586 // `crate::ptr::align_offset` is called with a correctly aligned and
3587 // valid pointer `ptr` (it comes from a reference to `self`) and with
3588 // a size that is a power of two (since it comes from the alignment for U),
3589 // satisfying its safety constraints.
3590 let offset = unsafe { crate::ptr::align_offset(ptr, mem::align_of::<U>()) };
3591 if offset > self.len() {
3592 (self, &mut [], &mut [])
3594 let (left, rest) = self.split_at_mut(offset);
3595 let (us_len, ts_len) = rest.align_to_offsets::<U>();
3596 let rest_len = rest.len();
3597 let mut_ptr = rest.as_mut_ptr();
3598 // We can't use `rest` again after this, that would invalidate its alias `mut_ptr`!
3599 // SAFETY: see comments for `align_to`.
3603 from_raw_parts_mut(mut_ptr as *mut U, us_len),
3604 from_raw_parts_mut(mut_ptr.add(rest_len - ts_len), ts_len),
3610 /// Split a slice into a prefix, a middle of aligned SIMD types, and a suffix.
3612 /// This is a safe wrapper around [`slice::align_to`], so has the same weak
3613 /// postconditions as that method. You're only assured that
3614 /// `self.len() == prefix.len() + middle.len() * LANES + suffix.len()`.
3616 /// Notably, all of the following are possible:
3617 /// - `prefix.len() >= LANES`.
3618 /// - `middle.is_empty()` despite `self.len() >= 3 * LANES`.
3619 /// - `suffix.len() >= LANES`.
3621 /// That said, this is a safe method, so if you're only writing safe code,
3622 /// then this can at most cause incorrect logic, not unsoundness.
3626 /// This will panic if the size of the SIMD type is different from
3627 /// `LANES` times that of the scalar.
3629 /// At the time of writing, the trait restrictions on `Simd<T, LANES>` keeps
3630 /// that from ever happening, as only power-of-two numbers of lanes are
3631 /// supported. It's possible that, in the future, those restrictions might
3632 /// be lifted in a way that would make it possible to see panics from this
3633 /// method for something like `LANES == 3`.
3638 /// #![feature(portable_simd)]
3639 /// use core::simd::SimdFloat;
3641 /// let short = &[1, 2, 3];
3642 /// let (prefix, middle, suffix) = short.as_simd::<4>();
3643 /// assert_eq!(middle, []); // Not enough elements for anything in the middle
3645 /// // They might be split in any possible way between prefix and suffix
3646 /// let it = prefix.iter().chain(suffix).copied();
3647 /// assert_eq!(it.collect::<Vec<_>>(), vec![1, 2, 3]);
3649 /// fn basic_simd_sum(x: &[f32]) -> f32 {
3650 /// use std::ops::Add;
3651 /// use std::simd::f32x4;
3652 /// let (prefix, middle, suffix) = x.as_simd();
3653 /// let sums = f32x4::from_array([
3654 /// prefix.iter().copied().sum(),
3657 /// suffix.iter().copied().sum(),
3659 /// let sums = middle.iter().copied().fold(sums, f32x4::add);
3660 /// sums.reduce_sum()
3663 /// let numbers: Vec<f32> = (1..101).map(|x| x as _).collect();
3664 /// assert_eq!(basic_simd_sum(&numbers[1..99]), 4949.0);
3666 #[unstable(feature = "portable_simd", issue = "86656")]
3668 pub fn as_simd<const LANES: usize>(&self) -> (&[T], &[Simd<T, LANES>], &[T])
3670 Simd<T, LANES>: AsRef<[T; LANES]>,
3671 T: simd::SimdElement,
3672 simd::LaneCount<LANES>: simd::SupportedLaneCount,
3674 // These are expected to always match, as vector types are laid out like
3675 // arrays per <https://llvm.org/docs/LangRef.html#vector-type>, but we
3676 // might as well double-check since it'll optimize away anyhow.
3677 assert_eq!(mem::size_of::<Simd<T, LANES>>(), mem::size_of::<[T; LANES]>());
3679 // SAFETY: The simd types have the same layout as arrays, just with
3680 // potentially-higher alignment, so the de-facto transmutes are sound.
3681 unsafe { self.align_to() }
3684 /// Split a mutable slice into a mutable prefix, a middle of aligned SIMD types,
3685 /// and a mutable suffix.
3687 /// This is a safe wrapper around [`slice::align_to_mut`], so has the same weak
3688 /// postconditions as that method. You're only assured that
3689 /// `self.len() == prefix.len() + middle.len() * LANES + suffix.len()`.
3691 /// Notably, all of the following are possible:
3692 /// - `prefix.len() >= LANES`.
3693 /// - `middle.is_empty()` despite `self.len() >= 3 * LANES`.
3694 /// - `suffix.len() >= LANES`.
3696 /// That said, this is a safe method, so if you're only writing safe code,
3697 /// then this can at most cause incorrect logic, not unsoundness.
3699 /// This is the mutable version of [`slice::as_simd`]; see that for examples.
3703 /// This will panic if the size of the SIMD type is different from
3704 /// `LANES` times that of the scalar.
3706 /// At the time of writing, the trait restrictions on `Simd<T, LANES>` keeps
3707 /// that from ever happening, as only power-of-two numbers of lanes are
3708 /// supported. It's possible that, in the future, those restrictions might
3709 /// be lifted in a way that would make it possible to see panics from this
3710 /// method for something like `LANES == 3`.
3711 #[unstable(feature = "portable_simd", issue = "86656")]
3713 pub fn as_simd_mut<const LANES: usize>(&mut self) -> (&mut [T], &mut [Simd<T, LANES>], &mut [T])
3715 Simd<T, LANES>: AsMut<[T; LANES]>,
3716 T: simd::SimdElement,
3717 simd::LaneCount<LANES>: simd::SupportedLaneCount,
3719 // These are expected to always match, as vector types are laid out like
3720 // arrays per <https://llvm.org/docs/LangRef.html#vector-type>, but we
3721 // might as well double-check since it'll optimize away anyhow.
3722 assert_eq!(mem::size_of::<Simd<T, LANES>>(), mem::size_of::<[T; LANES]>());
3724 // SAFETY: The simd types have the same layout as arrays, just with
3725 // potentially-higher alignment, so the de-facto transmutes are sound.
3726 unsafe { self.align_to_mut() }
3729 /// Checks if the elements of this slice are sorted.
3731 /// That is, for each element `a` and its following element `b`, `a <= b` must hold. If the
3732 /// slice yields exactly zero or one element, `true` is returned.
3734 /// Note that if `Self::Item` is only `PartialOrd`, but not `Ord`, the above definition
3735 /// implies that this function returns `false` if any two consecutive items are not
3741 /// #![feature(is_sorted)]
3742 /// let empty: [i32; 0] = [];
3744 /// assert!([1, 2, 2, 9].is_sorted());
3745 /// assert!(![1, 3, 2, 4].is_sorted());
3746 /// assert!([0].is_sorted());
3747 /// assert!(empty.is_sorted());
3748 /// assert!(![0.0, 1.0, f32::NAN].is_sorted());
3751 #[unstable(feature = "is_sorted", reason = "new API", issue = "53485")]
3753 pub fn is_sorted(&self) -> bool
3757 self.is_sorted_by(|a, b| a.partial_cmp(b))
3760 /// Checks if the elements of this slice are sorted using the given comparator function.
3762 /// Instead of using `PartialOrd::partial_cmp`, this function uses the given `compare`
3763 /// function to determine the ordering of two elements. Apart from that, it's equivalent to
3764 /// [`is_sorted`]; see its documentation for more information.
3766 /// [`is_sorted`]: slice::is_sorted
3767 #[unstable(feature = "is_sorted", reason = "new API", issue = "53485")]
3769 pub fn is_sorted_by<'a, F>(&'a self, mut compare: F) -> bool
3771 F: FnMut(&'a T, &'a T) -> Option<Ordering>,
3773 self.iter().is_sorted_by(|a, b| compare(*a, *b))
3776 /// Checks if the elements of this slice are sorted using the given key extraction function.
3778 /// Instead of comparing the slice's elements directly, this function compares the keys of the
3779 /// elements, as determined by `f`. Apart from that, it's equivalent to [`is_sorted`]; see its
3780 /// documentation for more information.
3782 /// [`is_sorted`]: slice::is_sorted
3787 /// #![feature(is_sorted)]
3789 /// assert!(["c", "bb", "aaa"].is_sorted_by_key(|s| s.len()));
3790 /// assert!(![-2i32, -1, 0, 3].is_sorted_by_key(|n| n.abs()));
3793 #[unstable(feature = "is_sorted", reason = "new API", issue = "53485")]
3795 pub fn is_sorted_by_key<'a, F, K>(&'a self, f: F) -> bool
3797 F: FnMut(&'a T) -> K,
3800 self.iter().is_sorted_by_key(f)
3803 /// Returns the index of the partition point according to the given predicate
3804 /// (the index of the first element of the second partition).
3806 /// The slice is assumed to be partitioned according to the given predicate.
3807 /// This means that all elements for which the predicate returns true are at the start of the slice
3808 /// and all elements for which the predicate returns false are at the end.
3809 /// For example, `[7, 15, 3, 5, 4, 12, 6]` is partitioned under the predicate `x % 2 != 0`
3810 /// (all odd numbers are at the start, all even at the end).
3812 /// If this slice is not partitioned, the returned result is unspecified and meaningless,
3813 /// as this method performs a kind of binary search.
3815 /// See also [`binary_search`], [`binary_search_by`], and [`binary_search_by_key`].
3817 /// [`binary_search`]: slice::binary_search
3818 /// [`binary_search_by`]: slice::binary_search_by
3819 /// [`binary_search_by_key`]: slice::binary_search_by_key
3824 /// let v = [1, 2, 3, 3, 5, 6, 7];
3825 /// let i = v.partition_point(|&x| x < 5);
3827 /// assert_eq!(i, 4);
3828 /// assert!(v[..i].iter().all(|&x| x < 5));
3829 /// assert!(v[i..].iter().all(|&x| !(x < 5)));
3832 /// If all elements of the slice match the predicate, including if the slice
3833 /// is empty, then the length of the slice will be returned:
3836 /// let a = [2, 4, 8];
3837 /// assert_eq!(a.partition_point(|x| x < &100), a.len());
3838 /// let a: [i32; 0] = [];
3839 /// assert_eq!(a.partition_point(|x| x < &100), 0);
3842 /// If you want to insert an item to a sorted vector, while maintaining
3846 /// let mut s = vec![0, 1, 1, 1, 1, 2, 3, 5, 8, 13, 21, 34, 55];
3848 /// let idx = s.partition_point(|&x| x < num);
3849 /// s.insert(idx, num);
3850 /// assert_eq!(s, [0, 1, 1, 1, 1, 2, 3, 5, 8, 13, 21, 34, 42, 55]);
3852 #[stable(feature = "partition_point", since = "1.52.0")]
3854 pub fn partition_point<P>(&self, mut pred: P) -> usize
3856 P: FnMut(&T) -> bool,
3858 self.binary_search_by(|x| if pred(x) { Less } else { Greater }).unwrap_or_else(|i| i)
3861 /// Removes the subslice corresponding to the given range
3862 /// and returns a reference to it.
3864 /// Returns `None` and does not modify the slice if the given
3865 /// range is out of bounds.
3867 /// Note that this method only accepts one-sided ranges such as
3868 /// `2..` or `..6`, but not `2..6`.
3872 /// Taking the first three elements of a slice:
3875 /// #![feature(slice_take)]
3877 /// let mut slice: &[_] = &['a', 'b', 'c', 'd'];
3878 /// let mut first_three = slice.take(..3).unwrap();
3880 /// assert_eq!(slice, &['d']);
3881 /// assert_eq!(first_three, &['a', 'b', 'c']);
3884 /// Taking the last two elements of a slice:
3887 /// #![feature(slice_take)]
3889 /// let mut slice: &[_] = &['a', 'b', 'c', 'd'];
3890 /// let mut tail = slice.take(2..).unwrap();
3892 /// assert_eq!(slice, &['a', 'b']);
3893 /// assert_eq!(tail, &['c', 'd']);
3896 /// Getting `None` when `range` is out of bounds:
3899 /// #![feature(slice_take)]
3901 /// let mut slice: &[_] = &['a', 'b', 'c', 'd'];
3903 /// assert_eq!(None, slice.take(5..));
3904 /// assert_eq!(None, slice.take(..5));
3905 /// assert_eq!(None, slice.take(..=4));
3906 /// let expected: &[char] = &['a', 'b', 'c', 'd'];
3907 /// assert_eq!(Some(expected), slice.take(..4));
3910 #[must_use = "method does not modify the slice if the range is out of bounds"]
3911 #[unstable(feature = "slice_take", issue = "62280")]
3912 pub fn take<'a, R: OneSidedRange<usize>>(self: &mut &'a Self, range: R) -> Option<&'a Self> {
3913 let (direction, split_index) = split_point_of(range)?;
3914 if split_index > self.len() {
3917 let (front, back) = self.split_at(split_index);
3919 Direction::Front => {
3923 Direction::Back => {
3930 /// Removes the subslice corresponding to the given range
3931 /// and returns a mutable reference to it.
3933 /// Returns `None` and does not modify the slice if the given
3934 /// range is out of bounds.
3936 /// Note that this method only accepts one-sided ranges such as
3937 /// `2..` or `..6`, but not `2..6`.
3941 /// Taking the first three elements of a slice:
3944 /// #![feature(slice_take)]
3946 /// let mut slice: &mut [_] = &mut ['a', 'b', 'c', 'd'];
3947 /// let mut first_three = slice.take_mut(..3).unwrap();
3949 /// assert_eq!(slice, &mut ['d']);
3950 /// assert_eq!(first_three, &mut ['a', 'b', 'c']);
3953 /// Taking the last two elements of a slice:
3956 /// #![feature(slice_take)]
3958 /// let mut slice: &mut [_] = &mut ['a', 'b', 'c', 'd'];
3959 /// let mut tail = slice.take_mut(2..).unwrap();
3961 /// assert_eq!(slice, &mut ['a', 'b']);
3962 /// assert_eq!(tail, &mut ['c', 'd']);
3965 /// Getting `None` when `range` is out of bounds:
3968 /// #![feature(slice_take)]
3970 /// let mut slice: &mut [_] = &mut ['a', 'b', 'c', 'd'];
3972 /// assert_eq!(None, slice.take_mut(5..));
3973 /// assert_eq!(None, slice.take_mut(..5));
3974 /// assert_eq!(None, slice.take_mut(..=4));
3975 /// let expected: &mut [_] = &mut ['a', 'b', 'c', 'd'];
3976 /// assert_eq!(Some(expected), slice.take_mut(..4));
3979 #[must_use = "method does not modify the slice if the range is out of bounds"]
3980 #[unstable(feature = "slice_take", issue = "62280")]
3981 pub fn take_mut<'a, R: OneSidedRange<usize>>(
3982 self: &mut &'a mut Self,
3984 ) -> Option<&'a mut Self> {
3985 let (direction, split_index) = split_point_of(range)?;
3986 if split_index > self.len() {
3989 let (front, back) = mem::take(self).split_at_mut(split_index);
3991 Direction::Front => {
3995 Direction::Back => {
4002 /// Removes the first element of the slice and returns a reference
4005 /// Returns `None` if the slice is empty.
4010 /// #![feature(slice_take)]
4012 /// let mut slice: &[_] = &['a', 'b', 'c'];
4013 /// let first = slice.take_first().unwrap();
4015 /// assert_eq!(slice, &['b', 'c']);
4016 /// assert_eq!(first, &'a');
4019 #[unstable(feature = "slice_take", issue = "62280")]
4020 pub fn take_first<'a>(self: &mut &'a Self) -> Option<&'a T> {
4021 let (first, rem) = self.split_first()?;
4026 /// Removes the first element of the slice and returns a mutable
4027 /// reference to it.
4029 /// Returns `None` if the slice is empty.
4034 /// #![feature(slice_take)]
4036 /// let mut slice: &mut [_] = &mut ['a', 'b', 'c'];
4037 /// let first = slice.take_first_mut().unwrap();
4040 /// assert_eq!(slice, &['b', 'c']);
4041 /// assert_eq!(first, &'d');
4044 #[unstable(feature = "slice_take", issue = "62280")]
4045 pub fn take_first_mut<'a>(self: &mut &'a mut Self) -> Option<&'a mut T> {
4046 let (first, rem) = mem::take(self).split_first_mut()?;
4051 /// Removes the last element of the slice and returns a reference
4054 /// Returns `None` if the slice is empty.
4059 /// #![feature(slice_take)]
4061 /// let mut slice: &[_] = &['a', 'b', 'c'];
4062 /// let last = slice.take_last().unwrap();
4064 /// assert_eq!(slice, &['a', 'b']);
4065 /// assert_eq!(last, &'c');
4068 #[unstable(feature = "slice_take", issue = "62280")]
4069 pub fn take_last<'a>(self: &mut &'a Self) -> Option<&'a T> {
4070 let (last, rem) = self.split_last()?;
4075 /// Removes the last element of the slice and returns a mutable
4076 /// reference to it.
4078 /// Returns `None` if the slice is empty.
4083 /// #![feature(slice_take)]
4085 /// let mut slice: &mut [_] = &mut ['a', 'b', 'c'];
4086 /// let last = slice.take_last_mut().unwrap();
4089 /// assert_eq!(slice, &['a', 'b']);
4090 /// assert_eq!(last, &'d');
4093 #[unstable(feature = "slice_take", issue = "62280")]
4094 pub fn take_last_mut<'a>(self: &mut &'a mut Self) -> Option<&'a mut T> {
4095 let (last, rem) = mem::take(self).split_last_mut()?;
4100 /// Returns mutable references to many indices at once, without doing any checks.
4102 /// For a safe alternative see [`get_many_mut`].
4106 /// Calling this method with overlapping or out-of-bounds indices is *[undefined behavior]*
4107 /// even if the resulting references are not used.
4112 /// #![feature(get_many_mut)]
4114 /// let x = &mut [1, 2, 4];
4117 /// let [a, b] = x.get_many_unchecked_mut([0, 2]);
4121 /// assert_eq!(x, &[10, 2, 400]);
4124 /// [`get_many_mut`]: slice::get_many_mut
4125 /// [undefined behavior]: https://doc.rust-lang.org/reference/behavior-considered-undefined.html
4126 #[unstable(feature = "get_many_mut", issue = "104642")]
4128 pub unsafe fn get_many_unchecked_mut<const N: usize>(
4130 indices: [usize; N],
4132 // NB: This implementation is written as it is because any variation of
4133 // `indices.map(|i| self.get_unchecked_mut(i))` would make miri unhappy,
4134 // or generate worse code otherwise. This is also why we need to go
4135 // through a raw pointer here.
4136 let slice: *mut [T] = self;
4137 let mut arr: mem::MaybeUninit<[&mut T; N]> = mem::MaybeUninit::uninit();
4138 let arr_ptr = arr.as_mut_ptr();
4140 // SAFETY: We expect `indices` to contain disjunct values that are
4141 // in bounds of `self`.
4144 let idx = *indices.get_unchecked(i);
4145 *(*arr_ptr).get_unchecked_mut(i) = &mut *slice.get_unchecked_mut(idx);
4151 /// Returns mutable references to many indices at once.
4153 /// Returns an error if any index is out-of-bounds, or if the same index was
4154 /// passed more than once.
4159 /// #![feature(get_many_mut)]
4161 /// let v = &mut [1, 2, 3];
4162 /// if let Ok([a, b]) = v.get_many_mut([0, 2]) {
4166 /// assert_eq!(v, &[413, 2, 612]);
4168 #[unstable(feature = "get_many_mut", issue = "104642")]
4170 pub fn get_many_mut<const N: usize>(
4172 indices: [usize; N],
4173 ) -> Result<[&mut T; N], GetManyMutError<N>> {
4174 if !get_many_check_valid(&indices, self.len()) {
4175 return Err(GetManyMutError { _private: () });
4177 // SAFETY: The `get_many_check_valid()` call checked that all indices
4178 // are disjunct and in bounds.
4179 unsafe { Ok(self.get_many_unchecked_mut(indices)) }
4183 impl<T, const N: usize> [[T; N]] {
4184 /// Takes a `&[[T; N]]`, and flattens it to a `&[T]`.
4188 /// This panics if the length of the resulting slice would overflow a `usize`.
4190 /// This is only possible when flattening a slice of arrays of zero-sized
4191 /// types, and thus tends to be irrelevant in practice. If
4192 /// `size_of::<T>() > 0`, this will never panic.
4197 /// #![feature(slice_flatten)]
4199 /// assert_eq!([[1, 2, 3], [4, 5, 6]].flatten(), &[1, 2, 3, 4, 5, 6]);
4202 /// [[1, 2, 3], [4, 5, 6]].flatten(),
4203 /// [[1, 2], [3, 4], [5, 6]].flatten(),
4206 /// let slice_of_empty_arrays: &[[i32; 0]] = &[[], [], [], [], []];
4207 /// assert!(slice_of_empty_arrays.flatten().is_empty());
4209 /// let empty_slice_of_arrays: &[[u32; 10]] = &[];
4210 /// assert!(empty_slice_of_arrays.flatten().is_empty());
4212 #[unstable(feature = "slice_flatten", issue = "95629")]
4213 pub fn flatten(&self) -> &[T] {
4214 let len = if T::IS_ZST {
4215 self.len().checked_mul(N).expect("slice len overflow")
4217 // SAFETY: `self.len() * N` cannot overflow because `self` is
4218 // already in the address space.
4219 unsafe { self.len().unchecked_mul(N) }
4221 // SAFETY: `[T]` is layout-identical to `[T; N]`
4222 unsafe { from_raw_parts(self.as_ptr().cast(), len) }
4225 /// Takes a `&mut [[T; N]]`, and flattens it to a `&mut [T]`.
4229 /// This panics if the length of the resulting slice would overflow a `usize`.
4231 /// This is only possible when flattening a slice of arrays of zero-sized
4232 /// types, and thus tends to be irrelevant in practice. If
4233 /// `size_of::<T>() > 0`, this will never panic.
4238 /// #![feature(slice_flatten)]
4240 /// fn add_5_to_all(slice: &mut [i32]) {
4241 /// for i in slice {
4246 /// let mut array = [[1, 2, 3], [4, 5, 6], [7, 8, 9]];
4247 /// add_5_to_all(array.flatten_mut());
4248 /// assert_eq!(array, [[6, 7, 8], [9, 10, 11], [12, 13, 14]]);
4250 #[unstable(feature = "slice_flatten", issue = "95629")]
4251 pub fn flatten_mut(&mut self) -> &mut [T] {
4252 let len = if T::IS_ZST {
4253 self.len().checked_mul(N).expect("slice len overflow")
4255 // SAFETY: `self.len() * N` cannot overflow because `self` is
4256 // already in the address space.
4257 unsafe { self.len().unchecked_mul(N) }
4259 // SAFETY: `[T]` is layout-identical to `[T; N]`
4260 unsafe { from_raw_parts_mut(self.as_mut_ptr().cast(), len) }
4266 /// Sorts the slice of floats.
4268 /// This sort is in-place (i.e. does not allocate), *O*(*n* \* log(*n*)) worst-case, and uses
4269 /// the ordering defined by [`f32::total_cmp`].
4271 /// # Current implementation
4273 /// This uses the same sorting algorithm as [`sort_unstable_by`](slice::sort_unstable_by).
4278 /// #![feature(sort_floats)]
4279 /// let mut v = [2.6, -5e-8, f32::NAN, 8.29, f32::INFINITY, -1.0, 0.0, -f32::INFINITY, -0.0];
4281 /// v.sort_floats();
4282 /// let sorted = [-f32::INFINITY, -1.0, -5e-8, -0.0, 0.0, 2.6, 8.29, f32::INFINITY, f32::NAN];
4283 /// assert_eq!(&v[..8], &sorted[..8]);
4284 /// assert!(v[8].is_nan());
4286 #[unstable(feature = "sort_floats", issue = "93396")]
4288 pub fn sort_floats(&mut self) {
4289 self.sort_unstable_by(f32::total_cmp);
4295 /// Sorts the slice of floats.
4297 /// This sort is in-place (i.e. does not allocate), *O*(*n* \* log(*n*)) worst-case, and uses
4298 /// the ordering defined by [`f64::total_cmp`].
4300 /// # Current implementation
4302 /// This uses the same sorting algorithm as [`sort_unstable_by`](slice::sort_unstable_by).
4307 /// #![feature(sort_floats)]
4308 /// let mut v = [2.6, -5e-8, f64::NAN, 8.29, f64::INFINITY, -1.0, 0.0, -f64::INFINITY, -0.0];
4310 /// v.sort_floats();
4311 /// let sorted = [-f64::INFINITY, -1.0, -5e-8, -0.0, 0.0, 2.6, 8.29, f64::INFINITY, f64::NAN];
4312 /// assert_eq!(&v[..8], &sorted[..8]);
4313 /// assert!(v[8].is_nan());
4315 #[unstable(feature = "sort_floats", issue = "93396")]
4317 pub fn sort_floats(&mut self) {
4318 self.sort_unstable_by(f64::total_cmp);
4322 trait CloneFromSpec<T> {
4323 fn spec_clone_from(&mut self, src: &[T]);
4326 impl<T> CloneFromSpec<T> for [T]
4331 default fn spec_clone_from(&mut self, src: &[T]) {
4332 assert!(self.len() == src.len(), "destination and source slices have different lengths");
4333 // NOTE: We need to explicitly slice them to the same length
4334 // to make it easier for the optimizer to elide bounds checking.
4335 // But since it can't be relied on we also have an explicit specialization for T: Copy.
4336 let len = self.len();
4337 let src = &src[..len];
4339 self[i].clone_from(&src[i]);
4344 impl<T> CloneFromSpec<T> for [T]
4349 fn spec_clone_from(&mut self, src: &[T]) {
4350 self.copy_from_slice(src);
4354 #[stable(feature = "rust1", since = "1.0.0")]
4355 #[rustc_const_unstable(feature = "const_default_impls", issue = "87864")]
4356 impl<T> const Default for &[T] {
4357 /// Creates an empty slice.
4358 fn default() -> Self {
4363 #[stable(feature = "mut_slice_default", since = "1.5.0")]
4364 #[rustc_const_unstable(feature = "const_default_impls", issue = "87864")]
4365 impl<T> const Default for &mut [T] {
4366 /// Creates a mutable empty slice.
4367 fn default() -> Self {
4372 #[unstable(feature = "slice_pattern", reason = "stopgap trait for slice patterns", issue = "56345")]
4373 /// Patterns in slices - currently, only used by `strip_prefix` and `strip_suffix`. At a future
4374 /// point, we hope to generalise `core::str::Pattern` (which at the time of writing is limited to
4375 /// `str`) to slices, and then this trait will be replaced or abolished.
4376 pub trait SlicePattern {
4377 /// The element type of the slice being matched on.
4380 /// Currently, the consumers of `SlicePattern` need a slice.
4381 fn as_slice(&self) -> &[Self::Item];
4384 #[stable(feature = "slice_strip", since = "1.51.0")]
4385 impl<T> SlicePattern for [T] {
4389 fn as_slice(&self) -> &[Self::Item] {
4394 #[stable(feature = "slice_strip", since = "1.51.0")]
4395 impl<T, const N: usize> SlicePattern for [T; N] {
4399 fn as_slice(&self) -> &[Self::Item] {
4404 /// This checks every index against each other, and against `len`.
4406 /// This will do `binomial(N + 1, 2) = N * (N + 1) / 2 = 0, 1, 3, 6, 10, ..`
4407 /// comparison operations.
4408 fn get_many_check_valid<const N: usize>(indices: &[usize; N], len: usize) -> bool {
4409 // NB: The optimzer should inline the loops into a sequence
4410 // of instructions without additional branching.
4411 let mut valid = true;
4412 for (i, &idx) in indices.iter().enumerate() {
4414 for &idx2 in &indices[..i] {
4415 valid &= idx != idx2;
4421 /// The error type returned by [`get_many_mut<N>`][`slice::get_many_mut`].
4423 /// It indicates one of two possible errors:
4424 /// - An index is out-of-bounds.
4425 /// - The same index appeared multiple times in the array.
4430 /// #![feature(get_many_mut)]
4432 /// let v = &mut [1, 2, 3];
4433 /// assert!(v.get_many_mut([0, 999]).is_err());
4434 /// assert!(v.get_many_mut([1, 1]).is_err());
4436 #[unstable(feature = "get_many_mut", issue = "104642")]
4437 // NB: The N here is there to be forward-compatible with adding more details
4438 // to the error type at a later point
4439 pub struct GetManyMutError<const N: usize> {
4443 #[unstable(feature = "get_many_mut", issue = "104642")]
4444 impl<const N: usize> fmt::Debug for GetManyMutError<N> {
4445 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
4446 f.debug_struct("GetManyMutError").finish_non_exhaustive()
4450 #[unstable(feature = "get_many_mut", issue = "104642")]
4451 impl<const N: usize> fmt::Display for GetManyMutError<N> {
4452 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
4453 fmt::Display::fmt("an index is out of bounds or appeared multiple times in the array", f)