1 // ignore-tidy-filelength
3 //! Slice management and manipulation.
5 //! For more details see [`std::slice`].
7 //! [`std::slice`]: ../../std/slice/index.html
9 #![stable(feature = "rust1", since = "1.0.0")]
11 use crate::cmp::Ordering::{self, Equal, Greater, Less};
12 use crate::marker::Copy;
14 use crate::ops::{FnMut, Range, RangeBounds};
15 use crate::option::Option;
16 use crate::option::Option::{None, Some};
18 use crate::result::Result;
19 use crate::result::Result::{Err, Ok};
22 feature = "slice_internals",
24 reason = "exposed from core to be reused in std; use the memchr crate"
26 /// Pure rust memchr implementation, taken from rust-memchr
37 #[stable(feature = "rust1", since = "1.0.0")]
38 pub use iter::{Chunks, ChunksMut, Windows};
39 #[stable(feature = "rust1", since = "1.0.0")]
40 pub use iter::{Iter, IterMut};
41 #[stable(feature = "rust1", since = "1.0.0")]
42 pub use iter::{RSplitN, RSplitNMut, Split, SplitMut, SplitN, SplitNMut};
44 #[stable(feature = "slice_rsplit", since = "1.27.0")]
45 pub use iter::{RSplit, RSplitMut};
47 #[stable(feature = "chunks_exact", since = "1.31.0")]
48 pub use iter::{ChunksExact, ChunksExactMut};
50 #[stable(feature = "rchunks", since = "1.31.0")]
51 pub use iter::{RChunks, RChunksExact, RChunksExactMut, RChunksMut};
53 #[unstable(feature = "array_chunks", issue = "74985")]
54 pub use iter::{ArrayChunks, ArrayChunksMut};
56 #[unstable(feature = "array_windows", issue = "75027")]
57 pub use iter::ArrayWindows;
59 #[unstable(feature = "split_inclusive", issue = "72360")]
60 pub use iter::{SplitInclusive, SplitInclusiveMut};
62 #[stable(feature = "rust1", since = "1.0.0")]
63 pub use raw::{from_raw_parts, from_raw_parts_mut};
65 #[stable(feature = "from_ref", since = "1.28.0")]
66 pub use raw::{from_mut, from_ref};
68 // This function is public only because there is no other way to unit test heapsort.
69 #[unstable(feature = "sort_internals", reason = "internal to sort module", issue = "none")]
70 pub use sort::heapsort;
72 #[stable(feature = "slice_get_slice", since = "1.28.0")]
73 pub use index::SliceIndex;
75 #[unstable(feature = "slice_check_range", issue = "76393")]
76 pub use index::check_range;
81 /// Returns the number of elements in the slice.
86 /// let a = [1, 2, 3];
87 /// assert_eq!(a.len(), 3);
89 #[stable(feature = "rust1", since = "1.0.0")]
90 #[rustc_const_stable(feature = "const_slice_len", since = "1.32.0")]
92 // SAFETY: const sound because we transmute out the length field as a usize (which it must be)
93 #[allow_internal_unstable(const_fn_union)]
94 pub const fn len(&self) -> usize {
95 // SAFETY: this is safe because `&[T]` and `FatPtr<T>` have the same layout.
96 // Only `std` can make this guarantee.
97 unsafe { crate::ptr::Repr { rust: self }.raw.len }
100 /// Returns `true` if the slice has a length of 0.
105 /// let a = [1, 2, 3];
106 /// assert!(!a.is_empty());
108 #[stable(feature = "rust1", since = "1.0.0")]
109 #[rustc_const_stable(feature = "const_slice_is_empty", since = "1.32.0")]
111 pub const fn is_empty(&self) -> bool {
115 /// Returns the first element of the slice, or `None` if it is empty.
120 /// let v = [10, 40, 30];
121 /// assert_eq!(Some(&10), v.first());
123 /// let w: &[i32] = &[];
124 /// assert_eq!(None, w.first());
126 #[stable(feature = "rust1", since = "1.0.0")]
128 pub fn first(&self) -> Option<&T> {
129 if let [first, ..] = self { Some(first) } else { None }
132 /// Returns a mutable pointer to the first element of the slice, or `None` if it is empty.
137 /// let x = &mut [0, 1, 2];
139 /// if let Some(first) = x.first_mut() {
142 /// assert_eq!(x, &[5, 1, 2]);
144 #[stable(feature = "rust1", since = "1.0.0")]
146 pub fn first_mut(&mut self) -> Option<&mut T> {
147 if let [first, ..] = self { Some(first) } else { None }
150 /// Returns the first and all the rest of the elements of the slice, or `None` if it is empty.
155 /// let x = &[0, 1, 2];
157 /// if let Some((first, elements)) = x.split_first() {
158 /// assert_eq!(first, &0);
159 /// assert_eq!(elements, &[1, 2]);
162 #[stable(feature = "slice_splits", since = "1.5.0")]
164 pub fn split_first(&self) -> Option<(&T, &[T])> {
165 if let [first, tail @ ..] = self { Some((first, tail)) } else { None }
168 /// Returns the first and all the rest of the elements of the slice, or `None` if it is empty.
173 /// let x = &mut [0, 1, 2];
175 /// if let Some((first, elements)) = x.split_first_mut() {
180 /// assert_eq!(x, &[3, 4, 5]);
182 #[stable(feature = "slice_splits", since = "1.5.0")]
184 pub fn split_first_mut(&mut self) -> Option<(&mut T, &mut [T])> {
185 if let [first, tail @ ..] = self { Some((first, tail)) } else { None }
188 /// Returns the last and all the rest of the elements of the slice, or `None` if it is empty.
193 /// let x = &[0, 1, 2];
195 /// if let Some((last, elements)) = x.split_last() {
196 /// assert_eq!(last, &2);
197 /// assert_eq!(elements, &[0, 1]);
200 #[stable(feature = "slice_splits", since = "1.5.0")]
202 pub fn split_last(&self) -> Option<(&T, &[T])> {
203 if let [init @ .., last] = self { Some((last, init)) } else { None }
206 /// Returns the last and all the rest of the elements of the slice, or `None` if it is empty.
211 /// let x = &mut [0, 1, 2];
213 /// if let Some((last, elements)) = x.split_last_mut() {
218 /// assert_eq!(x, &[4, 5, 3]);
220 #[stable(feature = "slice_splits", since = "1.5.0")]
222 pub fn split_last_mut(&mut self) -> Option<(&mut T, &mut [T])> {
223 if let [init @ .., last] = self { Some((last, init)) } else { None }
226 /// Returns the last element of the slice, or `None` if it is empty.
231 /// let v = [10, 40, 30];
232 /// assert_eq!(Some(&30), v.last());
234 /// let w: &[i32] = &[];
235 /// assert_eq!(None, w.last());
237 #[stable(feature = "rust1", since = "1.0.0")]
239 pub fn last(&self) -> Option<&T> {
240 if let [.., last] = self { Some(last) } else { None }
243 /// Returns a mutable pointer to the last item in the slice.
248 /// let x = &mut [0, 1, 2];
250 /// if let Some(last) = x.last_mut() {
253 /// assert_eq!(x, &[0, 1, 10]);
255 #[stable(feature = "rust1", since = "1.0.0")]
257 pub fn last_mut(&mut self) -> Option<&mut T> {
258 if let [.., last] = self { Some(last) } else { None }
261 /// Returns a reference to an element or subslice depending on the type of
264 /// - If given a position, returns a reference to the element at that
265 /// position or `None` if out of bounds.
266 /// - If given a range, returns the subslice corresponding to that range,
267 /// or `None` if out of bounds.
272 /// let v = [10, 40, 30];
273 /// assert_eq!(Some(&40), v.get(1));
274 /// assert_eq!(Some(&[10, 40][..]), v.get(0..2));
275 /// assert_eq!(None, v.get(3));
276 /// assert_eq!(None, v.get(0..4));
278 #[stable(feature = "rust1", since = "1.0.0")]
280 pub fn get<I>(&self, index: I) -> Option<&I::Output>
287 /// Returns a mutable reference to an element or subslice depending on the
288 /// type of index (see [`get`]) or `None` if the index is out of bounds.
290 /// [`get`]: #method.get
295 /// let x = &mut [0, 1, 2];
297 /// if let Some(elem) = x.get_mut(1) {
300 /// assert_eq!(x, &[0, 42, 2]);
302 #[stable(feature = "rust1", since = "1.0.0")]
304 pub fn get_mut<I>(&mut self, index: I) -> Option<&mut I::Output>
311 /// Returns a reference to an element or subslice, without doing bounds
314 /// For a safe alternative see [`get`].
318 /// Calling this method with an out-of-bounds index is *[undefined behavior]*
319 /// even if the resulting reference is not used.
321 /// [`get`]: #method.get
322 /// [undefined behavior]: https://doc.rust-lang.org/reference/behavior-considered-undefined.html
327 /// let x = &[1, 2, 4];
330 /// assert_eq!(x.get_unchecked(1), &2);
333 #[stable(feature = "rust1", since = "1.0.0")]
335 pub unsafe fn get_unchecked<I>(&self, index: I) -> &I::Output
339 // SAFETY: the caller must uphold most of the safety requirements for `get_unchecked`;
340 // the slice is dereferencable because `self` is a safe reference.
341 // The returned pointer is safe because impls of `SliceIndex` have to guarantee that it is.
342 unsafe { &*index.get_unchecked(self) }
345 /// Returns a mutable reference to an element or subslice, without doing
348 /// For a safe alternative see [`get_mut`].
352 /// Calling this method with an out-of-bounds index is *[undefined behavior]*
353 /// even if the resulting reference is not used.
355 /// [`get_mut`]: #method.get_mut
356 /// [undefined behavior]: https://doc.rust-lang.org/reference/behavior-considered-undefined.html
361 /// let x = &mut [1, 2, 4];
364 /// let elem = x.get_unchecked_mut(1);
367 /// assert_eq!(x, &[1, 13, 4]);
369 #[stable(feature = "rust1", since = "1.0.0")]
371 pub unsafe fn get_unchecked_mut<I>(&mut self, index: I) -> &mut I::Output
375 // SAFETY: the caller must uphold the safety requirements for `get_unchecked_mut`;
376 // the slice is dereferencable because `self` is a safe reference.
377 // The returned pointer is safe because impls of `SliceIndex` have to guarantee that it is.
378 unsafe { &mut *index.get_unchecked_mut(self) }
381 /// Returns a raw pointer to the slice's buffer.
383 /// The caller must ensure that the slice outlives the pointer this
384 /// function returns, or else it will end up pointing to garbage.
386 /// The caller must also ensure that the memory the pointer (non-transitively) points to
387 /// is never written to (except inside an `UnsafeCell`) using this pointer or any pointer
388 /// derived from it. If you need to mutate the contents of the slice, use [`as_mut_ptr`].
390 /// Modifying the container referenced by this slice may cause its buffer
391 /// to be reallocated, which would also make any pointers to it invalid.
396 /// let x = &[1, 2, 4];
397 /// let x_ptr = x.as_ptr();
400 /// for i in 0..x.len() {
401 /// assert_eq!(x.get_unchecked(i), &*x_ptr.add(i));
406 /// [`as_mut_ptr`]: #method.as_mut_ptr
407 #[stable(feature = "rust1", since = "1.0.0")]
408 #[rustc_const_stable(feature = "const_slice_as_ptr", since = "1.32.0")]
410 pub const fn as_ptr(&self) -> *const T {
411 self as *const [T] as *const T
414 /// Returns an unsafe mutable pointer to the slice's buffer.
416 /// The caller must ensure that the slice outlives the pointer this
417 /// function returns, or else it will end up pointing to garbage.
419 /// Modifying the container referenced by this slice may cause its buffer
420 /// to be reallocated, which would also make any pointers to it invalid.
425 /// let x = &mut [1, 2, 4];
426 /// let x_ptr = x.as_mut_ptr();
429 /// for i in 0..x.len() {
430 /// *x_ptr.add(i) += 2;
433 /// assert_eq!(x, &[3, 4, 6]);
435 #[stable(feature = "rust1", since = "1.0.0")]
437 pub fn as_mut_ptr(&mut self) -> *mut T {
438 self as *mut [T] as *mut T
441 /// Returns the two raw pointers spanning the slice.
443 /// The returned range is half-open, which means that the end pointer
444 /// points *one past* the last element of the slice. This way, an empty
445 /// slice is represented by two equal pointers, and the difference between
446 /// the two pointers represents the size of the slice.
448 /// See [`as_ptr`] for warnings on using these pointers. The end pointer
449 /// requires extra caution, as it does not point to a valid element in the
452 /// This function is useful for interacting with foreign interfaces which
453 /// use two pointers to refer to a range of elements in memory, as is
456 /// It can also be useful to check if a pointer to an element refers to an
457 /// element of this slice:
460 /// #![feature(slice_ptr_range)]
462 /// let a = [1, 2, 3];
463 /// let x = &a[1] as *const _;
464 /// let y = &5 as *const _;
466 /// assert!(a.as_ptr_range().contains(&x));
467 /// assert!(!a.as_ptr_range().contains(&y));
470 /// [`as_ptr`]: #method.as_ptr
471 #[unstable(feature = "slice_ptr_range", issue = "65807")]
473 pub fn as_ptr_range(&self) -> Range<*const T> {
474 let start = self.as_ptr();
475 // SAFETY: The `add` here is safe, because:
477 // - Both pointers are part of the same object, as pointing directly
478 // past the object also counts.
480 // - The size of the slice is never larger than isize::MAX bytes, as
482 // - https://github.com/rust-lang/unsafe-code-guidelines/issues/102#issuecomment-473340447
483 // - https://doc.rust-lang.org/reference/behavior-considered-undefined.html
484 // - https://doc.rust-lang.org/core/slice/fn.from_raw_parts.html#safety
485 // (This doesn't seem normative yet, but the very same assumption is
486 // made in many places, including the Index implementation of slices.)
488 // - There is no wrapping around involved, as slices do not wrap past
489 // the end of the address space.
491 // See the documentation of pointer::add.
492 let end = unsafe { start.add(self.len()) };
496 /// Returns the two unsafe mutable pointers spanning the slice.
498 /// The returned range is half-open, which means that the end pointer
499 /// points *one past* the last element of the slice. This way, an empty
500 /// slice is represented by two equal pointers, and the difference between
501 /// the two pointers represents the size of the slice.
503 /// See [`as_mut_ptr`] for warnings on using these pointers. The end
504 /// pointer requires extra caution, as it does not point to a valid element
507 /// This function is useful for interacting with foreign interfaces which
508 /// use two pointers to refer to a range of elements in memory, as is
511 /// [`as_mut_ptr`]: #method.as_mut_ptr
512 #[unstable(feature = "slice_ptr_range", issue = "65807")]
514 pub fn as_mut_ptr_range(&mut self) -> Range<*mut T> {
515 let start = self.as_mut_ptr();
516 // SAFETY: See as_ptr_range() above for why `add` here is safe.
517 let end = unsafe { start.add(self.len()) };
521 /// Swaps two elements in the slice.
525 /// * a - The index of the first element
526 /// * b - The index of the second element
530 /// Panics if `a` or `b` are out of bounds.
535 /// let mut v = ["a", "b", "c", "d"];
537 /// assert!(v == ["a", "d", "c", "b"]);
539 #[stable(feature = "rust1", since = "1.0.0")]
541 pub fn swap(&mut self, a: usize, b: usize) {
542 // Can't take two mutable loans from one vector, so instead just cast
543 // them to their raw pointers to do the swap.
544 let pa: *mut T = &mut self[a];
545 let pb: *mut T = &mut self[b];
546 // SAFETY: `pa` and `pb` have been created from safe mutable references and refer
547 // to elements in the slice and therefore are guaranteed to be valid and aligned.
548 // Note that accessing the elements behind `a` and `b` is checked and will
549 // panic when out of bounds.
555 /// Reverses the order of elements in the slice, in place.
560 /// let mut v = [1, 2, 3];
562 /// assert!(v == [3, 2, 1]);
564 #[stable(feature = "rust1", since = "1.0.0")]
566 pub fn reverse(&mut self) {
567 let mut i: usize = 0;
570 // For very small types, all the individual reads in the normal
571 // path perform poorly. We can do better, given efficient unaligned
572 // load/store, by loading a larger chunk and reversing a register.
574 // Ideally LLVM would do this for us, as it knows better than we do
575 // whether unaligned reads are efficient (since that changes between
576 // different ARM versions, for example) and what the best chunk size
577 // would be. Unfortunately, as of LLVM 4.0 (2017-05) it only unrolls
578 // the loop, so we need to do this ourselves. (Hypothesis: reverse
579 // is troublesome because the sides can be aligned differently --
580 // will be, when the length is odd -- so there's no way of emitting
581 // pre- and postludes to use fully-aligned SIMD in the middle.)
583 let fast_unaligned = cfg!(any(target_arch = "x86", target_arch = "x86_64"));
585 if fast_unaligned && mem::size_of::<T>() == 1 {
586 // Use the llvm.bswap intrinsic to reverse u8s in a usize
587 let chunk = mem::size_of::<usize>();
588 while i + chunk - 1 < ln / 2 {
589 // SAFETY: There are several things to check here:
591 // - Note that `chunk` is either 4 or 8 due to the cfg check
592 // above. So `chunk - 1` is positive.
593 // - Indexing with index `i` is fine as the loop check guarantees
594 // `i + chunk - 1 < ln / 2`
595 // <=> `i < ln / 2 - (chunk - 1) < ln / 2 < ln`.
596 // - Indexing with index `ln - i - chunk = ln - (i + chunk)` is fine:
597 // - `i + chunk > 0` is trivially true.
598 // - The loop check guarantees:
599 // `i + chunk - 1 < ln / 2`
600 // <=> `i + chunk ≤ ln / 2 ≤ ln`, thus subtraction does not underflow.
601 // - The `read_unaligned` and `write_unaligned` calls are fine:
602 // - `pa` points to index `i` where `i < ln / 2 - (chunk - 1)`
603 // (see above) and `pb` points to index `ln - i - chunk`, so
604 // both are at least `chunk`
605 // many bytes away from the end of `self`.
606 // - Any initialized memory is valid `usize`.
608 let pa: *mut T = self.get_unchecked_mut(i);
609 let pb: *mut T = self.get_unchecked_mut(ln - i - chunk);
610 let va = ptr::read_unaligned(pa as *mut usize);
611 let vb = ptr::read_unaligned(pb as *mut usize);
612 ptr::write_unaligned(pa as *mut usize, vb.swap_bytes());
613 ptr::write_unaligned(pb as *mut usize, va.swap_bytes());
619 if fast_unaligned && mem::size_of::<T>() == 2 {
620 // Use rotate-by-16 to reverse u16s in a u32
621 let chunk = mem::size_of::<u32>() / 2;
622 while i + chunk - 1 < ln / 2 {
623 // SAFETY: An unaligned u32 can be read from `i` if `i + 1 < ln`
624 // (and obviously `i < ln`), because each element is 2 bytes and
627 // `i + chunk - 1 < ln / 2` # while condition
628 // `i + 2 - 1 < ln / 2`
631 // Since it's less than the length divided by 2, then it must be
634 // This also means that the condition `0 < i + chunk <= ln` is
635 // always respected, ensuring the `pb` pointer can be used
638 let pa: *mut T = self.get_unchecked_mut(i);
639 let pb: *mut T = self.get_unchecked_mut(ln - i - chunk);
640 let va = ptr::read_unaligned(pa as *mut u32);
641 let vb = ptr::read_unaligned(pb as *mut u32);
642 ptr::write_unaligned(pa as *mut u32, vb.rotate_left(16));
643 ptr::write_unaligned(pb as *mut u32, va.rotate_left(16));
650 // SAFETY: `i` is inferior to half the length of the slice so
651 // accessing `i` and `ln - i - 1` is safe (`i` starts at 0 and
652 // will not go further than `ln / 2 - 1`).
653 // The resulting pointers `pa` and `pb` are therefore valid and
654 // aligned, and can be read from and written to.
656 // Unsafe swap to avoid the bounds check in safe swap.
657 let pa: *mut T = self.get_unchecked_mut(i);
658 let pb: *mut T = self.get_unchecked_mut(ln - i - 1);
665 /// Returns an iterator over the slice.
670 /// let x = &[1, 2, 4];
671 /// let mut iterator = x.iter();
673 /// assert_eq!(iterator.next(), Some(&1));
674 /// assert_eq!(iterator.next(), Some(&2));
675 /// assert_eq!(iterator.next(), Some(&4));
676 /// assert_eq!(iterator.next(), None);
678 #[stable(feature = "rust1", since = "1.0.0")]
680 pub fn iter(&self) -> Iter<'_, T> {
684 /// Returns an iterator that allows modifying each value.
689 /// let x = &mut [1, 2, 4];
690 /// for elem in x.iter_mut() {
693 /// assert_eq!(x, &[3, 4, 6]);
695 #[stable(feature = "rust1", since = "1.0.0")]
697 pub fn iter_mut(&mut self) -> IterMut<'_, T> {
701 /// Returns an iterator over all contiguous windows of length
702 /// `size`. The windows overlap. If the slice is shorter than
703 /// `size`, the iterator returns no values.
707 /// Panics if `size` is 0.
712 /// let slice = ['r', 'u', 's', 't'];
713 /// let mut iter = slice.windows(2);
714 /// assert_eq!(iter.next().unwrap(), &['r', 'u']);
715 /// assert_eq!(iter.next().unwrap(), &['u', 's']);
716 /// assert_eq!(iter.next().unwrap(), &['s', 't']);
717 /// assert!(iter.next().is_none());
720 /// If the slice is shorter than `size`:
723 /// let slice = ['f', 'o', 'o'];
724 /// let mut iter = slice.windows(4);
725 /// assert!(iter.next().is_none());
727 #[stable(feature = "rust1", since = "1.0.0")]
729 pub fn windows(&self, size: usize) -> Windows<'_, T> {
731 Windows::new(self, size)
734 /// Returns an iterator over `chunk_size` elements of the slice at a time, starting at the
735 /// beginning of the slice.
737 /// The chunks are slices and do not overlap. If `chunk_size` does not divide the length of the
738 /// slice, then the last chunk will not have length `chunk_size`.
740 /// See [`chunks_exact`] for a variant of this iterator that returns chunks of always exactly
741 /// `chunk_size` elements, and [`rchunks`] for the same iterator but starting at the end of the
746 /// Panics if `chunk_size` is 0.
751 /// let slice = ['l', 'o', 'r', 'e', 'm'];
752 /// let mut iter = slice.chunks(2);
753 /// assert_eq!(iter.next().unwrap(), &['l', 'o']);
754 /// assert_eq!(iter.next().unwrap(), &['r', 'e']);
755 /// assert_eq!(iter.next().unwrap(), &['m']);
756 /// assert!(iter.next().is_none());
759 /// [`chunks_exact`]: #method.chunks_exact
760 /// [`rchunks`]: #method.rchunks
761 #[stable(feature = "rust1", since = "1.0.0")]
763 pub fn chunks(&self, chunk_size: usize) -> Chunks<'_, T> {
764 assert_ne!(chunk_size, 0);
765 Chunks::new(self, chunk_size)
768 /// Returns an iterator over `chunk_size` elements of the slice at a time, starting at the
769 /// beginning of the slice.
771 /// The chunks are mutable slices, and do not overlap. If `chunk_size` does not divide the
772 /// length of the slice, then the last chunk will not have length `chunk_size`.
774 /// See [`chunks_exact_mut`] for a variant of this iterator that returns chunks of always
775 /// exactly `chunk_size` elements, and [`rchunks_mut`] for the same iterator but starting at
776 /// the end of the slice.
780 /// Panics if `chunk_size` is 0.
785 /// let v = &mut [0, 0, 0, 0, 0];
786 /// let mut count = 1;
788 /// for chunk in v.chunks_mut(2) {
789 /// for elem in chunk.iter_mut() {
794 /// assert_eq!(v, &[1, 1, 2, 2, 3]);
797 /// [`chunks_exact_mut`]: #method.chunks_exact_mut
798 /// [`rchunks_mut`]: #method.rchunks_mut
799 #[stable(feature = "rust1", since = "1.0.0")]
801 pub fn chunks_mut(&mut self, chunk_size: usize) -> ChunksMut<'_, T> {
802 assert_ne!(chunk_size, 0);
803 ChunksMut::new(self, chunk_size)
806 /// Returns an iterator over `chunk_size` elements of the slice at a time, starting at the
807 /// beginning of the slice.
809 /// The chunks are slices and do not overlap. If `chunk_size` does not divide the length of the
810 /// slice, then the last up to `chunk_size-1` elements will be omitted and can be retrieved
811 /// from the `remainder` function of the iterator.
813 /// Due to each chunk having exactly `chunk_size` elements, the compiler can often optimize the
814 /// resulting code better than in the case of [`chunks`].
816 /// See [`chunks`] for a variant of this iterator that also returns the remainder as a smaller
817 /// chunk, and [`rchunks_exact`] for the same iterator but starting at the end of the slice.
821 /// Panics if `chunk_size` is 0.
826 /// let slice = ['l', 'o', 'r', 'e', 'm'];
827 /// let mut iter = slice.chunks_exact(2);
828 /// assert_eq!(iter.next().unwrap(), &['l', 'o']);
829 /// assert_eq!(iter.next().unwrap(), &['r', 'e']);
830 /// assert!(iter.next().is_none());
831 /// assert_eq!(iter.remainder(), &['m']);
834 /// [`chunks`]: #method.chunks
835 /// [`rchunks_exact`]: #method.rchunks_exact
836 #[stable(feature = "chunks_exact", since = "1.31.0")]
838 pub fn chunks_exact(&self, chunk_size: usize) -> ChunksExact<'_, T> {
839 assert_ne!(chunk_size, 0);
840 ChunksExact::new(self, chunk_size)
843 /// Returns an iterator over `chunk_size` elements of the slice at a time, starting at the
844 /// beginning of the slice.
846 /// The chunks are mutable slices, and do not overlap. If `chunk_size` does not divide the
847 /// length of the slice, then the last up to `chunk_size-1` elements will be omitted and can be
848 /// retrieved from the `into_remainder` function of the iterator.
850 /// Due to each chunk having exactly `chunk_size` elements, the compiler can often optimize the
851 /// resulting code better than in the case of [`chunks_mut`].
853 /// See [`chunks_mut`] for a variant of this iterator that also returns the remainder as a
854 /// smaller chunk, and [`rchunks_exact_mut`] for the same iterator but starting at the end of
859 /// Panics if `chunk_size` is 0.
864 /// let v = &mut [0, 0, 0, 0, 0];
865 /// let mut count = 1;
867 /// for chunk in v.chunks_exact_mut(2) {
868 /// for elem in chunk.iter_mut() {
873 /// assert_eq!(v, &[1, 1, 2, 2, 0]);
876 /// [`chunks_mut`]: #method.chunks_mut
877 /// [`rchunks_exact_mut`]: #method.rchunks_exact_mut
878 #[stable(feature = "chunks_exact", since = "1.31.0")]
880 pub fn chunks_exact_mut(&mut self, chunk_size: usize) -> ChunksExactMut<'_, T> {
881 assert_ne!(chunk_size, 0);
882 ChunksExactMut::new(self, chunk_size)
885 /// Returns an iterator over `N` elements of the slice at a time, starting at the
886 /// beginning of the slice.
888 /// The chunks are array references and do not overlap. If `N` does not divide the
889 /// length of the slice, then the last up to `N-1` elements will be omitted and can be
890 /// retrieved from the `remainder` function of the iterator.
892 /// This method is the const generic equivalent of [`chunks_exact`].
896 /// Panics if `N` is 0. This check will most probably get changed to a compile time
897 /// error before this method gets stabilized.
902 /// #![feature(array_chunks)]
903 /// let slice = ['l', 'o', 'r', 'e', 'm'];
904 /// let mut iter = slice.array_chunks();
905 /// assert_eq!(iter.next().unwrap(), &['l', 'o']);
906 /// assert_eq!(iter.next().unwrap(), &['r', 'e']);
907 /// assert!(iter.next().is_none());
908 /// assert_eq!(iter.remainder(), &['m']);
911 /// [`chunks_exact`]: #method.chunks_exact
912 #[unstable(feature = "array_chunks", issue = "74985")]
914 pub fn array_chunks<const N: usize>(&self) -> ArrayChunks<'_, T, N> {
916 ArrayChunks::new(self)
919 /// Returns an iterator over `N` elements of the slice at a time, starting at the
920 /// beginning of the slice.
922 /// The chunks are mutable array references and do not overlap. If `N` does not divide
923 /// the length of the slice, then the last up to `N-1` elements will be omitted and
924 /// can be retrieved from the `into_remainder` function of the iterator.
926 /// This method is the const generic equivalent of [`chunks_exact_mut`].
930 /// Panics if `N` is 0. This check will most probably get changed to a compile time
931 /// error before this method gets stabilized.
936 /// #![feature(array_chunks)]
937 /// let v = &mut [0, 0, 0, 0, 0];
938 /// let mut count = 1;
940 /// for chunk in v.array_chunks_mut() {
941 /// *chunk = [count; 2];
944 /// assert_eq!(v, &[1, 1, 2, 2, 0]);
947 /// [`chunks_exact_mut`]: #method.chunks_exact_mut
948 #[unstable(feature = "array_chunks", issue = "74985")]
950 pub fn array_chunks_mut<const N: usize>(&mut self) -> ArrayChunksMut<'_, T, N> {
952 ArrayChunksMut::new(self)
955 /// Returns an iterator over overlapping windows of `N` elements of a slice,
956 /// starting at the beginning of the slice.
958 /// This is the const generic equivalent of [`windows`].
960 /// If `N` is greater than the size of the slice, it will return no windows.
964 /// Panics if `N` is 0. This check will most probably get changed to a compile time
965 /// error before this method gets stabilized.
970 /// #![feature(array_windows)]
971 /// let slice = [0, 1, 2, 3];
972 /// let mut iter = slice.array_windows();
973 /// assert_eq!(iter.next().unwrap(), &[0, 1]);
974 /// assert_eq!(iter.next().unwrap(), &[1, 2]);
975 /// assert_eq!(iter.next().unwrap(), &[2, 3]);
976 /// assert!(iter.next().is_none());
979 /// [`windows`]: #method.windows
980 #[unstable(feature = "array_windows", issue = "75027")]
982 pub fn array_windows<const N: usize>(&self) -> ArrayWindows<'_, T, N> {
984 ArrayWindows::new(self)
987 /// Returns an iterator over `chunk_size` elements of the slice at a time, starting at the end
990 /// The chunks are slices and do not overlap. If `chunk_size` does not divide the length of the
991 /// slice, then the last chunk will not have length `chunk_size`.
993 /// See [`rchunks_exact`] for a variant of this iterator that returns chunks of always exactly
994 /// `chunk_size` elements, and [`chunks`] for the same iterator but starting at the beginning
999 /// Panics if `chunk_size` is 0.
1004 /// let slice = ['l', 'o', 'r', 'e', 'm'];
1005 /// let mut iter = slice.rchunks(2);
1006 /// assert_eq!(iter.next().unwrap(), &['e', 'm']);
1007 /// assert_eq!(iter.next().unwrap(), &['o', 'r']);
1008 /// assert_eq!(iter.next().unwrap(), &['l']);
1009 /// assert!(iter.next().is_none());
1012 /// [`rchunks_exact`]: #method.rchunks_exact
1013 /// [`chunks`]: #method.chunks
1014 #[stable(feature = "rchunks", since = "1.31.0")]
1016 pub fn rchunks(&self, chunk_size: usize) -> RChunks<'_, T> {
1017 assert!(chunk_size != 0);
1018 RChunks::new(self, chunk_size)
1021 /// Returns an iterator over `chunk_size` elements of the slice at a time, starting at the end
1024 /// The chunks are mutable slices, and do not overlap. If `chunk_size` does not divide the
1025 /// length of the slice, then the last chunk will not have length `chunk_size`.
1027 /// See [`rchunks_exact_mut`] for a variant of this iterator that returns chunks of always
1028 /// exactly `chunk_size` elements, and [`chunks_mut`] for the same iterator but starting at the
1029 /// beginning of the slice.
1033 /// Panics if `chunk_size` is 0.
1038 /// let v = &mut [0, 0, 0, 0, 0];
1039 /// let mut count = 1;
1041 /// for chunk in v.rchunks_mut(2) {
1042 /// for elem in chunk.iter_mut() {
1047 /// assert_eq!(v, &[3, 2, 2, 1, 1]);
1050 /// [`rchunks_exact_mut`]: #method.rchunks_exact_mut
1051 /// [`chunks_mut`]: #method.chunks_mut
1052 #[stable(feature = "rchunks", since = "1.31.0")]
1054 pub fn rchunks_mut(&mut self, chunk_size: usize) -> RChunksMut<'_, T> {
1055 assert!(chunk_size != 0);
1056 RChunksMut::new(self, chunk_size)
1059 /// Returns an iterator over `chunk_size` elements of the slice at a time, starting at the
1060 /// end of the slice.
1062 /// The chunks are slices and do not overlap. If `chunk_size` does not divide the length of the
1063 /// slice, then the last up to `chunk_size-1` elements will be omitted and can be retrieved
1064 /// from the `remainder` function of the iterator.
1066 /// Due to each chunk having exactly `chunk_size` elements, the compiler can often optimize the
1067 /// resulting code better than in the case of [`chunks`].
1069 /// See [`rchunks`] for a variant of this iterator that also returns the remainder as a smaller
1070 /// chunk, and [`chunks_exact`] for the same iterator but starting at the beginning of the
1075 /// Panics if `chunk_size` is 0.
1080 /// let slice = ['l', 'o', 'r', 'e', 'm'];
1081 /// let mut iter = slice.rchunks_exact(2);
1082 /// assert_eq!(iter.next().unwrap(), &['e', 'm']);
1083 /// assert_eq!(iter.next().unwrap(), &['o', 'r']);
1084 /// assert!(iter.next().is_none());
1085 /// assert_eq!(iter.remainder(), &['l']);
1088 /// [`chunks`]: #method.chunks
1089 /// [`rchunks`]: #method.rchunks
1090 /// [`chunks_exact`]: #method.chunks_exact
1091 #[stable(feature = "rchunks", since = "1.31.0")]
1093 pub fn rchunks_exact(&self, chunk_size: usize) -> RChunksExact<'_, T> {
1094 assert!(chunk_size != 0);
1095 RChunksExact::new(self, chunk_size)
1098 /// Returns an iterator over `chunk_size` elements of the slice at a time, starting at the end
1101 /// The chunks are mutable slices, and do not overlap. If `chunk_size` does not divide the
1102 /// length of the slice, then the last up to `chunk_size-1` elements will be omitted and can be
1103 /// retrieved from the `into_remainder` function of the iterator.
1105 /// Due to each chunk having exactly `chunk_size` elements, the compiler can often optimize the
1106 /// resulting code better than in the case of [`chunks_mut`].
1108 /// See [`rchunks_mut`] for a variant of this iterator that also returns the remainder as a
1109 /// smaller chunk, and [`chunks_exact_mut`] for the same iterator but starting at the beginning
1114 /// Panics if `chunk_size` is 0.
1119 /// let v = &mut [0, 0, 0, 0, 0];
1120 /// let mut count = 1;
1122 /// for chunk in v.rchunks_exact_mut(2) {
1123 /// for elem in chunk.iter_mut() {
1128 /// assert_eq!(v, &[0, 2, 2, 1, 1]);
1131 /// [`chunks_mut`]: #method.chunks_mut
1132 /// [`rchunks_mut`]: #method.rchunks_mut
1133 /// [`chunks_exact_mut`]: #method.chunks_exact_mut
1134 #[stable(feature = "rchunks", since = "1.31.0")]
1136 pub fn rchunks_exact_mut(&mut self, chunk_size: usize) -> RChunksExactMut<'_, T> {
1137 assert!(chunk_size != 0);
1138 RChunksExactMut::new(self, chunk_size)
1141 /// Divides one slice into two at an index.
1143 /// The first will contain all indices from `[0, mid)` (excluding
1144 /// the index `mid` itself) and the second will contain all
1145 /// indices from `[mid, len)` (excluding the index `len` itself).
1149 /// Panics if `mid > len`.
1154 /// let v = [1, 2, 3, 4, 5, 6];
1157 /// let (left, right) = v.split_at(0);
1158 /// assert_eq!(left, []);
1159 /// assert_eq!(right, [1, 2, 3, 4, 5, 6]);
1163 /// let (left, right) = v.split_at(2);
1164 /// assert_eq!(left, [1, 2]);
1165 /// assert_eq!(right, [3, 4, 5, 6]);
1169 /// let (left, right) = v.split_at(6);
1170 /// assert_eq!(left, [1, 2, 3, 4, 5, 6]);
1171 /// assert_eq!(right, []);
1174 #[stable(feature = "rust1", since = "1.0.0")]
1176 pub fn split_at(&self, mid: usize) -> (&[T], &[T]) {
1177 assert!(mid <= self.len());
1178 // SAFETY: `[ptr; mid]` and `[mid; len]` are inside `self`, which
1179 // fulfills the requirements of `from_raw_parts_mut`.
1180 unsafe { self.split_at_unchecked(mid) }
1183 /// Divides one mutable slice into two at an index.
1185 /// The first will contain all indices from `[0, mid)` (excluding
1186 /// the index `mid` itself) and the second will contain all
1187 /// indices from `[mid, len)` (excluding the index `len` itself).
1191 /// Panics if `mid > len`.
1196 /// let mut v = [1, 0, 3, 0, 5, 6];
1197 /// // scoped to restrict the lifetime of the borrows
1199 /// let (left, right) = v.split_at_mut(2);
1200 /// assert_eq!(left, [1, 0]);
1201 /// assert_eq!(right, [3, 0, 5, 6]);
1205 /// assert_eq!(v, [1, 2, 3, 4, 5, 6]);
1207 #[stable(feature = "rust1", since = "1.0.0")]
1209 pub fn split_at_mut(&mut self, mid: usize) -> (&mut [T], &mut [T]) {
1210 assert!(mid <= self.len());
1211 // SAFETY: `[ptr; mid]` and `[mid; len]` are inside `self`, which
1212 // fulfills the requirements of `from_raw_parts_mut`.
1213 unsafe { self.split_at_mut_unchecked(mid) }
1216 /// Divides one slice into two at an index, without doing bounds checking.
1218 /// The first will contain all indices from `[0, mid)` (excluding
1219 /// the index `mid` itself) and the second will contain all
1220 /// indices from `[mid, len)` (excluding the index `len` itself).
1222 /// For a safe alternative see [`split_at`].
1226 /// Calling this method with an out-of-bounds index is *[undefined behavior]*
1227 /// even if the resulting reference is not used. The caller has to ensure that
1228 /// `0 <= mid <= self.len()`.
1230 /// [`split_at`]: #method.split_at
1231 /// [undefined behavior]: https://doc.rust-lang.org/reference/behavior-considered-undefined.html
1236 /// #![feature(slice_split_at_unchecked)]
1238 /// let v = [1, 2, 3, 4, 5, 6];
1241 /// let (left, right) = v.split_at_unchecked(0);
1242 /// assert_eq!(left, []);
1243 /// assert_eq!(right, [1, 2, 3, 4, 5, 6]);
1247 /// let (left, right) = v.split_at_unchecked(2);
1248 /// assert_eq!(left, [1, 2]);
1249 /// assert_eq!(right, [3, 4, 5, 6]);
1253 /// let (left, right) = v.split_at_unchecked(6);
1254 /// assert_eq!(left, [1, 2, 3, 4, 5, 6]);
1255 /// assert_eq!(right, []);
1258 #[unstable(feature = "slice_split_at_unchecked", reason = "new API", issue = "76014")]
1260 unsafe fn split_at_unchecked(&self, mid: usize) -> (&[T], &[T]) {
1261 // SAFETY: Caller has to check that `0 <= mid <= self.len()`
1262 unsafe { (self.get_unchecked(..mid), self.get_unchecked(mid..)) }
1265 /// Divides one mutable slice into two at an index, without doing bounds checking.
1267 /// The first will contain all indices from `[0, mid)` (excluding
1268 /// the index `mid` itself) and the second will contain all
1269 /// indices from `[mid, len)` (excluding the index `len` itself).
1271 /// For a safe alternative see [`split_at_mut`].
1275 /// Calling this method with an out-of-bounds index is *[undefined behavior]*
1276 /// even if the resulting reference is not used. The caller has to ensure that
1277 /// `0 <= mid <= self.len()`.
1279 /// [`split_at_mut`]: #method.split_at_mut
1280 /// [undefined behavior]: https://doc.rust-lang.org/reference/behavior-considered-undefined.html
1285 /// #![feature(slice_split_at_unchecked)]
1287 /// let mut v = [1, 0, 3, 0, 5, 6];
1288 /// // scoped to restrict the lifetime of the borrows
1290 /// let (left, right) = v.split_at_mut_unchecked(2);
1291 /// assert_eq!(left, [1, 0]);
1292 /// assert_eq!(right, [3, 0, 5, 6]);
1296 /// assert_eq!(v, [1, 2, 3, 4, 5, 6]);
1298 #[unstable(feature = "slice_split_at_unchecked", reason = "new API", issue = "76014")]
1300 unsafe fn split_at_mut_unchecked(&mut self, mid: usize) -> (&mut [T], &mut [T]) {
1301 let len = self.len();
1302 let ptr = self.as_mut_ptr();
1304 // SAFETY: Caller has to check that `0 <= mid <= self.len()`.
1306 // `[ptr; mid]` and `[mid; len]` are not overlapping, so returning a mutable reference
1308 unsafe { (from_raw_parts_mut(ptr, mid), from_raw_parts_mut(ptr.add(mid), len - mid)) }
1311 /// Returns an iterator over subslices separated by elements that match
1312 /// `pred`. The matched element is not contained in the subslices.
1317 /// let slice = [10, 40, 33, 20];
1318 /// let mut iter = slice.split(|num| num % 3 == 0);
1320 /// assert_eq!(iter.next().unwrap(), &[10, 40]);
1321 /// assert_eq!(iter.next().unwrap(), &[20]);
1322 /// assert!(iter.next().is_none());
1325 /// If the first element is matched, an empty slice will be the first item
1326 /// returned by the iterator. Similarly, if the last element in the slice
1327 /// is matched, an empty slice will be the last item returned by the
1331 /// let slice = [10, 40, 33];
1332 /// let mut iter = slice.split(|num| num % 3 == 0);
1334 /// assert_eq!(iter.next().unwrap(), &[10, 40]);
1335 /// assert_eq!(iter.next().unwrap(), &[]);
1336 /// assert!(iter.next().is_none());
1339 /// If two matched elements are directly adjacent, an empty slice will be
1340 /// present between them:
1343 /// let slice = [10, 6, 33, 20];
1344 /// let mut iter = slice.split(|num| num % 3 == 0);
1346 /// assert_eq!(iter.next().unwrap(), &[10]);
1347 /// assert_eq!(iter.next().unwrap(), &[]);
1348 /// assert_eq!(iter.next().unwrap(), &[20]);
1349 /// assert!(iter.next().is_none());
1351 #[stable(feature = "rust1", since = "1.0.0")]
1353 pub fn split<F>(&self, pred: F) -> Split<'_, T, F>
1355 F: FnMut(&T) -> bool,
1357 Split::new(self, pred)
1360 /// Returns an iterator over mutable subslices separated by elements that
1361 /// match `pred`. The matched element is not contained in the subslices.
1366 /// let mut v = [10, 40, 30, 20, 60, 50];
1368 /// for group in v.split_mut(|num| *num % 3 == 0) {
1371 /// assert_eq!(v, [1, 40, 30, 1, 60, 1]);
1373 #[stable(feature = "rust1", since = "1.0.0")]
1375 pub fn split_mut<F>(&mut self, pred: F) -> SplitMut<'_, T, F>
1377 F: FnMut(&T) -> bool,
1379 SplitMut::new(self, pred)
1382 /// Returns an iterator over subslices separated by elements that match
1383 /// `pred`. The matched element is contained in the end of the previous
1384 /// subslice as a terminator.
1389 /// #![feature(split_inclusive)]
1390 /// let slice = [10, 40, 33, 20];
1391 /// let mut iter = slice.split_inclusive(|num| num % 3 == 0);
1393 /// assert_eq!(iter.next().unwrap(), &[10, 40, 33]);
1394 /// assert_eq!(iter.next().unwrap(), &[20]);
1395 /// assert!(iter.next().is_none());
1398 /// If the last element of the slice is matched,
1399 /// that element will be considered the terminator of the preceding slice.
1400 /// That slice will be the last item returned by the iterator.
1403 /// #![feature(split_inclusive)]
1404 /// let slice = [3, 10, 40, 33];
1405 /// let mut iter = slice.split_inclusive(|num| num % 3 == 0);
1407 /// assert_eq!(iter.next().unwrap(), &[3]);
1408 /// assert_eq!(iter.next().unwrap(), &[10, 40, 33]);
1409 /// assert!(iter.next().is_none());
1411 #[unstable(feature = "split_inclusive", issue = "72360")]
1413 pub fn split_inclusive<F>(&self, pred: F) -> SplitInclusive<'_, T, F>
1415 F: FnMut(&T) -> bool,
1417 SplitInclusive::new(self, pred)
1420 /// Returns an iterator over mutable subslices separated by elements that
1421 /// match `pred`. The matched element is contained in the previous
1422 /// subslice as a terminator.
1427 /// #![feature(split_inclusive)]
1428 /// let mut v = [10, 40, 30, 20, 60, 50];
1430 /// for group in v.split_inclusive_mut(|num| *num % 3 == 0) {
1431 /// let terminator_idx = group.len()-1;
1432 /// group[terminator_idx] = 1;
1434 /// assert_eq!(v, [10, 40, 1, 20, 1, 1]);
1436 #[unstable(feature = "split_inclusive", issue = "72360")]
1438 pub fn split_inclusive_mut<F>(&mut self, pred: F) -> SplitInclusiveMut<'_, T, F>
1440 F: FnMut(&T) -> bool,
1442 SplitInclusiveMut::new(self, pred)
1445 /// Returns an iterator over subslices separated by elements that match
1446 /// `pred`, starting at the end of the slice and working backwards.
1447 /// The matched element is not contained in the subslices.
1452 /// let slice = [11, 22, 33, 0, 44, 55];
1453 /// let mut iter = slice.rsplit(|num| *num == 0);
1455 /// assert_eq!(iter.next().unwrap(), &[44, 55]);
1456 /// assert_eq!(iter.next().unwrap(), &[11, 22, 33]);
1457 /// assert_eq!(iter.next(), None);
1460 /// As with `split()`, if the first or last element is matched, an empty
1461 /// slice will be the first (or last) item returned by the iterator.
1464 /// let v = &[0, 1, 1, 2, 3, 5, 8];
1465 /// let mut it = v.rsplit(|n| *n % 2 == 0);
1466 /// assert_eq!(it.next().unwrap(), &[]);
1467 /// assert_eq!(it.next().unwrap(), &[3, 5]);
1468 /// assert_eq!(it.next().unwrap(), &[1, 1]);
1469 /// assert_eq!(it.next().unwrap(), &[]);
1470 /// assert_eq!(it.next(), None);
1472 #[stable(feature = "slice_rsplit", since = "1.27.0")]
1474 pub fn rsplit<F>(&self, pred: F) -> RSplit<'_, T, F>
1476 F: FnMut(&T) -> bool,
1478 RSplit::new(self, pred)
1481 /// Returns an iterator over mutable subslices separated by elements that
1482 /// match `pred`, starting at the end of the slice and working
1483 /// backwards. The matched element is not contained in the subslices.
1488 /// let mut v = [100, 400, 300, 200, 600, 500];
1490 /// let mut count = 0;
1491 /// for group in v.rsplit_mut(|num| *num % 3 == 0) {
1493 /// group[0] = count;
1495 /// assert_eq!(v, [3, 400, 300, 2, 600, 1]);
1498 #[stable(feature = "slice_rsplit", since = "1.27.0")]
1500 pub fn rsplit_mut<F>(&mut self, pred: F) -> RSplitMut<'_, T, F>
1502 F: FnMut(&T) -> bool,
1504 RSplitMut::new(self, pred)
1507 /// Returns an iterator over subslices separated by elements that match
1508 /// `pred`, limited to returning at most `n` items. The matched element is
1509 /// not contained in the subslices.
1511 /// The last element returned, if any, will contain the remainder of the
1516 /// Print the slice split once by numbers divisible by 3 (i.e., `[10, 40]`,
1517 /// `[20, 60, 50]`):
1520 /// let v = [10, 40, 30, 20, 60, 50];
1522 /// for group in v.splitn(2, |num| *num % 3 == 0) {
1523 /// println!("{:?}", group);
1526 #[stable(feature = "rust1", since = "1.0.0")]
1528 pub fn splitn<F>(&self, n: usize, pred: F) -> SplitN<'_, T, F>
1530 F: FnMut(&T) -> bool,
1532 SplitN::new(self.split(pred), n)
1535 /// Returns an iterator over subslices separated by elements that match
1536 /// `pred`, limited to returning at most `n` items. The matched element is
1537 /// not contained in the subslices.
1539 /// The last element returned, if any, will contain the remainder of the
1545 /// let mut v = [10, 40, 30, 20, 60, 50];
1547 /// for group in v.splitn_mut(2, |num| *num % 3 == 0) {
1550 /// assert_eq!(v, [1, 40, 30, 1, 60, 50]);
1552 #[stable(feature = "rust1", since = "1.0.0")]
1554 pub fn splitn_mut<F>(&mut self, n: usize, pred: F) -> SplitNMut<'_, T, F>
1556 F: FnMut(&T) -> bool,
1558 SplitNMut::new(self.split_mut(pred), n)
1561 /// Returns an iterator over subslices separated by elements that match
1562 /// `pred` limited to returning at most `n` items. This starts at the end of
1563 /// the slice and works backwards. The matched element is not contained in
1566 /// The last element returned, if any, will contain the remainder of the
1571 /// Print the slice split once, starting from the end, by numbers divisible
1572 /// by 3 (i.e., `[50]`, `[10, 40, 30, 20]`):
1575 /// let v = [10, 40, 30, 20, 60, 50];
1577 /// for group in v.rsplitn(2, |num| *num % 3 == 0) {
1578 /// println!("{:?}", group);
1581 #[stable(feature = "rust1", since = "1.0.0")]
1583 pub fn rsplitn<F>(&self, n: usize, pred: F) -> RSplitN<'_, T, F>
1585 F: FnMut(&T) -> bool,
1587 RSplitN::new(self.rsplit(pred), n)
1590 /// Returns an iterator over subslices separated by elements that match
1591 /// `pred` limited to returning at most `n` items. This starts at the end of
1592 /// the slice and works backwards. The matched element is not contained in
1595 /// The last element returned, if any, will contain the remainder of the
1601 /// let mut s = [10, 40, 30, 20, 60, 50];
1603 /// for group in s.rsplitn_mut(2, |num| *num % 3 == 0) {
1606 /// assert_eq!(s, [1, 40, 30, 20, 60, 1]);
1608 #[stable(feature = "rust1", since = "1.0.0")]
1610 pub fn rsplitn_mut<F>(&mut self, n: usize, pred: F) -> RSplitNMut<'_, T, F>
1612 F: FnMut(&T) -> bool,
1614 RSplitNMut::new(self.rsplit_mut(pred), n)
1617 /// Returns `true` if the slice contains an element with the given value.
1622 /// let v = [10, 40, 30];
1623 /// assert!(v.contains(&30));
1624 /// assert!(!v.contains(&50));
1627 /// If you do not have an `&T`, but just an `&U` such that `T: Borrow<U>`
1628 /// (e.g. `String: Borrow<str>`), you can use `iter().any`:
1631 /// let v = [String::from("hello"), String::from("world")]; // slice of `String`
1632 /// assert!(v.iter().any(|e| e == "hello")); // search with `&str`
1633 /// assert!(!v.iter().any(|e| e == "hi"));
1635 #[stable(feature = "rust1", since = "1.0.0")]
1636 pub fn contains(&self, x: &T) -> bool
1640 cmp::SliceContains::slice_contains(x, self)
1643 /// Returns `true` if `needle` is a prefix of the slice.
1648 /// let v = [10, 40, 30];
1649 /// assert!(v.starts_with(&[10]));
1650 /// assert!(v.starts_with(&[10, 40]));
1651 /// assert!(!v.starts_with(&[50]));
1652 /// assert!(!v.starts_with(&[10, 50]));
1655 /// Always returns `true` if `needle` is an empty slice:
1658 /// let v = &[10, 40, 30];
1659 /// assert!(v.starts_with(&[]));
1660 /// let v: &[u8] = &[];
1661 /// assert!(v.starts_with(&[]));
1663 #[stable(feature = "rust1", since = "1.0.0")]
1664 pub fn starts_with(&self, needle: &[T]) -> bool
1668 let n = needle.len();
1669 self.len() >= n && needle == &self[..n]
1672 /// Returns `true` if `needle` is a suffix of the slice.
1677 /// let v = [10, 40, 30];
1678 /// assert!(v.ends_with(&[30]));
1679 /// assert!(v.ends_with(&[40, 30]));
1680 /// assert!(!v.ends_with(&[50]));
1681 /// assert!(!v.ends_with(&[50, 30]));
1684 /// Always returns `true` if `needle` is an empty slice:
1687 /// let v = &[10, 40, 30];
1688 /// assert!(v.ends_with(&[]));
1689 /// let v: &[u8] = &[];
1690 /// assert!(v.ends_with(&[]));
1692 #[stable(feature = "rust1", since = "1.0.0")]
1693 pub fn ends_with(&self, needle: &[T]) -> bool
1697 let (m, n) = (self.len(), needle.len());
1698 m >= n && needle == &self[m - n..]
1701 /// Returns a subslice with the prefix removed.
1703 /// This method returns [`None`] if slice does not start with `prefix`.
1704 /// Also it returns the original slice if `prefix` is an empty slice.
1709 /// #![feature(slice_strip)]
1710 /// let v = &[10, 40, 30];
1711 /// assert_eq!(v.strip_prefix(&[10]), Some(&[40, 30][..]));
1712 /// assert_eq!(v.strip_prefix(&[10, 40]), Some(&[30][..]));
1713 /// assert_eq!(v.strip_prefix(&[50]), None);
1714 /// assert_eq!(v.strip_prefix(&[10, 50]), None);
1716 #[must_use = "returns the subslice without modifying the original"]
1717 #[unstable(feature = "slice_strip", issue = "73413")]
1718 pub fn strip_prefix(&self, prefix: &[T]) -> Option<&[T]>
1722 let n = prefix.len();
1723 if n <= self.len() {
1724 let (head, tail) = self.split_at(n);
1732 /// Returns a subslice with the suffix removed.
1734 /// This method returns [`None`] if slice does not end with `suffix`.
1735 /// Also it returns the original slice if `suffix` is an empty slice
1740 /// #![feature(slice_strip)]
1741 /// let v = &[10, 40, 30];
1742 /// assert_eq!(v.strip_suffix(&[30]), Some(&[10, 40][..]));
1743 /// assert_eq!(v.strip_suffix(&[40, 30]), Some(&[10][..]));
1744 /// assert_eq!(v.strip_suffix(&[50]), None);
1745 /// assert_eq!(v.strip_suffix(&[50, 30]), None);
1747 #[must_use = "returns the subslice without modifying the original"]
1748 #[unstable(feature = "slice_strip", issue = "73413")]
1749 pub fn strip_suffix(&self, suffix: &[T]) -> Option<&[T]>
1753 let (len, n) = (self.len(), suffix.len());
1755 let (head, tail) = self.split_at(len - n);
1763 /// Binary searches this sorted slice for a given element.
1765 /// If the value is found then [`Result::Ok`] is returned, containing the
1766 /// index of the matching element. If there are multiple matches, then any
1767 /// one of the matches could be returned. If the value is not found then
1768 /// [`Result::Err`] is returned, containing the index where a matching
1769 /// element could be inserted while maintaining sorted order.
1773 /// Looks up a series of four elements. The first is found, with a
1774 /// uniquely determined position; the second and third are not
1775 /// found; the fourth could match any position in `[1, 4]`.
1778 /// let s = [0, 1, 1, 1, 1, 2, 3, 5, 8, 13, 21, 34, 55];
1780 /// assert_eq!(s.binary_search(&13), Ok(9));
1781 /// assert_eq!(s.binary_search(&4), Err(7));
1782 /// assert_eq!(s.binary_search(&100), Err(13));
1783 /// let r = s.binary_search(&1);
1784 /// assert!(match r { Ok(1..=4) => true, _ => false, });
1787 /// If you want to insert an item to a sorted vector, while maintaining
1791 /// let mut s = vec![0, 1, 1, 1, 1, 2, 3, 5, 8, 13, 21, 34, 55];
1793 /// let idx = s.binary_search(&num).unwrap_or_else(|x| x);
1794 /// s.insert(idx, num);
1795 /// assert_eq!(s, [0, 1, 1, 1, 1, 2, 3, 5, 8, 13, 21, 34, 42, 55]);
1797 #[stable(feature = "rust1", since = "1.0.0")]
1798 pub fn binary_search(&self, x: &T) -> Result<usize, usize>
1802 self.binary_search_by(|p| p.cmp(x))
1805 /// Binary searches this sorted slice with a comparator function.
1807 /// The comparator function should implement an order consistent
1808 /// with the sort order of the underlying slice, returning an
1809 /// order code that indicates whether its argument is `Less`,
1810 /// `Equal` or `Greater` the desired target.
1812 /// If the value is found then [`Result::Ok`] is returned, containing the
1813 /// index of the matching element. If there are multiple matches, then any
1814 /// one of the matches could be returned. If the value is not found then
1815 /// [`Result::Err`] is returned, containing the index where a matching
1816 /// element could be inserted while maintaining sorted order.
1820 /// Looks up a series of four elements. The first is found, with a
1821 /// uniquely determined position; the second and third are not
1822 /// found; the fourth could match any position in `[1, 4]`.
1825 /// let s = [0, 1, 1, 1, 1, 2, 3, 5, 8, 13, 21, 34, 55];
1828 /// assert_eq!(s.binary_search_by(|probe| probe.cmp(&seek)), Ok(9));
1830 /// assert_eq!(s.binary_search_by(|probe| probe.cmp(&seek)), Err(7));
1832 /// assert_eq!(s.binary_search_by(|probe| probe.cmp(&seek)), Err(13));
1834 /// let r = s.binary_search_by(|probe| probe.cmp(&seek));
1835 /// assert!(match r { Ok(1..=4) => true, _ => false, });
1837 #[stable(feature = "rust1", since = "1.0.0")]
1839 pub fn binary_search_by<'a, F>(&'a self, mut f: F) -> Result<usize, usize>
1841 F: FnMut(&'a T) -> Ordering,
1844 let mut size = s.len();
1848 let mut base = 0usize;
1850 let half = size / 2;
1851 let mid = base + half;
1852 // SAFETY: the call is made safe by the following inconstants:
1853 // - `mid >= 0`: by definition
1854 // - `mid < size`: `mid = size / 2 + size / 4 + size / 8 ...`
1855 let cmp = f(unsafe { s.get_unchecked(mid) });
1856 base = if cmp == Greater { base } else { mid };
1859 // SAFETY: base is always in [0, size) because base <= mid.
1860 let cmp = f(unsafe { s.get_unchecked(base) });
1861 if cmp == Equal { Ok(base) } else { Err(base + (cmp == Less) as usize) }
1864 /// Binary searches this sorted slice with a key extraction function.
1866 /// Assumes that the slice is sorted by the key, for instance with
1867 /// [`sort_by_key`] using the same key extraction function.
1869 /// If the value is found then [`Result::Ok`] is returned, containing the
1870 /// index of the matching element. If there are multiple matches, then any
1871 /// one of the matches could be returned. If the value is not found then
1872 /// [`Result::Err`] is returned, containing the index where a matching
1873 /// element could be inserted while maintaining sorted order.
1875 /// [`sort_by_key`]: #method.sort_by_key
1879 /// Looks up a series of four elements in a slice of pairs sorted by
1880 /// their second elements. The first is found, with a uniquely
1881 /// determined position; the second and third are not found; the
1882 /// fourth could match any position in `[1, 4]`.
1885 /// let s = [(0, 0), (2, 1), (4, 1), (5, 1), (3, 1),
1886 /// (1, 2), (2, 3), (4, 5), (5, 8), (3, 13),
1887 /// (1, 21), (2, 34), (4, 55)];
1889 /// assert_eq!(s.binary_search_by_key(&13, |&(a,b)| b), Ok(9));
1890 /// assert_eq!(s.binary_search_by_key(&4, |&(a,b)| b), Err(7));
1891 /// assert_eq!(s.binary_search_by_key(&100, |&(a,b)| b), Err(13));
1892 /// let r = s.binary_search_by_key(&1, |&(a,b)| b);
1893 /// assert!(match r { Ok(1..=4) => true, _ => false, });
1895 #[stable(feature = "slice_binary_search_by_key", since = "1.10.0")]
1897 pub fn binary_search_by_key<'a, B, F>(&'a self, b: &B, mut f: F) -> Result<usize, usize>
1899 F: FnMut(&'a T) -> B,
1902 self.binary_search_by(|k| f(k).cmp(b))
1905 /// Sorts the slice, but may not preserve the order of equal elements.
1907 /// This sort is unstable (i.e., may reorder equal elements), in-place
1908 /// (i.e., does not allocate), and *O*(*n* \* log(*n*)) worst-case.
1910 /// # Current implementation
1912 /// The current algorithm is based on [pattern-defeating quicksort][pdqsort] by Orson Peters,
1913 /// which combines the fast average case of randomized quicksort with the fast worst case of
1914 /// heapsort, while achieving linear time on slices with certain patterns. It uses some
1915 /// randomization to avoid degenerate cases, but with a fixed seed to always provide
1916 /// deterministic behavior.
1918 /// It is typically faster than stable sorting, except in a few special cases, e.g., when the
1919 /// slice consists of several concatenated sorted sequences.
1924 /// let mut v = [-5, 4, 1, -3, 2];
1926 /// v.sort_unstable();
1927 /// assert!(v == [-5, -3, 1, 2, 4]);
1930 /// [pdqsort]: https://github.com/orlp/pdqsort
1931 #[stable(feature = "sort_unstable", since = "1.20.0")]
1933 pub fn sort_unstable(&mut self)
1937 sort::quicksort(self, |a, b| a.lt(b));
1940 /// Sorts the slice with a comparator function, but may not preserve the order of equal
1943 /// This sort is unstable (i.e., may reorder equal elements), in-place
1944 /// (i.e., does not allocate), and *O*(*n* \* log(*n*)) worst-case.
1946 /// The comparator function must define a total ordering for the elements in the slice. If
1947 /// the ordering is not total, the order of the elements is unspecified. An order is a
1948 /// total order if it is (for all a, b and c):
1950 /// * total and antisymmetric: exactly one of a < b, a == b or a > b is true; and
1951 /// * transitive, a < b and b < c implies a < c. The same must hold for both == and >.
1953 /// For example, while [`f64`] doesn't implement [`Ord`] because `NaN != NaN`, we can use
1954 /// `partial_cmp` as our sort function when we know the slice doesn't contain a `NaN`.
1957 /// let mut floats = [5f64, 4.0, 1.0, 3.0, 2.0];
1958 /// floats.sort_unstable_by(|a, b| a.partial_cmp(b).unwrap());
1959 /// assert_eq!(floats, [1.0, 2.0, 3.0, 4.0, 5.0]);
1962 /// # Current implementation
1964 /// The current algorithm is based on [pattern-defeating quicksort][pdqsort] by Orson Peters,
1965 /// which combines the fast average case of randomized quicksort with the fast worst case of
1966 /// heapsort, while achieving linear time on slices with certain patterns. It uses some
1967 /// randomization to avoid degenerate cases, but with a fixed seed to always provide
1968 /// deterministic behavior.
1970 /// It is typically faster than stable sorting, except in a few special cases, e.g., when the
1971 /// slice consists of several concatenated sorted sequences.
1976 /// let mut v = [5, 4, 1, 3, 2];
1977 /// v.sort_unstable_by(|a, b| a.cmp(b));
1978 /// assert!(v == [1, 2, 3, 4, 5]);
1980 /// // reverse sorting
1981 /// v.sort_unstable_by(|a, b| b.cmp(a));
1982 /// assert!(v == [5, 4, 3, 2, 1]);
1985 /// [pdqsort]: https://github.com/orlp/pdqsort
1986 #[stable(feature = "sort_unstable", since = "1.20.0")]
1988 pub fn sort_unstable_by<F>(&mut self, mut compare: F)
1990 F: FnMut(&T, &T) -> Ordering,
1992 sort::quicksort(self, |a, b| compare(a, b) == Ordering::Less);
1995 /// Sorts the slice with a key extraction function, but may not preserve the order of equal
1998 /// This sort is unstable (i.e., may reorder equal elements), in-place
1999 /// (i.e., does not allocate), and *O*(m \* *n* \* log(*n*)) worst-case, where the key function is
2002 /// # Current implementation
2004 /// The current algorithm is based on [pattern-defeating quicksort][pdqsort] by Orson Peters,
2005 /// which combines the fast average case of randomized quicksort with the fast worst case of
2006 /// heapsort, while achieving linear time on slices with certain patterns. It uses some
2007 /// randomization to avoid degenerate cases, but with a fixed seed to always provide
2008 /// deterministic behavior.
2010 /// Due to its key calling strategy, [`sort_unstable_by_key`](#method.sort_unstable_by_key)
2011 /// is likely to be slower than [`sort_by_cached_key`](#method.sort_by_cached_key) in
2012 /// cases where the key function is expensive.
2017 /// let mut v = [-5i32, 4, 1, -3, 2];
2019 /// v.sort_unstable_by_key(|k| k.abs());
2020 /// assert!(v == [1, 2, -3, 4, -5]);
2023 /// [pdqsort]: https://github.com/orlp/pdqsort
2024 #[stable(feature = "sort_unstable", since = "1.20.0")]
2026 pub fn sort_unstable_by_key<K, F>(&mut self, mut f: F)
2031 sort::quicksort(self, |a, b| f(a).lt(&f(b)));
2034 /// Reorder the slice such that the element at `index` is at its final sorted position.
2036 /// This reordering has the additional property that any value at position `i < index` will be
2037 /// less than or equal to any value at a position `j > index`. Additionally, this reordering is
2038 /// unstable (i.e. any number of equal elements may end up at position `index`), in-place
2039 /// (i.e. does not allocate), and *O*(*n*) worst-case. This function is also/ known as "kth
2040 /// element" in other libraries. It returns a triplet of the following values: all elements less
2041 /// than the one at the given index, the value at the given index, and all elements greater than
2042 /// the one at the given index.
2044 /// # Current implementation
2046 /// The current algorithm is based on the quickselect portion of the same quicksort algorithm
2047 /// used for [`sort_unstable`].
2049 /// [`sort_unstable`]: #method.sort_unstable
2053 /// Panics when `index >= len()`, meaning it always panics on empty slices.
2058 /// #![feature(slice_partition_at_index)]
2060 /// let mut v = [-5i32, 4, 1, -3, 2];
2062 /// // Find the median
2063 /// v.partition_at_index(2);
2065 /// // We are only guaranteed the slice will be one of the following, based on the way we sort
2066 /// // about the specified index.
2067 /// assert!(v == [-3, -5, 1, 2, 4] ||
2068 /// v == [-5, -3, 1, 2, 4] ||
2069 /// v == [-3, -5, 1, 4, 2] ||
2070 /// v == [-5, -3, 1, 4, 2]);
2072 #[unstable(feature = "slice_partition_at_index", issue = "55300")]
2074 pub fn partition_at_index(&mut self, index: usize) -> (&mut [T], &mut T, &mut [T])
2078 let mut f = |a: &T, b: &T| a.lt(b);
2079 sort::partition_at_index(self, index, &mut f)
2082 /// Reorder the slice with a comparator function such that the element at `index` is at its
2083 /// final sorted position.
2085 /// This reordering has the additional property that any value at position `i < index` will be
2086 /// less than or equal to any value at a position `j > index` using the comparator function.
2087 /// Additionally, this reordering is unstable (i.e. any number of equal elements may end up at
2088 /// position `index`), in-place (i.e. does not allocate), and *O*(*n*) worst-case. This function
2089 /// is also known as "kth element" in other libraries. It returns a triplet of the following
2090 /// values: all elements less than the one at the given index, the value at the given index,
2091 /// and all elements greater than the one at the given index, using the provided comparator
2094 /// # Current implementation
2096 /// The current algorithm is based on the quickselect portion of the same quicksort algorithm
2097 /// used for [`sort_unstable`].
2099 /// [`sort_unstable`]: #method.sort_unstable
2103 /// Panics when `index >= len()`, meaning it always panics on empty slices.
2108 /// #![feature(slice_partition_at_index)]
2110 /// let mut v = [-5i32, 4, 1, -3, 2];
2112 /// // Find the median as if the slice were sorted in descending order.
2113 /// v.partition_at_index_by(2, |a, b| b.cmp(a));
2115 /// // We are only guaranteed the slice will be one of the following, based on the way we sort
2116 /// // about the specified index.
2117 /// assert!(v == [2, 4, 1, -5, -3] ||
2118 /// v == [2, 4, 1, -3, -5] ||
2119 /// v == [4, 2, 1, -5, -3] ||
2120 /// v == [4, 2, 1, -3, -5]);
2122 #[unstable(feature = "slice_partition_at_index", issue = "55300")]
2124 pub fn partition_at_index_by<F>(
2128 ) -> (&mut [T], &mut T, &mut [T])
2130 F: FnMut(&T, &T) -> Ordering,
2132 let mut f = |a: &T, b: &T| compare(a, b) == Less;
2133 sort::partition_at_index(self, index, &mut f)
2136 /// Reorder the slice with a key extraction function such that the element at `index` is at its
2137 /// final sorted position.
2139 /// This reordering has the additional property that any value at position `i < index` will be
2140 /// less than or equal to any value at a position `j > index` using the key extraction function.
2141 /// Additionally, this reordering is unstable (i.e. any number of equal elements may end up at
2142 /// position `index`), in-place (i.e. does not allocate), and *O*(*n*) worst-case. This function
2143 /// is also known as "kth element" in other libraries. It returns a triplet of the following
2144 /// values: all elements less than the one at the given index, the value at the given index, and
2145 /// all elements greater than the one at the given index, using the provided key extraction
2148 /// # Current implementation
2150 /// The current algorithm is based on the quickselect portion of the same quicksort algorithm
2151 /// used for [`sort_unstable`].
2153 /// [`sort_unstable`]: #method.sort_unstable
2157 /// Panics when `index >= len()`, meaning it always panics on empty slices.
2162 /// #![feature(slice_partition_at_index)]
2164 /// let mut v = [-5i32, 4, 1, -3, 2];
2166 /// // Return the median as if the array were sorted according to absolute value.
2167 /// v.partition_at_index_by_key(2, |a| a.abs());
2169 /// // We are only guaranteed the slice will be one of the following, based on the way we sort
2170 /// // about the specified index.
2171 /// assert!(v == [1, 2, -3, 4, -5] ||
2172 /// v == [1, 2, -3, -5, 4] ||
2173 /// v == [2, 1, -3, 4, -5] ||
2174 /// v == [2, 1, -3, -5, 4]);
2176 #[unstable(feature = "slice_partition_at_index", issue = "55300")]
2178 pub fn partition_at_index_by_key<K, F>(
2182 ) -> (&mut [T], &mut T, &mut [T])
2187 let mut g = |a: &T, b: &T| f(a).lt(&f(b));
2188 sort::partition_at_index(self, index, &mut g)
2191 /// Moves all consecutive repeated elements to the end of the slice according to the
2192 /// [`PartialEq`] trait implementation.
2194 /// Returns two slices. The first contains no consecutive repeated elements.
2195 /// The second contains all the duplicates in no specified order.
2197 /// If the slice is sorted, the first returned slice contains no duplicates.
2202 /// #![feature(slice_partition_dedup)]
2204 /// let mut slice = [1, 2, 2, 3, 3, 2, 1, 1];
2206 /// let (dedup, duplicates) = slice.partition_dedup();
2208 /// assert_eq!(dedup, [1, 2, 3, 2, 1]);
2209 /// assert_eq!(duplicates, [2, 3, 1]);
2211 #[unstable(feature = "slice_partition_dedup", issue = "54279")]
2213 pub fn partition_dedup(&mut self) -> (&mut [T], &mut [T])
2217 self.partition_dedup_by(|a, b| a == b)
2220 /// Moves all but the first of consecutive elements to the end of the slice satisfying
2221 /// a given equality relation.
2223 /// Returns two slices. The first contains no consecutive repeated elements.
2224 /// The second contains all the duplicates in no specified order.
2226 /// The `same_bucket` function is passed references to two elements from the slice and
2227 /// must determine if the elements compare equal. The elements are passed in opposite order
2228 /// from their order in the slice, so if `same_bucket(a, b)` returns `true`, `a` is moved
2229 /// at the end of the slice.
2231 /// If the slice is sorted, the first returned slice contains no duplicates.
2236 /// #![feature(slice_partition_dedup)]
2238 /// let mut slice = ["foo", "Foo", "BAZ", "Bar", "bar", "baz", "BAZ"];
2240 /// let (dedup, duplicates) = slice.partition_dedup_by(|a, b| a.eq_ignore_ascii_case(b));
2242 /// assert_eq!(dedup, ["foo", "BAZ", "Bar", "baz"]);
2243 /// assert_eq!(duplicates, ["bar", "Foo", "BAZ"]);
2245 #[unstable(feature = "slice_partition_dedup", issue = "54279")]
2247 pub fn partition_dedup_by<F>(&mut self, mut same_bucket: F) -> (&mut [T], &mut [T])
2249 F: FnMut(&mut T, &mut T) -> bool,
2251 // Although we have a mutable reference to `self`, we cannot make
2252 // *arbitrary* changes. The `same_bucket` calls could panic, so we
2253 // must ensure that the slice is in a valid state at all times.
2255 // The way that we handle this is by using swaps; we iterate
2256 // over all the elements, swapping as we go so that at the end
2257 // the elements we wish to keep are in the front, and those we
2258 // wish to reject are at the back. We can then split the slice.
2259 // This operation is still `O(n)`.
2261 // Example: We start in this state, where `r` represents "next
2262 // read" and `w` represents "next_write`.
2265 // +---+---+---+---+---+---+
2266 // | 0 | 1 | 1 | 2 | 3 | 3 |
2267 // +---+---+---+---+---+---+
2270 // Comparing self[r] against self[w-1], this is not a duplicate, so
2271 // we swap self[r] and self[w] (no effect as r==w) and then increment both
2272 // r and w, leaving us with:
2275 // +---+---+---+---+---+---+
2276 // | 0 | 1 | 1 | 2 | 3 | 3 |
2277 // +---+---+---+---+---+---+
2280 // Comparing self[r] against self[w-1], this value is a duplicate,
2281 // so we increment `r` but leave everything else unchanged:
2284 // +---+---+---+---+---+---+
2285 // | 0 | 1 | 1 | 2 | 3 | 3 |
2286 // +---+---+---+---+---+---+
2289 // Comparing self[r] against self[w-1], this is not a duplicate,
2290 // so swap self[r] and self[w] and advance r and w:
2293 // +---+---+---+---+---+---+
2294 // | 0 | 1 | 2 | 1 | 3 | 3 |
2295 // +---+---+---+---+---+---+
2298 // Not a duplicate, repeat:
2301 // +---+---+---+---+---+---+
2302 // | 0 | 1 | 2 | 3 | 1 | 3 |
2303 // +---+---+---+---+---+---+
2306 // Duplicate, advance r. End of slice. Split at w.
2308 let len = self.len();
2310 return (self, &mut []);
2313 let ptr = self.as_mut_ptr();
2314 let mut next_read: usize = 1;
2315 let mut next_write: usize = 1;
2317 // SAFETY: the `while` condition guarantees `next_read` and `next_write`
2318 // are less than `len`, thus are inside `self`. `prev_ptr_write` points to
2319 // one element before `ptr_write`, but `next_write` starts at 1, so
2320 // `prev_ptr_write` is never less than 0 and is inside the slice.
2321 // This fulfils the requirements for dereferencing `ptr_read`, `prev_ptr_write`
2322 // and `ptr_write`, and for using `ptr.add(next_read)`, `ptr.add(next_write - 1)`
2323 // and `prev_ptr_write.offset(1)`.
2325 // `next_write` is also incremented at most once per loop at most meaning
2326 // no element is skipped when it may need to be swapped.
2328 // `ptr_read` and `prev_ptr_write` never point to the same element. This
2329 // is required for `&mut *ptr_read`, `&mut *prev_ptr_write` to be safe.
2330 // The explanation is simply that `next_read >= next_write` is always true,
2331 // thus `next_read > next_write - 1` is too.
2333 // Avoid bounds checks by using raw pointers.
2334 while next_read < len {
2335 let ptr_read = ptr.add(next_read);
2336 let prev_ptr_write = ptr.add(next_write - 1);
2337 if !same_bucket(&mut *ptr_read, &mut *prev_ptr_write) {
2338 if next_read != next_write {
2339 let ptr_write = prev_ptr_write.offset(1);
2340 mem::swap(&mut *ptr_read, &mut *ptr_write);
2348 self.split_at_mut(next_write)
2351 /// Moves all but the first of consecutive elements to the end of the slice that resolve
2352 /// to the same key.
2354 /// Returns two slices. The first contains no consecutive repeated elements.
2355 /// The second contains all the duplicates in no specified order.
2357 /// If the slice is sorted, the first returned slice contains no duplicates.
2362 /// #![feature(slice_partition_dedup)]
2364 /// let mut slice = [10, 20, 21, 30, 30, 20, 11, 13];
2366 /// let (dedup, duplicates) = slice.partition_dedup_by_key(|i| *i / 10);
2368 /// assert_eq!(dedup, [10, 20, 30, 20, 11]);
2369 /// assert_eq!(duplicates, [21, 30, 13]);
2371 #[unstable(feature = "slice_partition_dedup", issue = "54279")]
2373 pub fn partition_dedup_by_key<K, F>(&mut self, mut key: F) -> (&mut [T], &mut [T])
2375 F: FnMut(&mut T) -> K,
2378 self.partition_dedup_by(|a, b| key(a) == key(b))
2381 /// Rotates the slice in-place such that the first `mid` elements of the
2382 /// slice move to the end while the last `self.len() - mid` elements move to
2383 /// the front. After calling `rotate_left`, the element previously at index
2384 /// `mid` will become the first element in the slice.
2388 /// This function will panic if `mid` is greater than the length of the
2389 /// slice. Note that `mid == self.len()` does _not_ panic and is a no-op
2394 /// Takes linear (in `self.len()`) time.
2399 /// let mut a = ['a', 'b', 'c', 'd', 'e', 'f'];
2400 /// a.rotate_left(2);
2401 /// assert_eq!(a, ['c', 'd', 'e', 'f', 'a', 'b']);
2404 /// Rotating a subslice:
2407 /// let mut a = ['a', 'b', 'c', 'd', 'e', 'f'];
2408 /// a[1..5].rotate_left(1);
2409 /// assert_eq!(a, ['a', 'c', 'd', 'e', 'b', 'f']);
2411 #[stable(feature = "slice_rotate", since = "1.26.0")]
2412 pub fn rotate_left(&mut self, mid: usize) {
2413 assert!(mid <= self.len());
2414 let k = self.len() - mid;
2415 let p = self.as_mut_ptr();
2417 // SAFETY: The range `[p.add(mid) - mid, p.add(mid) + k)` is trivially
2418 // valid for reading and writing, as required by `ptr_rotate`.
2420 rotate::ptr_rotate(mid, p.add(mid), k);
2424 /// Rotates the slice in-place such that the first `self.len() - k`
2425 /// elements of the slice move to the end while the last `k` elements move
2426 /// to the front. After calling `rotate_right`, the element previously at
2427 /// index `self.len() - k` will become the first element in the slice.
2431 /// This function will panic if `k` is greater than the length of the
2432 /// slice. Note that `k == self.len()` does _not_ panic and is a no-op
2437 /// Takes linear (in `self.len()`) time.
2442 /// let mut a = ['a', 'b', 'c', 'd', 'e', 'f'];
2443 /// a.rotate_right(2);
2444 /// assert_eq!(a, ['e', 'f', 'a', 'b', 'c', 'd']);
2447 /// Rotate a subslice:
2450 /// let mut a = ['a', 'b', 'c', 'd', 'e', 'f'];
2451 /// a[1..5].rotate_right(1);
2452 /// assert_eq!(a, ['a', 'e', 'b', 'c', 'd', 'f']);
2454 #[stable(feature = "slice_rotate", since = "1.26.0")]
2455 pub fn rotate_right(&mut self, k: usize) {
2456 assert!(k <= self.len());
2457 let mid = self.len() - k;
2458 let p = self.as_mut_ptr();
2460 // SAFETY: The range `[p.add(mid) - mid, p.add(mid) + k)` is trivially
2461 // valid for reading and writing, as required by `ptr_rotate`.
2463 rotate::ptr_rotate(mid, p.add(mid), k);
2467 /// Fills `self` with elements by cloning `value`.
2472 /// #![feature(slice_fill)]
2474 /// let mut buf = vec![0; 10];
2476 /// assert_eq!(buf, vec![1; 10]);
2478 #[unstable(feature = "slice_fill", issue = "70758")]
2479 pub fn fill(&mut self, value: T)
2483 if let Some((last, elems)) = self.split_last_mut() {
2485 el.clone_from(&value);
2492 /// Copies the elements from `src` into `self`.
2494 /// The length of `src` must be the same as `self`.
2496 /// If `T` implements `Copy`, it can be more performant to use
2497 /// [`copy_from_slice`].
2501 /// This function will panic if the two slices have different lengths.
2505 /// Cloning two elements from a slice into another:
2508 /// let src = [1, 2, 3, 4];
2509 /// let mut dst = [0, 0];
2511 /// // Because the slices have to be the same length,
2512 /// // we slice the source slice from four elements
2513 /// // to two. It will panic if we don't do this.
2514 /// dst.clone_from_slice(&src[2..]);
2516 /// assert_eq!(src, [1, 2, 3, 4]);
2517 /// assert_eq!(dst, [3, 4]);
2520 /// Rust enforces that there can only be one mutable reference with no
2521 /// immutable references to a particular piece of data in a particular
2522 /// scope. Because of this, attempting to use `clone_from_slice` on a
2523 /// single slice will result in a compile failure:
2526 /// let mut slice = [1, 2, 3, 4, 5];
2528 /// slice[..2].clone_from_slice(&slice[3..]); // compile fail!
2531 /// To work around this, we can use [`split_at_mut`] to create two distinct
2532 /// sub-slices from a slice:
2535 /// let mut slice = [1, 2, 3, 4, 5];
2538 /// let (left, right) = slice.split_at_mut(2);
2539 /// left.clone_from_slice(&right[1..]);
2542 /// assert_eq!(slice, [4, 5, 3, 4, 5]);
2545 /// [`copy_from_slice`]: #method.copy_from_slice
2546 /// [`split_at_mut`]: #method.split_at_mut
2547 #[stable(feature = "clone_from_slice", since = "1.7.0")]
2548 pub fn clone_from_slice(&mut self, src: &[T])
2552 assert!(self.len() == src.len(), "destination and source slices have different lengths");
2553 // NOTE: We need to explicitly slice them to the same length
2554 // for bounds checking to be elided, and the optimizer will
2555 // generate memcpy for simple cases (for example T = u8).
2556 let len = self.len();
2557 let src = &src[..len];
2559 self[i].clone_from(&src[i]);
2563 /// Copies all elements from `src` into `self`, using a memcpy.
2565 /// The length of `src` must be the same as `self`.
2567 /// If `T` does not implement `Copy`, use [`clone_from_slice`].
2571 /// This function will panic if the two slices have different lengths.
2575 /// Copying two elements from a slice into another:
2578 /// let src = [1, 2, 3, 4];
2579 /// let mut dst = [0, 0];
2581 /// // Because the slices have to be the same length,
2582 /// // we slice the source slice from four elements
2583 /// // to two. It will panic if we don't do this.
2584 /// dst.copy_from_slice(&src[2..]);
2586 /// assert_eq!(src, [1, 2, 3, 4]);
2587 /// assert_eq!(dst, [3, 4]);
2590 /// Rust enforces that there can only be one mutable reference with no
2591 /// immutable references to a particular piece of data in a particular
2592 /// scope. Because of this, attempting to use `copy_from_slice` on a
2593 /// single slice will result in a compile failure:
2596 /// let mut slice = [1, 2, 3, 4, 5];
2598 /// slice[..2].copy_from_slice(&slice[3..]); // compile fail!
2601 /// To work around this, we can use [`split_at_mut`] to create two distinct
2602 /// sub-slices from a slice:
2605 /// let mut slice = [1, 2, 3, 4, 5];
2608 /// let (left, right) = slice.split_at_mut(2);
2609 /// left.copy_from_slice(&right[1..]);
2612 /// assert_eq!(slice, [4, 5, 3, 4, 5]);
2615 /// [`clone_from_slice`]: #method.clone_from_slice
2616 /// [`split_at_mut`]: #method.split_at_mut
2617 #[stable(feature = "copy_from_slice", since = "1.9.0")]
2618 pub fn copy_from_slice(&mut self, src: &[T])
2622 // The panic code path was put into a cold function to not bloat the
2627 fn len_mismatch_fail(dst_len: usize, src_len: usize) -> ! {
2629 "source slice length ({}) does not match destination slice length ({})",
2634 if self.len() != src.len() {
2635 len_mismatch_fail(self.len(), src.len());
2638 // SAFETY: `self` is valid for `self.len()` elements by definition, and `src` was
2639 // checked to have the same length. The slices cannot overlap because
2640 // mutable references are exclusive.
2642 ptr::copy_nonoverlapping(src.as_ptr(), self.as_mut_ptr(), self.len());
2646 /// Copies elements from one part of the slice to another part of itself,
2647 /// using a memmove.
2649 /// `src` is the range within `self` to copy from. `dest` is the starting
2650 /// index of the range within `self` to copy to, which will have the same
2651 /// length as `src`. The two ranges may overlap. The ends of the two ranges
2652 /// must be less than or equal to `self.len()`.
2656 /// This function will panic if either range exceeds the end of the slice,
2657 /// or if the end of `src` is before the start.
2661 /// Copying four bytes within a slice:
2664 /// let mut bytes = *b"Hello, World!";
2666 /// bytes.copy_within(1..5, 8);
2668 /// assert_eq!(&bytes, b"Hello, Wello!");
2670 #[stable(feature = "copy_within", since = "1.37.0")]
2672 pub fn copy_within<R: RangeBounds<usize>>(&mut self, src: R, dest: usize)
2676 let Range { start: src_start, end: src_end } = check_range(self.len(), src);
2677 let count = src_end - src_start;
2678 assert!(dest <= self.len() - count, "dest is out of bounds");
2679 // SAFETY: the conditions for `ptr::copy` have all been checked above,
2680 // as have those for `ptr::add`.
2682 ptr::copy(self.as_ptr().add(src_start), self.as_mut_ptr().add(dest), count);
2686 /// Swaps all elements in `self` with those in `other`.
2688 /// The length of `other` must be the same as `self`.
2692 /// This function will panic if the two slices have different lengths.
2696 /// Swapping two elements across slices:
2699 /// let mut slice1 = [0, 0];
2700 /// let mut slice2 = [1, 2, 3, 4];
2702 /// slice1.swap_with_slice(&mut slice2[2..]);
2704 /// assert_eq!(slice1, [3, 4]);
2705 /// assert_eq!(slice2, [1, 2, 0, 0]);
2708 /// Rust enforces that there can only be one mutable reference to a
2709 /// particular piece of data in a particular scope. Because of this,
2710 /// attempting to use `swap_with_slice` on a single slice will result in
2711 /// a compile failure:
2714 /// let mut slice = [1, 2, 3, 4, 5];
2715 /// slice[..2].swap_with_slice(&mut slice[3..]); // compile fail!
2718 /// To work around this, we can use [`split_at_mut`] to create two distinct
2719 /// mutable sub-slices from a slice:
2722 /// let mut slice = [1, 2, 3, 4, 5];
2725 /// let (left, right) = slice.split_at_mut(2);
2726 /// left.swap_with_slice(&mut right[1..]);
2729 /// assert_eq!(slice, [4, 5, 3, 1, 2]);
2732 /// [`split_at_mut`]: #method.split_at_mut
2733 #[stable(feature = "swap_with_slice", since = "1.27.0")]
2734 pub fn swap_with_slice(&mut self, other: &mut [T]) {
2735 assert!(self.len() == other.len(), "destination and source slices have different lengths");
2736 // SAFETY: `self` is valid for `self.len()` elements by definition, and `src` was
2737 // checked to have the same length. The slices cannot overlap because
2738 // mutable references are exclusive.
2740 ptr::swap_nonoverlapping(self.as_mut_ptr(), other.as_mut_ptr(), self.len());
2744 /// Function to calculate lengths of the middle and trailing slice for `align_to{,_mut}`.
2745 fn align_to_offsets<U>(&self) -> (usize, usize) {
2746 // What we gonna do about `rest` is figure out what multiple of `U`s we can put in a
2747 // lowest number of `T`s. And how many `T`s we need for each such "multiple".
2749 // Consider for example T=u8 U=u16. Then we can put 1 U in 2 Ts. Simple. Now, consider
2750 // for example a case where size_of::<T> = 16, size_of::<U> = 24. We can put 2 Us in
2751 // place of every 3 Ts in the `rest` slice. A bit more complicated.
2753 // Formula to calculate this is:
2755 // Us = lcm(size_of::<T>, size_of::<U>) / size_of::<U>
2756 // Ts = lcm(size_of::<T>, size_of::<U>) / size_of::<T>
2758 // Expanded and simplified:
2760 // Us = size_of::<T> / gcd(size_of::<T>, size_of::<U>)
2761 // Ts = size_of::<U> / gcd(size_of::<T>, size_of::<U>)
2763 // Luckily since all this is constant-evaluated... performance here matters not!
2765 fn gcd(a: usize, b: usize) -> usize {
2766 use crate::intrinsics;
2767 // iterative stein’s algorithm
2768 // We should still make this `const fn` (and revert to recursive algorithm if we do)
2769 // because relying on llvm to consteval all this is… well, it makes me uncomfortable.
2771 // SAFETY: `a` and `b` are checked to be non-zero values.
2772 let (ctz_a, mut ctz_b) = unsafe {
2779 (intrinsics::cttz_nonzero(a), intrinsics::cttz_nonzero(b))
2781 let k = ctz_a.min(ctz_b);
2782 let mut a = a >> ctz_a;
2785 // remove all factors of 2 from b
2788 mem::swap(&mut a, &mut b);
2791 // SAFETY: `b` is checked to be non-zero.
2796 ctz_b = intrinsics::cttz_nonzero(b);
2801 let gcd: usize = gcd(mem::size_of::<T>(), mem::size_of::<U>());
2802 let ts: usize = mem::size_of::<U>() / gcd;
2803 let us: usize = mem::size_of::<T>() / gcd;
2805 // Armed with this knowledge, we can find how many `U`s we can fit!
2806 let us_len = self.len() / ts * us;
2807 // And how many `T`s will be in the trailing slice!
2808 let ts_len = self.len() % ts;
2812 /// Transmute the slice to a slice of another type, ensuring alignment of the types is
2815 /// This method splits the slice into three distinct slices: prefix, correctly aligned middle
2816 /// slice of a new type, and the suffix slice. The method may make the middle slice the greatest
2817 /// length possible for a given type and input slice, but only your algorithm's performance
2818 /// should depend on that, not its correctness. It is permissible for all of the input data to
2819 /// be returned as the prefix or suffix slice.
2821 /// This method has no purpose when either input element `T` or output element `U` are
2822 /// zero-sized and will return the original slice without splitting anything.
2826 /// This method is essentially a `transmute` with respect to the elements in the returned
2827 /// middle slice, so all the usual caveats pertaining to `transmute::<T, U>` also apply here.
2835 /// let bytes: [u8; 7] = [1, 2, 3, 4, 5, 6, 7];
2836 /// let (prefix, shorts, suffix) = bytes.align_to::<u16>();
2837 /// // less_efficient_algorithm_for_bytes(prefix);
2838 /// // more_efficient_algorithm_for_aligned_shorts(shorts);
2839 /// // less_efficient_algorithm_for_bytes(suffix);
2842 #[stable(feature = "slice_align_to", since = "1.30.0")]
2843 pub unsafe fn align_to<U>(&self) -> (&[T], &[U], &[T]) {
2844 // Note that most of this function will be constant-evaluated,
2845 if mem::size_of::<U>() == 0 || mem::size_of::<T>() == 0 {
2846 // handle ZSTs specially, which is – don't handle them at all.
2847 return (self, &[], &[]);
2850 // First, find at what point do we split between the first and 2nd slice. Easy with
2851 // ptr.align_offset.
2852 let ptr = self.as_ptr();
2853 // SAFETY: See the `align_to_mut` method for the detailed safety comment.
2854 let offset = unsafe { crate::ptr::align_offset(ptr, mem::align_of::<U>()) };
2855 if offset > self.len() {
2858 let (left, rest) = self.split_at(offset);
2859 let (us_len, ts_len) = rest.align_to_offsets::<U>();
2860 // SAFETY: now `rest` is definitely aligned, so `from_raw_parts` below is okay,
2861 // since the caller guarantees that we can transmute `T` to `U` safely.
2865 from_raw_parts(rest.as_ptr() as *const U, us_len),
2866 from_raw_parts(rest.as_ptr().add(rest.len() - ts_len), ts_len),
2872 /// Transmute the slice to a slice of another type, ensuring alignment of the types is
2875 /// This method splits the slice into three distinct slices: prefix, correctly aligned middle
2876 /// slice of a new type, and the suffix slice. The method may make the middle slice the greatest
2877 /// length possible for a given type and input slice, but only your algorithm's performance
2878 /// should depend on that, not its correctness. It is permissible for all of the input data to
2879 /// be returned as the prefix or suffix slice.
2881 /// This method has no purpose when either input element `T` or output element `U` are
2882 /// zero-sized and will return the original slice without splitting anything.
2886 /// This method is essentially a `transmute` with respect to the elements in the returned
2887 /// middle slice, so all the usual caveats pertaining to `transmute::<T, U>` also apply here.
2895 /// let mut bytes: [u8; 7] = [1, 2, 3, 4, 5, 6, 7];
2896 /// let (prefix, shorts, suffix) = bytes.align_to_mut::<u16>();
2897 /// // less_efficient_algorithm_for_bytes(prefix);
2898 /// // more_efficient_algorithm_for_aligned_shorts(shorts);
2899 /// // less_efficient_algorithm_for_bytes(suffix);
2902 #[stable(feature = "slice_align_to", since = "1.30.0")]
2903 pub unsafe fn align_to_mut<U>(&mut self) -> (&mut [T], &mut [U], &mut [T]) {
2904 // Note that most of this function will be constant-evaluated,
2905 if mem::size_of::<U>() == 0 || mem::size_of::<T>() == 0 {
2906 // handle ZSTs specially, which is – don't handle them at all.
2907 return (self, &mut [], &mut []);
2910 // First, find at what point do we split between the first and 2nd slice. Easy with
2911 // ptr.align_offset.
2912 let ptr = self.as_ptr();
2913 // SAFETY: Here we are ensuring we will use aligned pointers for U for the
2914 // rest of the method. This is done by passing a pointer to &[T] with an
2915 // alignment targeted for U.
2916 // `crate::ptr::align_offset` is called with a correctly aligned and
2917 // valid pointer `ptr` (it comes from a reference to `self`) and with
2918 // a size that is a power of two (since it comes from the alignement for U),
2919 // satisfying its safety constraints.
2920 let offset = unsafe { crate::ptr::align_offset(ptr, mem::align_of::<U>()) };
2921 if offset > self.len() {
2922 (self, &mut [], &mut [])
2924 let (left, rest) = self.split_at_mut(offset);
2925 let (us_len, ts_len) = rest.align_to_offsets::<U>();
2926 let rest_len = rest.len();
2927 let mut_ptr = rest.as_mut_ptr();
2928 // We can't use `rest` again after this, that would invalidate its alias `mut_ptr`!
2929 // SAFETY: see comments for `align_to`.
2933 from_raw_parts_mut(mut_ptr as *mut U, us_len),
2934 from_raw_parts_mut(mut_ptr.add(rest_len - ts_len), ts_len),
2940 /// Checks if the elements of this slice are sorted.
2942 /// That is, for each element `a` and its following element `b`, `a <= b` must hold. If the
2943 /// slice yields exactly zero or one element, `true` is returned.
2945 /// Note that if `Self::Item` is only `PartialOrd`, but not `Ord`, the above definition
2946 /// implies that this function returns `false` if any two consecutive items are not
2952 /// #![feature(is_sorted)]
2953 /// let empty: [i32; 0] = [];
2955 /// assert!([1, 2, 2, 9].is_sorted());
2956 /// assert!(![1, 3, 2, 4].is_sorted());
2957 /// assert!([0].is_sorted());
2958 /// assert!(empty.is_sorted());
2959 /// assert!(![0.0, 1.0, f32::NAN].is_sorted());
2962 #[unstable(feature = "is_sorted", reason = "new API", issue = "53485")]
2963 pub fn is_sorted(&self) -> bool
2967 self.is_sorted_by(|a, b| a.partial_cmp(b))
2970 /// Checks if the elements of this slice are sorted using the given comparator function.
2972 /// Instead of using `PartialOrd::partial_cmp`, this function uses the given `compare`
2973 /// function to determine the ordering of two elements. Apart from that, it's equivalent to
2974 /// [`is_sorted`]; see its documentation for more information.
2976 /// [`is_sorted`]: #method.is_sorted
2977 #[unstable(feature = "is_sorted", reason = "new API", issue = "53485")]
2978 pub fn is_sorted_by<F>(&self, mut compare: F) -> bool
2980 F: FnMut(&T, &T) -> Option<Ordering>,
2982 self.iter().is_sorted_by(|a, b| compare(*a, *b))
2985 /// Checks if the elements of this slice are sorted using the given key extraction function.
2987 /// Instead of comparing the slice's elements directly, this function compares the keys of the
2988 /// elements, as determined by `f`. Apart from that, it's equivalent to [`is_sorted`]; see its
2989 /// documentation for more information.
2991 /// [`is_sorted`]: #method.is_sorted
2996 /// #![feature(is_sorted)]
2998 /// assert!(["c", "bb", "aaa"].is_sorted_by_key(|s| s.len()));
2999 /// assert!(![-2i32, -1, 0, 3].is_sorted_by_key(|n| n.abs()));
3002 #[unstable(feature = "is_sorted", reason = "new API", issue = "53485")]
3003 pub fn is_sorted_by_key<F, K>(&self, f: F) -> bool
3008 self.iter().is_sorted_by_key(f)
3011 /// Returns the index of the partition point according to the given predicate
3012 /// (the index of the first element of the second partition).
3014 /// The slice is assumed to be partitioned according to the given predicate.
3015 /// This means that all elements for which the predicate returns true are at the start of the slice
3016 /// and all elements for which the predicate returns false are at the end.
3017 /// For example, [7, 15, 3, 5, 4, 12, 6] is a partitioned under the predicate x % 2 != 0
3018 /// (all odd numbers are at the start, all even at the end).
3020 /// If this slice is not partitioned, the returned result is unspecified and meaningless,
3021 /// as this method performs a kind of binary search.
3026 /// #![feature(partition_point)]
3028 /// let v = [1, 2, 3, 3, 5, 6, 7];
3029 /// let i = v.partition_point(|&x| x < 5);
3031 /// assert_eq!(i, 4);
3032 /// assert!(v[..i].iter().all(|&x| x < 5));
3033 /// assert!(v[i..].iter().all(|&x| !(x < 5)));
3035 #[unstable(feature = "partition_point", reason = "new API", issue = "73831")]
3036 pub fn partition_point<P>(&self, mut pred: P) -> usize
3038 P: FnMut(&T) -> bool,
3041 let mut right = self.len();
3043 while left != right {
3044 let mid = left + (right - left) / 2;
3045 // SAFETY: When `left < right`, `left <= mid < right`.
3046 // Therefore `left` always increases and `right` always decreases,
3047 // and either of them is selected. In both cases `left <= right` is
3048 // satisfied. Therefore if `left < right` in a step, `left <= right`
3049 // is satisfied in the next step. Therefore as long as `left != right`,
3050 // `0 <= left < right <= len` is satisfied and if this case
3051 // `0 <= mid < len` is satisfied too.
3052 let value = unsafe { self.get_unchecked(mid) };
3064 #[stable(feature = "rust1", since = "1.0.0")]
3065 impl<T> Default for &[T] {
3066 /// Creates an empty slice.
3067 fn default() -> Self {
3072 #[stable(feature = "mut_slice_default", since = "1.5.0")]
3073 impl<T> Default for &mut [T] {
3074 /// Creates a mutable empty slice.
3075 fn default() -> Self {