library/core/src/slice/mod.rs
This is Rust standard-library source from the compiler version used in the run.
1 //! Slice management and manipulation.2 //!3 //! For more details see [`std::slice`].4 //!5 //! [`std::slice`]: ../../std/slice/index.html6 7 #![stable(feature = "rust1", since = "1.0.0")]8 9 use crate::clone::TrivialClone;10 use crate::cmp::Ordering::{self, Equal, Greater, Less};11 use crate::intrinsics::{exact_div, unchecked_sub};12 use crate::marker::Destruct;13 use crate::mem::{self, MaybeUninit, SizedTypeProperties};14 use crate::num::NonZero;15 use crate::ops::{OneSidedRange, OneSidedRangeBound, Range, RangeBounds, RangeInclusive};16 use crate::panic::const_panic;17 use crate::simd::{self, Simd};18 use crate::ub_checks::assert_unsafe_precondition;19 use crate::{fmt, hint, ptr, range, slice};20 21 #[unstable(22 feature = "slice_internals",23 issue = "none",24 reason = "exposed from core to be reused in std; use the memchr crate"25 )]26 #[doc(hidden)]27 /// Pure Rust memchr implementation, taken from rust-memchr28 pub mod memchr;29 30 #[unstable(31 feature = "slice_internals",32 issue = "none",33 reason = "exposed from core to be reused in std;"34 )]35 #[doc(hidden)]36 pub mod sort;37 38 mod ascii;39 mod cmp;40 pub(crate) mod index;41 mod iter;42 mod raw;43 mod rotate;44 mod specialize;45 46 #[stable(feature = "inherent_ascii_escape", since = "1.60.0")]47 pub use ascii::EscapeAscii;48 #[unstable(feature = "str_internals", issue = "none")]49 #[doc(hidden)]50 pub use ascii::is_ascii_simple;51 #[stable(feature = "slice_get_slice", since = "1.28.0")]52 pub use index::SliceIndex;53 #[unstable(feature = "slice_range", issue = "76393")]54 pub use index::{range, try_range};55 #[stable(feature = "array_windows", since = "1.94.0")]56 pub use iter::ArrayWindows;57 #[stable(feature = "slice_group_by", since = "1.77.0")]58 pub use iter::{ChunkBy, ChunkByMut};59 #[stable(feature = "rust1", since = "1.0.0")]60 pub use iter::{Chunks, ChunksMut, Windows};61 #[stable(feature = "chunks_exact", since = "1.31.0")]62 pub use iter::{ChunksExact, ChunksExactMut};63 #[stable(feature = "rust1", since = "1.0.0")]64 pub use iter::{Iter, IterMut};65 #[stable(feature = "rchunks", since = "1.31.0")]66 pub use iter::{RChunks, RChunksExact, RChunksExactMut, RChunksMut};67 #[stable(feature = "slice_rsplit", since = "1.27.0")]68 pub use iter::{RSplit, RSplitMut};69 #[stable(feature = "rust1", since = "1.0.0")]70 pub use iter::{RSplitN, RSplitNMut, Split, SplitMut, SplitN, SplitNMut};71 #[stable(feature = "split_inclusive", since = "1.51.0")]72 pub use iter::{SplitInclusive, SplitInclusiveMut};73 #[stable(feature = "from_ref", since = "1.28.0")]74 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};77 #[stable(feature = "rust1", since = "1.0.0")]78 pub use raw::{from_raw_parts, from_raw_parts_mut};79 80 /// Calculates the direction and split point of a one-sided range.81 ///82 /// This is a helper function for `split_off` and `split_off_mut` that returns83 /// the direction of the split (front or back) as well as the index at84 /// which to split. Returns `None` if the split index would overflow.85 #[inline]86 fn split_point_of(range: impl OneSidedRange<usize>) -> Option<(Direction, usize)> {87 use OneSidedRangeBound::{End, EndInclusive, StartInclusive};88 89 Some(match range.bound() {90 (StartInclusive, i) => (Direction::Back, i),91 (End, i) => (Direction::Front, i),92 (EndInclusive, i) => (Direction::Front, i.checked_add(1)?),93 })94 }95 96 enum Direction {97 Front,98 Back,99 }100 101 impl<T> [T] {102 /// Returns the number of elements in the slice.103 ///104 /// # Examples105 ///106 /// ```107 /// let a = [1, 2, 3];108 /// assert_eq!(a.len(), 3);109 /// ```110 #[lang = "slice_len_fn"]111 #[stable(feature = "rust1", since = "1.0.0")]112 #[rustc_const_stable(feature = "const_slice_len", since = "1.39.0")]113 #[rustc_no_implicit_autorefs]114 #[inline]115 #[must_use]116 pub const fn len(&self) -> usize {117 ptr::metadata(self)118 }119 120 /// Returns `true` if the slice has a length of 0.121 ///122 /// # Examples123 ///124 /// ```125 /// let a = [1, 2, 3];126 /// assert!(!a.is_empty());127 ///128 /// let b: &[i32] = &[];129 /// assert!(b.is_empty());130 /// ```131 #[stable(feature = "rust1", since = "1.0.0")]132 #[rustc_const_stable(feature = "const_slice_is_empty", since = "1.39.0")]133 #[rustc_no_implicit_autorefs]134 #[inline]135 #[must_use]136 pub const fn is_empty(&self) -> bool {137 self.len() == 0138 }139 140 /// Returns the first element of the slice, or `None` if it is empty.141 ///142 /// # Examples143 ///144 /// ```145 /// let v = [10, 40, 30];146 /// assert_eq!(Some(&10), v.first());147 ///148 /// let w: &[i32] = &[];149 /// assert_eq!(None, w.first());150 /// ```151 #[stable(feature = "rust1", since = "1.0.0")]152 #[rustc_const_stable(feature = "const_slice_first_last_not_mut", since = "1.56.0")]153 #[inline]154 #[must_use]155 pub const fn first(&self) -> Option<&T> {156 if let [first, ..] = self { Some(first) } else { None }157 }158 159 /// Returns a mutable reference to the first element of the slice, or `None` if it is empty.160 ///161 /// # Examples162 ///163 /// ```164 /// let x = &mut [0, 1, 2];165 ///166 /// if let Some(first) = x.first_mut() {167 /// *first = 5;168 /// }169 /// assert_eq!(x, &[5, 1, 2]);170 ///171 /// let y: &mut [i32] = &mut [];172 /// assert_eq!(None, y.first_mut());173 /// ```174 #[stable(feature = "rust1", since = "1.0.0")]175 #[rustc_const_stable(feature = "const_slice_first_last", since = "1.83.0")]176 #[inline]177 #[must_use]178 pub const fn first_mut(&mut self) -> Option<&mut T> {179 if let [first, ..] = self { Some(first) } else { None }180 }181 182 /// Returns the first and all the rest of the elements of the slice, or `None` if it is empty.183 ///184 /// # Examples185 ///186 /// ```187 /// let x = &[0, 1, 2];188 ///189 /// if let Some((first, elements)) = x.split_first() {190 /// assert_eq!(first, &0);191 /// assert_eq!(elements, &[1, 2]);192 /// }193 /// ```194 #[stable(feature = "slice_splits", since = "1.5.0")]195 #[rustc_const_stable(feature = "const_slice_first_last_not_mut", since = "1.56.0")]196 #[inline]197 #[must_use]198 pub const fn split_first(&self) -> Option<(&T, &[T])> {199 if let [first, tail @ ..] = self { Some((first, tail)) } else { None }200 }201 202 /// Returns the first and all the rest of the elements of the slice, or `None` if it is empty.203 ///204 /// # Examples205 ///206 /// ```207 /// let x = &mut [0, 1, 2];208 ///209 /// if let Some((first, elements)) = x.split_first_mut() {210 /// *first = 3;211 /// elements[0] = 4;212 /// elements[1] = 5;213 /// }214 /// assert_eq!(x, &[3, 4, 5]);215 /// ```216 #[stable(feature = "slice_splits", since = "1.5.0")]217 #[rustc_const_stable(feature = "const_slice_first_last", since = "1.83.0")]218 #[inline]219 #[must_use]220 pub const fn split_first_mut(&mut self) -> Option<(&mut T, &mut [T])> {221 if let [first, tail @ ..] = self { Some((first, tail)) } else { None }222 }223 224 /// Returns the last and all the rest of the elements of the slice, or `None` if it is empty.225 ///226 /// # Examples227 ///228 /// ```229 /// let x = &[0, 1, 2];230 ///231 /// if let Some((last, elements)) = x.split_last() {232 /// assert_eq!(last, &2);233 /// assert_eq!(elements, &[0, 1]);234 /// }235 /// ```236 #[stable(feature = "slice_splits", since = "1.5.0")]237 #[rustc_const_stable(feature = "const_slice_first_last_not_mut", since = "1.56.0")]238 #[inline]239 #[must_use]240 pub const fn split_last(&self) -> Option<(&T, &[T])> {241 if let [init @ .., last] = self { Some((last, init)) } else { None }242 }243 244 /// Returns the last and all the rest of the elements of the slice, or `None` if it is empty.245 ///246 /// # Examples247 ///248 /// ```249 /// let x = &mut [0, 1, 2];250 ///251 /// if let Some((last, elements)) = x.split_last_mut() {252 /// *last = 3;253 /// elements[0] = 4;254 /// elements[1] = 5;255 /// }256 /// assert_eq!(x, &[4, 5, 3]);257 /// ```258 #[stable(feature = "slice_splits", since = "1.5.0")]259 #[rustc_const_stable(feature = "const_slice_first_last", since = "1.83.0")]260 #[inline]261 #[must_use]262 pub const fn split_last_mut(&mut self) -> Option<(&mut T, &mut [T])> {263 if let [init @ .., last] = self { Some((last, init)) } else { None }264 }265 266 /// Returns the last element of the slice, or `None` if it is empty.267 ///268 /// # Examples269 ///270 /// ```271 /// let v = [10, 40, 30];272 /// assert_eq!(Some(&30), v.last());273 ///274 /// let w: &[i32] = &[];275 /// assert_eq!(None, w.last());276 /// ```277 #[stable(feature = "rust1", since = "1.0.0")]278 #[rustc_const_stable(feature = "const_slice_first_last_not_mut", since = "1.56.0")]279 #[inline]280 #[must_use]281 pub const fn last(&self) -> Option<&T> {282 if let [.., last] = self { Some(last) } else { None }283 }284 285 /// Returns a mutable reference to the last item in the slice, or `None` if it is empty.286 ///287 /// # Examples288 ///289 /// ```290 /// let x = &mut [0, 1, 2];291 ///292 /// if let Some(last) = x.last_mut() {293 /// *last = 10;294 /// }295 /// assert_eq!(x, &[0, 1, 10]);296 ///297 /// let y: &mut [i32] = &mut [];298 /// assert_eq!(None, y.last_mut());299 /// ```300 #[stable(feature = "rust1", since = "1.0.0")]301 #[rustc_const_stable(feature = "const_slice_first_last", since = "1.83.0")]302 #[inline]303 #[must_use]304 pub const fn last_mut(&mut self) -> Option<&mut T> {305 if let [.., last] = self { Some(last) } else { None }306 }307 308 /// Returns an array reference to the first `N` items in the slice.309 ///310 /// If the slice is not at least `N` in length, this will return `None`.311 ///312 /// # Examples313 ///314 /// ```315 /// let u = [10, 40, 30];316 /// assert_eq!(Some(&[10, 40]), u.first_chunk::<2>());317 ///318 /// let v: &[i32] = &[10];319 /// assert_eq!(None, v.first_chunk::<2>());320 ///321 /// let w: &[i32] = &[];322 /// assert_eq!(Some(&[]), w.first_chunk::<0>());323 /// ```324 #[inline]325 #[stable(feature = "slice_first_last_chunk", since = "1.77.0")]326 #[rustc_const_stable(feature = "slice_first_last_chunk", since = "1.77.0")]327 pub const fn first_chunk<const N: usize>(&self) -> Option<&[T; N]> {328 if self.len() < N {329 None330 } else {331 // SAFETY: We explicitly check for the correct number of elements,332 // and do not let the reference outlive the slice.333 Some(unsafe { &*(self.as_ptr().cast_array()) })334 }335 }336 337 /// Returns a mutable array reference to the first `N` items in the slice.338 ///339 /// If the slice is not at least `N` in length, this will return `None`.340 ///341 /// # Examples342 ///343 /// ```344 /// let x = &mut [0, 1, 2];345 ///346 /// if let Some(first) = x.first_chunk_mut::<2>() {347 /// first[0] = 5;348 /// first[1] = 4;349 /// }350 /// assert_eq!(x, &[5, 4, 2]);351 ///352 /// assert_eq!(None, x.first_chunk_mut::<4>());353 /// ```354 #[inline]355 #[stable(feature = "slice_first_last_chunk", since = "1.77.0")]356 #[rustc_const_stable(feature = "const_slice_first_last_chunk", since = "1.83.0")]357 pub const fn first_chunk_mut<const N: usize>(&mut self) -> Option<&mut [T; N]> {358 if self.len() < N {359 None360 } else {361 // SAFETY: We explicitly check for the correct number of elements,362 // do not let the reference outlive the slice,363 // and require exclusive access to the entire slice to mutate the chunk.364 Some(unsafe { &mut *(self.as_mut_ptr().cast_array()) })365 }366 }367 368 /// Returns an array reference to the first `N` items in the slice and the remaining slice.369 ///370 /// If the slice is not at least `N` in length, this will return `None`.371 ///372 /// # Examples373 ///374 /// ```375 /// let x = &[0, 1, 2];376 ///377 /// if let Some((first, elements)) = x.split_first_chunk::<2>() {378 /// assert_eq!(first, &[0, 1]);379 /// assert_eq!(elements, &[2]);380 /// }381 ///382 /// assert_eq!(None, x.split_first_chunk::<4>());383 /// ```384 #[inline]385 #[stable(feature = "slice_first_last_chunk", since = "1.77.0")]386 #[rustc_const_stable(feature = "slice_first_last_chunk", since = "1.77.0")]387 pub const fn split_first_chunk<const N: usize>(&self) -> Option<(&[T; N], &[T])> {388 let Some((first, tail)) = self.split_at_checked(N) else { return None };389 390 // SAFETY: We explicitly check for the correct number of elements,391 // and do not let the references outlive the slice.392 Some((unsafe { &*(first.as_ptr().cast_array()) }, tail))393 }394 395 /// Returns a mutable array reference to the first `N` items in the slice and the remaining396 /// slice.397 ///398 /// If the slice is not at least `N` in length, this will return `None`.399 ///400 /// # Examples401 ///402 /// ```403 /// let x = &mut [0, 1, 2];404 ///405 /// if let Some((first, elements)) = x.split_first_chunk_mut::<2>() {406 /// first[0] = 3;407 /// first[1] = 4;408 /// elements[0] = 5;409 /// }410 /// assert_eq!(x, &[3, 4, 5]);411 ///412 /// assert_eq!(None, x.split_first_chunk_mut::<4>());413 /// ```414 #[inline]415 #[stable(feature = "slice_first_last_chunk", since = "1.77.0")]416 #[rustc_const_stable(feature = "const_slice_first_last_chunk", since = "1.83.0")]417 pub const fn split_first_chunk_mut<const N: usize>(418 &mut self,419 ) -> Option<(&mut [T; N], &mut [T])> {420 let Some((first, tail)) = self.split_at_mut_checked(N) else { return None };421 422 // SAFETY: We explicitly check for the correct number of elements,423 // do not let the reference outlive the slice,424 // and enforce exclusive mutability of the chunk by the split.425 Some((unsafe { &mut *(first.as_mut_ptr().cast_array()) }, tail))426 }427 428 /// Returns an array reference to the last `N` items in the slice and the remaining slice.429 ///430 /// If the slice is not at least `N` in length, this will return `None`.431 ///432 /// # Examples433 ///434 /// ```435 /// let x = &[0, 1, 2];436 ///437 /// if let Some((elements, last)) = x.split_last_chunk::<2>() {438 /// assert_eq!(elements, &[0]);439 /// assert_eq!(last, &[1, 2]);440 /// }441 ///442 /// assert_eq!(None, x.split_last_chunk::<4>());443 /// ```444 #[inline]445 #[stable(feature = "slice_first_last_chunk", since = "1.77.0")]446 #[rustc_const_stable(feature = "slice_first_last_chunk", since = "1.77.0")]447 pub const fn split_last_chunk<const N: usize>(&self) -> Option<(&[T], &[T; N])> {448 let Some(index) = self.len().checked_sub(N) else { return None };449 let (init, last) = self.split_at(index);450 451 // SAFETY: We explicitly check for the correct number of elements,452 // and do not let the references outlive the slice.453 Some((init, unsafe { &*(last.as_ptr().cast_array()) }))454 }455 456 /// Returns a mutable array reference to the last `N` items in the slice and the remaining457 /// slice.458 ///459 /// If the slice is not at least `N` in length, this will return `None`.460 ///461 /// # Examples462 ///463 /// ```464 /// let x = &mut [0, 1, 2];465 ///466 /// if let Some((elements, last)) = x.split_last_chunk_mut::<2>() {467 /// last[0] = 3;468 /// last[1] = 4;469 /// elements[0] = 5;470 /// }471 /// assert_eq!(x, &[5, 3, 4]);472 ///473 /// assert_eq!(None, x.split_last_chunk_mut::<4>());474 /// ```475 #[inline]476 #[stable(feature = "slice_first_last_chunk", since = "1.77.0")]477 #[rustc_const_stable(feature = "const_slice_first_last_chunk", since = "1.83.0")]478 pub const fn split_last_chunk_mut<const N: usize>(479 &mut self,480 ) -> Option<(&mut [T], &mut [T; N])> {481 let Some(index) = self.len().checked_sub(N) else { return None };482 let (init, last) = self.split_at_mut(index);483 484 // SAFETY: We explicitly check for the correct number of elements,485 // do not let the reference outlive the slice,486 // and enforce exclusive mutability of the chunk by the split.487 Some((init, unsafe { &mut *(last.as_mut_ptr().cast_array()) }))488 }489 490 /// Returns an array reference to the last `N` items in the slice.491 ///492 /// If the slice is not at least `N` in length, this will return `None`.493 ///494 /// # Examples495 ///496 /// ```497 /// let u = [10, 40, 30];498 /// assert_eq!(Some(&[40, 30]), u.last_chunk::<2>());499 ///500 /// let v: &[i32] = &[10];501 /// assert_eq!(None, v.last_chunk::<2>());502 ///503 /// let w: &[i32] = &[];504 /// assert_eq!(Some(&[]), w.last_chunk::<0>());505 /// ```506 #[inline]507 #[stable(feature = "slice_first_last_chunk", since = "1.77.0")]508 #[rustc_const_stable(feature = "const_slice_last_chunk", since = "1.80.0")]509 pub const fn last_chunk<const N: usize>(&self) -> Option<&[T; N]> {510 // FIXME(const-hack): Without const traits, we need this instead of `get`.511 let Some(index) = self.len().checked_sub(N) else { return None };512 let (_, last) = self.split_at(index);513 514 // SAFETY: We explicitly check for the correct number of elements,515 // and do not let the references outlive the slice.516 Some(unsafe { &*(last.as_ptr().cast_array()) })517 }518 519 /// Returns a mutable array reference to the last `N` items in the slice.520 ///521 /// If the slice is not at least `N` in length, this will return `None`.522 ///523 /// # Examples524 ///525 /// ```526 /// let x = &mut [0, 1, 2];527 ///528 /// if let Some(last) = x.last_chunk_mut::<2>() {529 /// last[0] = 10;530 /// last[1] = 20;531 /// }532 /// assert_eq!(x, &[0, 10, 20]);533 ///534 /// assert_eq!(None, x.last_chunk_mut::<4>());535 /// ```536 #[inline]537 #[stable(feature = "slice_first_last_chunk", since = "1.77.0")]538 #[rustc_const_stable(feature = "const_slice_first_last_chunk", since = "1.83.0")]539 pub const fn last_chunk_mut<const N: usize>(&mut self) -> Option<&mut [T; N]> {540 // FIXME(const-hack): Without const traits, we need this instead of `get`.541 let Some(index) = self.len().checked_sub(N) else { return None };542 let (_, last) = self.split_at_mut(index);543 544 // SAFETY: We explicitly check for the correct number of elements,545 // do not let the reference outlive the slice,546 // and require exclusive access to the entire slice to mutate the chunk.547 Some(unsafe { &mut *(last.as_mut_ptr().cast_array()) })548 }549 550 /// Returns a reference to an element or subslice depending on the type of551 /// index.552 ///553 /// - If given a position, returns a reference to the element at that554 /// position or `None` if out of bounds.555 /// - If given a range, returns the subslice corresponding to that range,556 /// or `None` if out of bounds.557 ///558 /// # Examples559 ///560 /// ```561 /// let v = [10, 40, 30];562 /// assert_eq!(Some(&40), v.get(1));563 /// assert_eq!(Some(&[10, 40][..]), v.get(0..2));564 /// assert_eq!(None, v.get(3));565 /// assert_eq!(None, v.get(0..4));566 /// ```567 #[stable(feature = "rust1", since = "1.0.0")]568 #[rustc_no_implicit_autorefs]569 #[inline]570 #[must_use]571 #[rustc_const_unstable(feature = "const_index", issue = "143775")]572 pub const fn get<I>(&self, index: I) -> Option<&I::Output>573 where574 I: [const] SliceIndex<Self>,575 {576 index.get(self)577 }578 579 /// Returns a mutable reference to an element or subslice depending on the580 /// type of index (see [`get`]) or `None` if the index is out of bounds.581 ///582 /// [`get`]: slice::get583 ///584 /// # Examples585 ///586 /// ```587 /// let x = &mut [0, 1, 2];588 ///589 /// if let Some(elem) = x.get_mut(1) {590 /// *elem = 42;591 /// }592 /// assert_eq!(x, &[0, 42, 2]);593 /// ```594 #[stable(feature = "rust1", since = "1.0.0")]595 #[rustc_no_implicit_autorefs]596 #[inline]597 #[must_use]598 #[rustc_const_unstable(feature = "const_index", issue = "143775")]599 pub const fn get_mut<I>(&mut self, index: I) -> Option<&mut I::Output>600 where601 I: [const] SliceIndex<Self>,602 {603 index.get_mut(self)604 }605 606 /// Returns a reference to an element or subslice, without doing bounds607 /// checking.608 ///609 /// For a safe alternative see [`get`].610 ///611 /// # Safety612 ///613 /// Calling this method with an out-of-bounds index is *[undefined behavior]*614 /// even if the resulting reference is not used.615 ///616 /// You can think of this like `.get(index).unwrap_unchecked()`. It's UB617 /// to call `.get_unchecked(len)`, even if you immediately convert to a618 /// pointer. And it's UB to call `.get_unchecked(..len + 1)`,619 /// `.get_unchecked(..=len)`, or similar.620 ///621 /// [`get`]: slice::get622 /// [undefined behavior]: https://doc.rust-lang.org/reference/behavior-considered-undefined.html623 ///624 /// # Examples625 ///626 /// ```627 /// let x = &[1, 2, 4];628 ///629 /// unsafe {630 /// assert_eq!(x.get_unchecked(1), &2);631 /// }632 /// ```633 #[stable(feature = "rust1", since = "1.0.0")]634 #[rustc_no_implicit_autorefs]635 #[inline]636 #[must_use]637 #[track_caller]638 #[rustc_const_unstable(feature = "const_index", issue = "143775")]639 pub const unsafe fn get_unchecked<I>(&self, index: I) -> &I::Output640 where641 I: [const] SliceIndex<Self>,642 {643 // SAFETY: the caller must uphold most of the safety requirements for `get_unchecked`;644 // the slice is dereferenceable because `self` is a safe reference.645 // The returned pointer is safe because impls of `SliceIndex` have to guarantee that it is.646 unsafe { &*index.get_unchecked(self) }647 }648 649 /// Returns a mutable reference to an element or subslice, without doing650 /// bounds checking.651 ///652 /// For a safe alternative see [`get_mut`].653 ///654 /// # Safety655 ///656 /// Calling this method with an out-of-bounds index is *[undefined behavior]*657 /// even if the resulting reference is not used.658 ///659 /// You can think of this like `.get_mut(index).unwrap_unchecked()`. It's660 /// UB to call `.get_unchecked_mut(len)`, even if you immediately convert661 /// to a pointer. And it's UB to call `.get_unchecked_mut(..len + 1)`,662 /// `.get_unchecked_mut(..=len)`, or similar.663 ///664 /// [`get_mut`]: slice::get_mut665 /// [undefined behavior]: https://doc.rust-lang.org/reference/behavior-considered-undefined.html666 ///667 /// # Examples668 ///669 /// ```670 /// let x = &mut [1, 2, 4];671 ///672 /// unsafe {673 /// let elem = x.get_unchecked_mut(1);674 /// *elem = 13;675 /// }676 /// assert_eq!(x, &[1, 13, 4]);677 /// ```678 #[stable(feature = "rust1", since = "1.0.0")]679 #[rustc_no_implicit_autorefs]680 #[inline]681 #[must_use]682 #[track_caller]683 #[rustc_const_unstable(feature = "const_index", issue = "143775")]684 pub const unsafe fn get_unchecked_mut<I>(&mut self, index: I) -> &mut I::Output685 where686 I: [const] SliceIndex<Self>,687 {688 // SAFETY: the caller must uphold the safety requirements for `get_unchecked_mut`;689 // the slice is dereferenceable because `self` is a safe reference.690 // The returned pointer is safe because impls of `SliceIndex` have to guarantee that it is.691 unsafe { &mut *index.get_unchecked_mut(self) }692 }693 694 /// Returns a raw pointer to the slice's buffer.695 ///696 /// The caller must ensure that the slice outlives the pointer this697 /// function returns, or else it will end up dangling.698 ///699 /// The caller must also ensure that the memory the pointer (non-transitively) points to700 /// is never written to (except inside an `UnsafeCell`) using this pointer or any pointer701 /// derived from it. If you need to mutate the contents of the slice, use [`as_mut_ptr`].702 ///703 /// Modifying the container referenced by this slice may cause its buffer704 /// to be reallocated, which would also make any pointers to it invalid.705 ///706 /// # Examples707 ///708 /// ```709 /// let x = &[1, 2, 4];710 /// let x_ptr = x.as_ptr();711 ///712 /// unsafe {713 /// for i in 0..x.len() {714 /// assert_eq!(x.get_unchecked(i), &*x_ptr.add(i));715 /// }716 /// }717 /// ```718 ///719 /// [`as_mut_ptr`]: slice::as_mut_ptr720 #[stable(feature = "rust1", since = "1.0.0")]721 #[rustc_const_stable(feature = "const_slice_as_ptr", since = "1.32.0")]722 #[rustc_never_returns_null_ptr]723 #[rustc_as_ptr]724 #[inline(always)]725 #[must_use]726 pub const fn as_ptr(&self) -> *const T {727 self as *const [T] as *const T728 }729 730 /// Returns an unsafe mutable pointer to the slice's buffer.731 ///732 /// The caller must ensure that the slice outlives the pointer this733 /// function returns, or else it will end up dangling.734 ///735 /// Modifying the container referenced by this slice may cause its buffer736 /// to be reallocated, which would also make any pointers to it invalid.737 ///738 /// # Examples739 ///740 /// ```741 /// let x = &mut [1, 2, 4];742 /// let x_ptr = x.as_mut_ptr();743 ///744 /// unsafe {745 /// for i in 0..x.len() {746 /// *x_ptr.add(i) += 2;747 /// }748 /// }749 /// assert_eq!(x, &[3, 4, 6]);750 /// ```751 #[stable(feature = "rust1", since = "1.0.0")]752 #[rustc_const_stable(feature = "const_ptr_offset", since = "1.61.0")]753 #[rustc_never_returns_null_ptr]754 #[rustc_as_ptr]755 #[inline(always)]756 #[must_use]757 #[rustc_no_writable]758 pub const fn as_mut_ptr(&mut self) -> *mut T {759 self as *mut [T] as *mut T760 }761 762 /// Returns the two raw pointers spanning the slice.763 ///764 /// The returned range is half-open, which means that the end pointer765 /// points *one past* the last element of the slice. This way, an empty766 /// slice is represented by two equal pointers, and the difference between767 /// the two pointers represents the size of the slice.768 ///769 /// See [`as_ptr`] for warnings on using these pointers. The end pointer770 /// requires extra caution, as it does not point to a valid element in the771 /// slice.772 ///773 /// This function is useful for interacting with foreign interfaces which774 /// use two pointers to refer to a range of elements in memory, as is775 /// common in C++.776 ///777 /// It can also be useful to check if a pointer to an element refers to an778 /// element of this slice:779 ///780 /// ```781 /// let a = [1, 2, 3];782 /// let x = &a[1] as *const _;783 /// let y = &5 as *const _;784 ///785 /// assert!(a.as_ptr_range().contains(&x));786 /// assert!(!a.as_ptr_range().contains(&y));787 /// ```788 ///789 /// [`as_ptr`]: slice::as_ptr790 #[stable(feature = "slice_ptr_range", since = "1.48.0")]791 #[rustc_const_stable(feature = "const_ptr_offset", since = "1.61.0")]792 #[inline]793 #[must_use]794 pub const fn as_ptr_range(&self) -> Range<*const T> {795 let start = self.as_ptr();796 // SAFETY: The `add` here is safe, because:797 //798 // - Both pointers are part of the same object, as pointing directly799 // past the object also counts.800 //801 // - The size of the slice is never larger than `isize::MAX` bytes, as802 // noted here:803 // - https://github.com/rust-lang/unsafe-code-guidelines/issues/102#issuecomment-473340447804 // - https://doc.rust-lang.org/reference/behavior-considered-undefined.html805 // - https://doc.rust-lang.org/core/slice/fn.from_raw_parts.html#safety806 // (This doesn't seem normative yet, but the very same assumption is807 // made in many places, including the Index implementation of slices.)808 //809 // - There is no wrapping around involved, as slices do not wrap past810 // the end of the address space.811 //812 // See the documentation of [`pointer::add`].813 let end = unsafe { start.add(self.len()) };814 start..end815 }816 817 /// Returns the two unsafe mutable pointers spanning the slice.818 ///819 /// The returned range is half-open, which means that the end pointer820 /// points *one past* the last element of the slice. This way, an empty821 /// slice is represented by two equal pointers, and the difference between822 /// the two pointers represents the size of the slice.823 ///824 /// See [`as_mut_ptr`] for warnings on using these pointers. The end825 /// pointer requires extra caution, as it does not point to a valid element826 /// in the slice.827 ///828 /// This function is useful for interacting with foreign interfaces which829 /// use two pointers to refer to a range of elements in memory, as is830 /// common in C++.831 ///832 /// [`as_mut_ptr`]: slice::as_mut_ptr833 #[stable(feature = "slice_ptr_range", since = "1.48.0")]834 #[rustc_const_stable(feature = "const_ptr_offset", since = "1.61.0")]835 #[inline]836 #[must_use]837 pub const fn as_mut_ptr_range(&mut self) -> Range<*mut T> {838 let start = self.as_mut_ptr();839 // SAFETY: See as_ptr_range() above for why `add` here is safe.840 let end = unsafe { start.add(self.len()) };841 start..end842 }843 844 /// Gets a reference to the underlying array.845 ///846 /// If `N` is not exactly equal to the length of `self`, then this method returns `None`.847 #[stable(feature = "core_slice_as_array", since = "1.93.0")]848 #[rustc_const_stable(feature = "core_slice_as_array", since = "1.93.0")]849 #[inline]850 #[must_use]851 pub const fn as_array<const N: usize>(&self) -> Option<&[T; N]> {852 if self.len() == N {853 let ptr = self.as_ptr().cast_array();854 855 // SAFETY: The underlying array of a slice can be reinterpreted as an actual array `[T; N]` if `N` is not greater than the slice's length.856 let me = unsafe { &*ptr };857 Some(me)858 } else {859 None860 }861 }862 863 /// Gets a mutable reference to the slice's underlying array.864 ///865 /// If `N` is not exactly equal to the length of `self`, then this method returns `None`.866 #[stable(feature = "core_slice_as_array", since = "1.93.0")]867 #[rustc_const_stable(feature = "core_slice_as_array", since = "1.93.0")]868 #[inline]869 #[must_use]870 pub const fn as_mut_array<const N: usize>(&mut self) -> Option<&mut [T; N]> {871 if self.len() == N {872 let ptr = self.as_mut_ptr().cast_array();873 874 // SAFETY: The underlying array of a slice can be reinterpreted as an actual array `[T; N]` if `N` is not greater than the slice's length.875 let me = unsafe { &mut *ptr };876 Some(me)877 } else {878 None879 }880 }881 882 /// Swaps two elements in the slice.883 ///884 /// If `a` equals to `b`, it's guaranteed that elements won't change value.885 ///886 /// # Arguments887 ///888 /// * a - The index of the first element889 /// * b - The index of the second element890 ///891 /// # Panics892 ///893 /// Panics if `a` or `b` are out of bounds.894 ///895 /// # Examples896 ///897 /// ```898 /// let mut v = ["a", "b", "c", "d", "e"];899 /// v.swap(2, 4);900 /// assert!(v == ["a", "b", "e", "d", "c"]);901 /// ```902 #[stable(feature = "rust1", since = "1.0.0")]903 #[rustc_const_stable(feature = "const_swap", since = "1.85.0")]904 #[inline]905 #[track_caller]906 pub const fn swap(&mut self, a: usize, b: usize) {907 // FIXME: use swap_unchecked here (https://github.com/rust-lang/rust/pull/88540#issuecomment-944344343)908 // Can't take two mutable loans from one vector, so instead use raw pointers.909 let pa = &raw mut self[a];910 let pb = &raw mut self[b];911 // SAFETY: `pa` and `pb` have been created from safe mutable references and refer912 // to elements in the slice and therefore are guaranteed to be valid and aligned.913 // Note that accessing the elements behind `a` and `b` is checked and will914 // panic when out of bounds.915 unsafe {916 ptr::swap(pa, pb);917 }918 }919 920 /// Swaps two elements in the slice, without doing bounds checking.921 ///922 /// For a safe alternative see [`swap`].923 ///924 /// # Arguments925 ///926 /// * a - The index of the first element927 /// * b - The index of the second element928 ///929 /// # Safety930 ///931 /// Calling this method with an out-of-bounds index is *[undefined behavior]*.932 /// The caller has to ensure that `a < self.len()` and `b < self.len()`.933 ///934 /// # Examples935 ///936 /// ```937 /// #![feature(slice_swap_unchecked)]938 ///939 /// let mut v = ["a", "b", "c", "d"];940 /// // SAFETY: we know that 1 and 3 are both indices of the slice941 /// unsafe { v.swap_unchecked(1, 3) };942 /// assert!(v == ["a", "d", "c", "b"]);943 /// ```944 ///945 /// [`swap`]: slice::swap946 /// [undefined behavior]: https://doc.rust-lang.org/reference/behavior-considered-undefined.html947 #[unstable(feature = "slice_swap_unchecked", issue = "88539")]948 #[track_caller]949 pub const unsafe fn swap_unchecked(&mut self, a: usize, b: usize) {950 assert_unsafe_precondition!(951 check_library_ub,952 "slice::swap_unchecked requires that the indices are within the slice",953 (954 len: usize = self.len(),955 a: usize = a,956 b: usize = b,957 ) => a < len && b < len,958 );959 960 let ptr = self.as_mut_ptr();961 // SAFETY: caller has to guarantee that `a < self.len()` and `b < self.len()`962 unsafe {963 ptr::swap(ptr.add(a), ptr.add(b));964 }965 }966 967 /// Reverses the order of elements in the slice, in place.968 ///969 /// # Examples970 ///971 /// ```972 /// let mut v = [1, 2, 3];973 /// v.reverse();974 /// assert!(v == [3, 2, 1]);975 /// ```976 #[stable(feature = "rust1", since = "1.0.0")]977 #[rustc_const_stable(feature = "const_slice_reverse", since = "1.90.0")]978 #[inline]979 pub const fn reverse(&mut self) {980 let half_len = self.len() / 2;981 let Range { start, end } = self.as_mut_ptr_range();982 983 // These slices will skip the middle item for an odd length,984 // since that one doesn't need to move.985 let (front_half, back_half) =986 // SAFETY: Both are subparts of the original slice, so the memory987 // range is valid, and they don't overlap because they're each only988 // half (or less) of the original slice.989 unsafe {990 (991 slice::from_raw_parts_mut(start, half_len),992 slice::from_raw_parts_mut(end.sub(half_len), half_len),993 )994 };995 996 // Introducing a function boundary here means that the two halves997 // get `noalias` markers, allowing better optimization as LLVM998 // knows that they're disjoint, unlike in the original slice.999 revswap(front_half, back_half, half_len);1000 1001 #[inline]1002 const fn revswap<T>(a: &mut [T], b: &mut [T], n: usize) {1003 debug_assert!(a.len() == n);1004 debug_assert!(b.len() == n);1005 1006 // Because this function is first compiled in isolation,1007 // this check tells LLVM that the indexing below is1008 // in-bounds. Then after inlining -- once the actual1009 // lengths of the slices are known -- it's removed.1010 // FIXME(const_trait_impl) replace with let (a, b) = (&mut a[..n], &mut b[..n]);1011 let (a, _) = a.split_at_mut(n);1012 let (b, _) = b.split_at_mut(n);1013 1014 let mut i = 0;1015 while i < n {1016 mem::swap(&mut a[i], &mut b[n - 1 - i]);1017 i += 1;1018 }1019 }1020 }1021 1022 /// Returns an iterator over the slice.1023 ///1024 /// The iterator yields all items from start to end.1025 ///1026 /// # Examples1027 ///1028 /// ```1029 /// let x = &[1, 2, 4];1030 /// let mut iterator = x.iter();1031 ///1032 /// assert_eq!(iterator.next(), Some(&1));1033 /// assert_eq!(iterator.next(), Some(&2));1034 /// assert_eq!(iterator.next(), Some(&4));1035 /// assert_eq!(iterator.next(), None);1036 /// ```1037 #[stable(feature = "rust1", since = "1.0.0")]1038 #[rustc_const_unstable(feature = "const_slice_make_iter", issue = "137737")]1039 #[inline]1040 #[rustc_diagnostic_item = "slice_iter"]1041 pub const fn iter(&self) -> Iter<'_, T> {1042 Iter::new(self)1043 }1044 1045 /// Returns an iterator that allows modifying each value.1046 ///1047 /// The iterator yields all items from start to end.1048 ///1049 /// # Examples1050 ///1051 /// ```1052 /// let x = &mut [1, 2, 4];1053 /// for elem in x.iter_mut() {1054 /// *elem += 2;1055 /// }1056 /// assert_eq!(x, &[3, 4, 6]);1057 /// ```1058 #[rustc_const_unstable(feature = "const_slice_make_iter", issue = "137737")]1059 #[stable(feature = "rust1", since = "1.0.0")]1060 #[inline]1061 pub const fn iter_mut(&mut self) -> IterMut<'_, T> {1062 IterMut::new(self)1063 }1064 1065 /// Returns an iterator over all contiguous windows of length1066 /// `size`. The windows overlap. If the slice is shorter than1067 /// `size`, the iterator returns no values.1068 ///1069 /// # Panics1070 ///1071 /// Panics if `size` is zero.1072 ///1073 /// # Examples1074 ///1075 /// ```1076 /// let slice = ['l', 'o', 'r', 'e', 'm'];1077 /// let mut iter = slice.windows(3);1078 /// assert_eq!(iter.next().unwrap(), &['l', 'o', 'r']);1079 /// assert_eq!(iter.next().unwrap(), &['o', 'r', 'e']);1080 /// assert_eq!(iter.next().unwrap(), &['r', 'e', 'm']);1081 /// assert!(iter.next().is_none());1082 /// ```1083 ///1084 /// If the slice is shorter than `size`:1085 ///1086 /// ```1087 /// let slice = ['f', 'o', 'o'];1088 /// let mut iter = slice.windows(4);1089 /// assert!(iter.next().is_none());1090 /// ```1091 ///1092 /// Because the [Iterator] trait cannot represent the required lifetimes,1093 /// there is no `windows_mut` analog to `windows`;1094 /// `[0,1,2].windows_mut(2).collect()` would violate [the rules of references]1095 /// (though a [LendingIterator] analog is possible). You can sometimes use1096 /// [`Cell::as_slice_of_cells`](crate::cell::Cell::as_slice_of_cells) in1097 /// conjunction with `windows` instead:1098 ///1099 /// [the rules of references]: https://doc.rust-lang.org/book/ch04-02-references-and-borrowing.html#the-rules-of-references1100 /// [LendingIterator]: https://blog.rust-lang.org/2022/10/28/gats-stabilization.html1101 /// ```1102 /// use std::cell::Cell;1103 ///1104 /// let mut array = ['R', 'u', 's', 't', ' ', '2', '0', '1', '5'];1105 /// let slice = &mut array[..];1106 /// let slice_of_cells: &[Cell<char>] = Cell::from_mut(slice).as_slice_of_cells();1107 /// for w in slice_of_cells.windows(3) {1108 /// Cell::swap(&w[0], &w[2]);1109 /// }1110 /// assert_eq!(array, ['s', 't', ' ', '2', '0', '1', '5', 'u', 'R']);1111 /// ```1112 #[stable(feature = "rust1", since = "1.0.0")]1113 #[rustc_const_unstable(feature = "const_slice_make_iter", issue = "137737")]1114 #[inline]1115 #[track_caller]1116 pub const fn windows(&self, size: usize) -> Windows<'_, T> {1117 let size = NonZero::new(size).expect("window size must be non-zero");1118 Windows::new(self, size)1119 }1120 1121 /// Returns an iterator over `chunk_size` elements of the slice at a time, starting at the1122 /// beginning of the slice.1123 ///1124 /// The chunks are slices and do not overlap. If `chunk_size` does not divide the length of the1125 /// slice, then the last chunk will not have length `chunk_size`.1126 ///1127 /// See [`chunks_exact`] for a variant of this iterator that returns chunks of always exactly1128 /// `chunk_size` elements, and [`rchunks`] for the same iterator but starting at the end of the1129 /// slice.1130 ///1131 /// If your `chunk_size` is a constant, consider using [`as_chunks`] instead, which will1132 /// give references to arrays of exactly that length, rather than slices.1133 ///1134 /// # Panics1135 ///1136 /// Panics if `chunk_size` is zero.1137 ///1138 /// # Examples1139 ///1140 /// ```1141 /// let slice = ['l', 'o', 'r', 'e', 'm'];1142 /// let mut iter = slice.chunks(2);1143 /// assert_eq!(iter.next().unwrap(), &['l', 'o']);1144 /// assert_eq!(iter.next().unwrap(), &['r', 'e']);1145 /// assert_eq!(iter.next().unwrap(), &['m']);1146 /// assert!(iter.next().is_none());1147 /// ```1148 ///1149 /// [`chunks_exact`]: slice::chunks_exact1150 /// [`rchunks`]: slice::rchunks1151 /// [`as_chunks`]: slice::as_chunks1152 #[stable(feature = "rust1", since = "1.0.0")]1153 #[rustc_const_unstable(feature = "const_slice_make_iter", issue = "137737")]1154 #[inline]1155 #[track_caller]1156 pub const fn chunks(&self, chunk_size: usize) -> Chunks<'_, T> {1157 assert!(chunk_size != 0, "chunk size must be non-zero");1158 Chunks::new(self, chunk_size)1159 }1160 1161 /// Returns an iterator over `chunk_size` elements of the slice at a time, starting at the1162 /// beginning of the slice.1163 ///1164 /// The chunks are mutable slices, and do not overlap. If `chunk_size` does not divide the1165 /// length of the slice, then the last chunk will not have length `chunk_size`.1166 ///1167 /// See [`chunks_exact_mut`] for a variant of this iterator that returns chunks of always1168 /// exactly `chunk_size` elements, and [`rchunks_mut`] for the same iterator but starting at1169 /// the end of the slice.1170 ///1171 /// If your `chunk_size` is a constant, consider using [`as_chunks_mut`] instead, which will1172 /// give references to arrays of exactly that length, rather than slices.1173 ///1174 /// # Panics1175 ///1176 /// Panics if `chunk_size` is zero.1177 ///1178 /// # Examples1179 ///1180 /// ```1181 /// let v = &mut [0, 0, 0, 0, 0];1182 /// let mut count = 1;1183 ///1184 /// for chunk in v.chunks_mut(2) {1185 /// for elem in chunk.iter_mut() {1186 /// *elem += count;1187 /// }1188 /// count += 1;1189 /// }1190 /// assert_eq!(v, &[1, 1, 2, 2, 3]);1191 /// ```1192 ///1193 /// [`chunks_exact_mut`]: slice::chunks_exact_mut1194 /// [`rchunks_mut`]: slice::rchunks_mut1195 /// [`as_chunks_mut`]: slice::as_chunks_mut1196 #[stable(feature = "rust1", since = "1.0.0")]1197 #[rustc_const_unstable(feature = "const_slice_make_iter", issue = "137737")]1198 #[inline]1199 #[track_caller]1200 pub const fn chunks_mut(&mut self, chunk_size: usize) -> ChunksMut<'_, T> {1201 assert!(chunk_size != 0, "chunk size must be non-zero");1202 ChunksMut::new(self, chunk_size)1203 }1204 1205 /// Returns an iterator over `chunk_size` elements of the slice at a time, starting at the1206 /// beginning of the slice.1207 ///1208 /// The chunks are slices and do not overlap. If `chunk_size` does not divide the length of the1209 /// slice, then the last up to `chunk_size-1` elements will be omitted and can be retrieved1210 /// from the `remainder` function of the iterator.1211 ///1212 /// Due to each chunk having exactly `chunk_size` elements, the compiler can often optimize the1213 /// resulting code better than in the case of [`chunks`].1214 ///1215 /// See [`chunks`] for a variant of this iterator that also returns the remainder as a smaller1216 /// chunk, and [`rchunks_exact`] for the same iterator but starting at the end of the slice.1217 ///1218 /// If your `chunk_size` is a constant, consider using [`as_chunks`] instead, which will1219 /// give references to arrays of exactly that length, rather than slices.1220 ///1221 /// # Panics1222 ///1223 /// Panics if `chunk_size` is zero.1224 ///1225 /// # Examples1226 ///1227 /// ```1228 /// let slice = ['l', 'o', 'r', 'e', 'm'];1229 /// let mut iter = slice.chunks_exact(2);1230 /// assert_eq!(iter.next().unwrap(), &['l', 'o']);1231 /// assert_eq!(iter.next().unwrap(), &['r', 'e']);1232 /// assert!(iter.next().is_none());1233 /// assert_eq!(iter.remainder(), &['m']);1234 /// ```1235 ///1236 /// [`chunks`]: slice::chunks1237 /// [`rchunks_exact`]: slice::rchunks_exact1238 /// [`as_chunks`]: slice::as_chunks1239 #[stable(feature = "chunks_exact", since = "1.31.0")]1240 #[rustc_const_unstable(feature = "const_slice_make_iter", issue = "137737")]1241 #[inline]1242 #[track_caller]1243 pub const fn chunks_exact(&self, chunk_size: usize) -> ChunksExact<'_, T> {1244 assert!(chunk_size != 0, "chunk size must be non-zero");1245 ChunksExact::new(self, chunk_size)1246 }1247 1248 /// Returns an iterator over `chunk_size` elements of the slice at a time, starting at the1249 /// beginning of the slice.1250 ///1251 /// The chunks are mutable slices, and do not overlap. If `chunk_size` does not divide the1252 /// length of the slice, then the last up to `chunk_size-1` elements will be omitted and can be1253 /// retrieved from the `into_remainder` function of the iterator.1254 ///1255 /// Due to each chunk having exactly `chunk_size` elements, the compiler can often optimize the1256 /// resulting code better than in the case of [`chunks_mut`].1257 ///1258 /// See [`chunks_mut`] for a variant of this iterator that also returns the remainder as a1259 /// smaller chunk, and [`rchunks_exact_mut`] for the same iterator but starting at the end of1260 /// the slice.1261 ///1262 /// If your `chunk_size` is a constant, consider using [`as_chunks_mut`] instead, which will1263 /// give references to arrays of exactly that length, rather than slices.1264 ///1265 /// # Panics1266 ///1267 /// Panics if `chunk_size` is zero.1268 ///1269 /// # Examples1270 ///1271 /// ```1272 /// let v = &mut [0, 0, 0, 0, 0];1273 /// let mut count = 1;1274 ///1275 /// for chunk in v.chunks_exact_mut(2) {1276 /// for elem in chunk.iter_mut() {1277 /// *elem += count;1278 /// }1279 /// count += 1;1280 /// }1281 /// assert_eq!(v, &[1, 1, 2, 2, 0]);1282 /// ```1283 ///1284 /// [`chunks_mut`]: slice::chunks_mut1285 /// [`rchunks_exact_mut`]: slice::rchunks_exact_mut1286 /// [`as_chunks_mut`]: slice::as_chunks_mut1287 #[stable(feature = "chunks_exact", since = "1.31.0")]1288 #[rustc_const_unstable(feature = "const_slice_make_iter", issue = "137737")]1289 #[inline]1290 #[track_caller]1291 pub const fn chunks_exact_mut(&mut self, chunk_size: usize) -> ChunksExactMut<'_, T> {1292 assert!(chunk_size != 0, "chunk size must be non-zero");1293 ChunksExactMut::new(self, chunk_size)1294 }1295 1296 /// Splits the slice into a slice of `N`-element arrays,1297 /// assuming that there's no remainder.1298 ///1299 /// This is the inverse operation to [`as_flattened`].1300 ///1301 /// [`as_flattened`]: slice::as_flattened1302 ///1303 /// As this is `unsafe`, consider whether you could use [`as_chunks`] or1304 /// [`as_rchunks`] instead, perhaps via something like1305 /// `if let (chunks, []) = slice.as_chunks()` or1306 /// `let (chunks, []) = slice.as_chunks() else { unreachable!() };`.1307 ///1308 /// [`as_chunks`]: slice::as_chunks1309 /// [`as_rchunks`]: slice::as_rchunks1310 ///1311 /// # Safety1312 ///1313 /// This may only be called when1314 /// - The slice splits exactly into `N`-element chunks (aka `self.len() % N == 0`).1315 /// - `N != 0`.1316 ///1317 /// # Examples1318 ///1319 /// ```1320 /// let slice: &[char] = &['l', 'o', 'r', 'e', 'm', '!'];1321 /// let chunks: &[[char; 1]] =1322 /// // SAFETY: 1-element chunks never have remainder1323 /// unsafe { slice.as_chunks_unchecked() };1324 /// assert_eq!(chunks, &[['l'], ['o'], ['r'], ['e'], ['m'], ['!']]);1325 /// let chunks: &[[char; 3]] =1326 /// // SAFETY: The slice length (6) is a multiple of 31327 /// unsafe { slice.as_chunks_unchecked() };1328 /// assert_eq!(chunks, &[['l', 'o', 'r'], ['e', 'm', '!']]);1329 ///1330 /// // These would be unsound:1331 /// // let chunks: &[[_; 5]] = slice.as_chunks_unchecked() // The slice length is not a multiple of 51332 /// // let chunks: &[[_; 0]] = slice.as_chunks_unchecked() // Zero-length chunks are never allowed1333 /// ```1334 #[stable(feature = "slice_as_chunks", since = "1.88.0")]1335 #[rustc_const_stable(feature = "slice_as_chunks", since = "1.88.0")]1336 #[inline]1337 #[must_use]1338 #[track_caller]1339 pub const unsafe fn as_chunks_unchecked<const N: usize>(&self) -> &[[T; N]] {1340 assert_unsafe_precondition!(1341 check_language_ub,1342 "slice::as_chunks_unchecked requires `N != 0` and the slice to split exactly into `N`-element chunks",1343 (n: usize = N, len: usize = self.len()) => n != 0 && len.is_multiple_of(n),1344 );1345 // SAFETY: Caller must guarantee that `N` is nonzero and exactly divides the slice length1346 let new_len = unsafe { exact_div(self.len(), N) };1347 // SAFETY: We cast a slice of `new_len * N` elements into1348 // a slice of `new_len` many `N` elements chunks.1349 unsafe { from_raw_parts(self.as_ptr().cast(), new_len) }1350 }1351 1352 /// Splits the slice into a slice of `N`-element arrays,1353 /// starting at the beginning of the slice,1354 /// and a remainder slice with length strictly less than `N`.1355 ///1356 /// The remainder is meaningful in the division sense. Given1357 /// `let (chunks, remainder) = slice.as_chunks()`, then:1358 /// - `chunks.len()` equals `slice.len() / N`,1359 /// - `remainder.len()` equals `slice.len() % N`, and1360 /// - `slice.len()` equals `chunks.len() * N + remainder.len()`.1361 ///1362 /// You can flatten the chunks back into a slice-of-`T` with [`as_flattened`].1363 ///1364 /// [`as_flattened`]: slice::as_flattened1365 ///1366 /// # Panics1367 ///1368 /// Panics if `N` is zero.1369 ///1370 /// Note that this check is against a const generic parameter, not a runtime1371 /// value, and thus a particular monomorphization will either always panic1372 /// or it will never panic.1373 ///1374 /// # Examples1375 ///1376 /// ```1377 /// let slice = ['l', 'o', 'r', 'e', 'm'];1378 /// let (chunks, remainder) = slice.as_chunks();1379 /// assert_eq!(chunks, &[['l', 'o'], ['r', 'e']]);1380 /// assert_eq!(remainder, &['m']);1381 /// ```1382 ///1383 /// If you expect the slice to be an exact multiple, you can combine1384 /// `let`-`else` with an empty slice pattern:1385 /// ```1386 /// let slice = ['R', 'u', 's', 't'];1387 /// let (chunks, []) = slice.as_chunks::<2>() else {1388 /// panic!("slice didn't have even length")1389 /// };1390 /// assert_eq!(chunks, &[['R', 'u'], ['s', 't']]);1391 /// ```1392 #[stable(feature = "slice_as_chunks", since = "1.88.0")]1393 #[rustc_const_stable(feature = "slice_as_chunks", since = "1.88.0")]1394 #[inline]1395 #[track_caller]1396 #[must_use]1397 pub const fn as_chunks<const N: usize>(&self) -> (&[[T; N]], &[T]) {1398 assert!(N != 0, "chunk size must be non-zero");1399 let len_rounded_down = self.len() / N * N;1400 // SAFETY: The rounded-down value is always the same or smaller than the1401 // original length, and thus must be in-bounds of the slice.1402 let (multiple_of_n, remainder) = unsafe { self.split_at_unchecked(len_rounded_down) };1403 // SAFETY: We already panicked for zero, and ensured by construction1404 // that the length of the subslice is a multiple of N.1405 let array_slice = unsafe { multiple_of_n.as_chunks_unchecked() };1406 (array_slice, remainder)1407 }1408 1409 /// Splits the slice into a slice of `N`-element arrays,1410 /// starting at the end of the slice,1411 /// and a remainder slice with length strictly less than `N`.1412 ///1413 /// The remainder is meaningful in the division sense. Given1414 /// `let (remainder, chunks) = slice.as_rchunks()`, then:1415 /// - `remainder.len()` equals `slice.len() % N`,1416 /// - `chunks.len()` equals `slice.len() / N`, and1417 /// - `slice.len()` equals `chunks.len() * N + remainder.len()`.1418 ///1419 /// You can flatten the chunks back into a slice-of-`T` with [`as_flattened`].1420 ///1421 /// [`as_flattened`]: slice::as_flattened1422 ///1423 /// # Panics1424 ///1425 /// Panics if `N` is zero.1426 ///1427 /// Note that this check is against a const generic parameter, not a runtime1428 /// value, and thus a particular monomorphization will either always panic1429 /// or it will never panic.1430 ///1431 /// # Examples1432 ///1433 /// ```1434 /// let slice = ['l', 'o', 'r', 'e', 'm'];1435 /// let (remainder, chunks) = slice.as_rchunks();1436 /// assert_eq!(remainder, &['l']);1437 /// assert_eq!(chunks, &[['o', 'r'], ['e', 'm']]);1438 /// ```1439 #[stable(feature = "slice_as_chunks", since = "1.88.0")]1440 #[rustc_const_stable(feature = "slice_as_chunks", since = "1.88.0")]1441 #[inline]1442 #[track_caller]1443 #[must_use]1444 pub const fn as_rchunks<const N: usize>(&self) -> (&[T], &[[T; N]]) {1445 assert!(N != 0, "chunk size must be non-zero");1446 let len = self.len() / N;1447 let (remainder, multiple_of_n) = self.split_at(self.len() - len * N);1448 // SAFETY: We already panicked for zero, and ensured by construction1449 // that the length of the subslice is a multiple of N.1450 let array_slice = unsafe { multiple_of_n.as_chunks_unchecked() };1451 (remainder, array_slice)1452 }1453 1454 /// Splits the slice into a slice of `N`-element arrays,1455 /// assuming that there's no remainder.1456 ///1457 /// This is the inverse operation to [`as_flattened_mut`].1458 ///1459 /// [`as_flattened_mut`]: slice::as_flattened_mut1460 ///1461 /// As this is `unsafe`, consider whether you could use [`as_chunks_mut`] or1462 /// [`as_rchunks_mut`] instead, perhaps via something like1463 /// `if let (chunks, []) = slice.as_chunks_mut()` or1464 /// `let (chunks, []) = slice.as_chunks_mut() else { unreachable!() };`.1465 ///1466 /// [`as_chunks_mut`]: slice::as_chunks_mut1467 /// [`as_rchunks_mut`]: slice::as_rchunks_mut1468 ///1469 /// # Safety1470 ///1471 /// This may only be called when1472 /// - The slice splits exactly into `N`-element chunks (aka `self.len() % N == 0`).1473 /// - `N != 0`.1474 ///1475 /// # Examples1476 ///1477 /// ```1478 /// let slice: &mut [char] = &mut ['l', 'o', 'r', 'e', 'm', '!'];1479 /// let chunks: &mut [[char; 1]] =1480 /// // SAFETY: 1-element chunks never have remainder1481 /// unsafe { slice.as_chunks_unchecked_mut() };1482 /// chunks[0] = ['L'];1483 /// assert_eq!(chunks, &[['L'], ['o'], ['r'], ['e'], ['m'], ['!']]);1484 /// let chunks: &mut [[char; 3]] =1485 /// // SAFETY: The slice length (6) is a multiple of 31486 /// unsafe { slice.as_chunks_unchecked_mut() };1487 /// chunks[1] = ['a', 'x', '?'];1488 /// assert_eq!(slice, &['L', 'o', 'r', 'a', 'x', '?']);1489 ///1490 /// // These would be unsound:1491 /// // let chunks: &[[_; 5]] = slice.as_chunks_unchecked_mut() // The slice length is not a multiple of 51492 /// // let chunks: &[[_; 0]] = slice.as_chunks_unchecked_mut() // Zero-length chunks are never allowed1493 /// ```1494 #[stable(feature = "slice_as_chunks", since = "1.88.0")]1495 #[rustc_const_stable(feature = "slice_as_chunks", since = "1.88.0")]1496 #[inline]1497 #[must_use]1498 #[track_caller]1499 pub const unsafe fn as_chunks_unchecked_mut<const N: usize>(&mut self) -> &mut [[T; N]] {1500 assert_unsafe_precondition!(1501 check_language_ub,1502 "slice::as_chunks_unchecked requires `N != 0` and the slice to split exactly into `N`-element chunks",1503 (n: usize = N, len: usize = self.len()) => n != 0 && len.is_multiple_of(n)1504 );1505 // SAFETY: Caller must guarantee that `N` is nonzero and exactly divides the slice length1506 let new_len = unsafe { exact_div(self.len(), N) };1507 // SAFETY: We cast a slice of `new_len * N` elements into1508 // a slice of `new_len` many `N` elements chunks.1509 unsafe { from_raw_parts_mut(self.as_mut_ptr().cast(), new_len) }1510 }1511 1512 /// Splits the slice into a slice of `N`-element arrays,1513 /// starting at the beginning of the slice,1514 /// and a remainder slice with length strictly less than `N`.1515 ///1516 /// The remainder is meaningful in the division sense. Given1517 /// `let (chunks, remainder) = slice.as_chunks_mut()`, then:1518 /// - `chunks.len()` equals `slice.len() / N`,1519 /// - `remainder.len()` equals `slice.len() % N`, and1520 /// - `slice.len()` equals `chunks.len() * N + remainder.len()`.1521 ///1522 /// You can flatten the chunks back into a slice-of-`T` with [`as_flattened_mut`].1523 ///1524 /// [`as_flattened_mut`]: slice::as_flattened_mut1525 ///1526 /// # Panics1527 ///1528 /// Panics if `N` is zero.1529 ///1530 /// Note that this check is against a const generic parameter, not a runtime1531 /// value, and thus a particular monomorphization will either always panic1532 /// or it will never panic.1533 ///1534 /// # Examples1535 ///1536 /// ```1537 /// let v = &mut [0, 0, 0, 0, 0];1538 /// let mut count = 1;1539 ///1540 /// let (chunks, remainder) = v.as_chunks_mut();1541 /// remainder[0] = 9;1542 /// for chunk in chunks {1543 /// *chunk = [count; 2];1544 /// count += 1;1545 /// }1546 /// assert_eq!(v, &[1, 1, 2, 2, 9]);1547 /// ```1548 #[stable(feature = "slice_as_chunks", since = "1.88.0")]1549 #[rustc_const_stable(feature = "slice_as_chunks", since = "1.88.0")]1550 #[inline]1551 #[track_caller]1552 #[must_use]1553 pub const fn as_chunks_mut<const N: usize>(&mut self) -> (&mut [[T; N]], &mut [T]) {1554 assert!(N != 0, "chunk size must be non-zero");1555 let len_rounded_down = self.len() / N * N;1556 // SAFETY: The rounded-down value is always the same or smaller than the1557 // original length, and thus must be in-bounds of the slice.1558 let (multiple_of_n, remainder) = unsafe { self.split_at_mut_unchecked(len_rounded_down) };1559 // SAFETY: We already panicked for zero, and ensured by construction1560 // that the length of the subslice is a multiple of N.1561 let array_slice = unsafe { multiple_of_n.as_chunks_unchecked_mut() };1562 (array_slice, remainder)1563 }1564 1565 /// Splits the slice into a slice of `N`-element arrays,1566 /// starting at the end of the slice,1567 /// and a remainder slice with length strictly less than `N`.1568 ///1569 /// The remainder is meaningful in the division sense. Given1570 /// `let (remainder, chunks) = slice.as_rchunks_mut()`, then:1571 /// - `remainder.len()` equals `slice.len() % N`,1572 /// - `chunks.len()` equals `slice.len() / N`, and1573 /// - `slice.len()` equals `chunks.len() * N + remainder.len()`.1574 ///1575 /// You can flatten the chunks back into a slice-of-`T` with [`as_flattened_mut`].1576 ///1577 /// [`as_flattened_mut`]: slice::as_flattened_mut1578 ///1579 /// # Panics1580 ///1581 /// Panics if `N` is zero.1582 ///1583 /// Note that this check is against a const generic parameter, not a runtime1584 /// value, and thus a particular monomorphization will either always panic1585 /// or it will never panic.1586 ///1587 /// # Examples1588 ///1589 /// ```1590 /// let v = &mut [0, 0, 0, 0, 0];1591 /// let mut count = 1;1592 ///1593 /// let (remainder, chunks) = v.as_rchunks_mut();1594 /// remainder[0] = 9;1595 /// for chunk in chunks {1596 /// *chunk = [count; 2];1597 /// count += 1;1598 /// }1599 /// assert_eq!(v, &[9, 1, 1, 2, 2]);1600 /// ```1601 #[stable(feature = "slice_as_chunks", since = "1.88.0")]1602 #[rustc_const_stable(feature = "slice_as_chunks", since = "1.88.0")]1603 #[inline]1604 #[track_caller]1605 #[must_use]1606 pub const fn as_rchunks_mut<const N: usize>(&mut self) -> (&mut [T], &mut [[T; N]]) {1607 assert!(N != 0, "chunk size must be non-zero");1608 let len = self.len() / N;1609 let (remainder, multiple_of_n) = self.split_at_mut(self.len() - len * N);1610 // SAFETY: We already panicked for zero, and ensured by construction1611 // that the length of the subslice is a multiple of N.1612 let array_slice = unsafe { multiple_of_n.as_chunks_unchecked_mut() };1613 (remainder, array_slice)1614 }1615 1616 /// Returns an iterator over overlapping windows of `N` elements of a slice,1617 /// starting at the beginning of the slice.1618 ///1619 /// This is the const generic equivalent of [`windows`].1620 ///1621 /// If `N` is greater than the size of the slice, it will return no windows.1622 ///1623 /// # Panics1624 ///1625 /// Panics if `N` is zero.1626 ///1627 /// Note that this check is against a const generic parameter, not a runtime1628 /// value, and thus a particular monomorphization will either always panic1629 /// or it will never panic.1630 ///1631 /// # Examples1632 ///1633 /// ```1634 /// let slice = [0, 1, 2, 3];1635 /// let mut iter = slice.array_windows();1636 /// assert_eq!(iter.next().unwrap(), &[0, 1]);1637 /// assert_eq!(iter.next().unwrap(), &[1, 2]);1638 /// assert_eq!(iter.next().unwrap(), &[2, 3]);1639 /// assert!(iter.next().is_none());1640 /// ```1641 ///1642 /// [`windows`]: slice::windows1643 #[stable(feature = "array_windows", since = "1.94.0")]1644 #[rustc_const_unstable(feature = "const_slice_make_iter", issue = "137737")]1645 #[inline]1646 #[track_caller]1647 pub const fn array_windows<const N: usize>(&self) -> ArrayWindows<'_, T, N> {1648 assert!(N != 0, "window size must be non-zero");1649 ArrayWindows::new(self)1650 }1651 1652 /// Returns an iterator over `chunk_size` elements of the slice at a time, starting at the end1653 /// of the slice.1654 ///1655 /// The chunks are slices and do not overlap. If `chunk_size` does not divide the length of the1656 /// slice, then the last chunk will not have length `chunk_size`.1657 ///1658 /// See [`rchunks_exact`] for a variant of this iterator that returns chunks of always exactly1659 /// `chunk_size` elements, and [`chunks`] for the same iterator but starting at the beginning1660 /// of the slice.1661 ///1662 /// If your `chunk_size` is a constant, consider using [`as_rchunks`] instead, which will1663 /// give references to arrays of exactly that length, rather than slices.1664 ///1665 /// # Panics1666 ///1667 /// Panics if `chunk_size` is zero.1668 ///1669 /// # Examples1670 ///1671 /// ```1672 /// let slice = ['l', 'o', 'r', 'e', 'm'];1673 /// let mut iter = slice.rchunks(2);1674 /// assert_eq!(iter.next().unwrap(), &['e', 'm']);1675 /// assert_eq!(iter.next().unwrap(), &['o', 'r']);1676 /// assert_eq!(iter.next().unwrap(), &['l']);1677 /// assert!(iter.next().is_none());1678 /// ```1679 ///1680 /// [`rchunks_exact`]: slice::rchunks_exact1681 /// [`chunks`]: slice::chunks1682 /// [`as_rchunks`]: slice::as_rchunks1683 #[stable(feature = "rchunks", since = "1.31.0")]1684 #[rustc_const_unstable(feature = "const_slice_make_iter", issue = "137737")]1685 #[inline]1686 #[track_caller]1687 pub const fn rchunks(&self, chunk_size: usize) -> RChunks<'_, T> {1688 assert!(chunk_size != 0, "chunk size must be non-zero");1689 RChunks::new(self, chunk_size)1690 }1691 1692 /// Returns an iterator over `chunk_size` elements of the slice at a time, starting at the end1693 /// of the slice.1694 ///1695 /// The chunks are mutable slices, and do not overlap. If `chunk_size` does not divide the1696 /// length of the slice, then the last chunk will not have length `chunk_size`.1697 ///1698 /// See [`rchunks_exact_mut`] for a variant of this iterator that returns chunks of always1699 /// exactly `chunk_size` elements, and [`chunks_mut`] for the same iterator but starting at the1700 /// beginning of the slice.1701 ///1702 /// If your `chunk_size` is a constant, consider using [`as_rchunks_mut`] instead, which will1703 /// give references to arrays of exactly that length, rather than slices.1704 ///1705 /// # Panics1706 ///1707 /// Panics if `chunk_size` is zero.1708 ///1709 /// # Examples1710 ///1711 /// ```1712 /// let v = &mut [0, 0, 0, 0, 0];1713 /// let mut count = 1;1714 ///1715 /// for chunk in v.rchunks_mut(2) {1716 /// for elem in chunk.iter_mut() {1717 /// *elem += count;1718 /// }1719 /// count += 1;1720 /// }1721 /// assert_eq!(v, &[3, 2, 2, 1, 1]);1722 /// ```1723 ///1724 /// [`rchunks_exact_mut`]: slice::rchunks_exact_mut1725 /// [`chunks_mut`]: slice::chunks_mut1726 /// [`as_rchunks_mut`]: slice::as_rchunks_mut1727 #[stable(feature = "rchunks", since = "1.31.0")]1728 #[rustc_const_unstable(feature = "const_slice_make_iter", issue = "137737")]1729 #[inline]1730 #[track_caller]1731 pub const fn rchunks_mut(&mut self, chunk_size: usize) -> RChunksMut<'_, T> {1732 assert!(chunk_size != 0, "chunk size must be non-zero");1733 RChunksMut::new(self, chunk_size)1734 }1735 1736 /// Returns an iterator over `chunk_size` elements of the slice at a time, starting at the1737 /// end of the slice.1738 ///1739 /// The chunks are slices and do not overlap. If `chunk_size` does not divide the length of the1740 /// slice, then the last up to `chunk_size-1` elements will be omitted and can be retrieved1741 /// from the `remainder` function of the iterator.1742 ///1743 /// Due to each chunk having exactly `chunk_size` elements, the compiler can often optimize the1744 /// resulting code better than in the case of [`rchunks`].1745 ///1746 /// See [`rchunks`] for a variant of this iterator that also returns the remainder as a smaller1747 /// chunk, and [`chunks_exact`] for the same iterator but starting at the beginning of the1748 /// slice.1749 ///1750 /// If your `chunk_size` is a constant, consider using [`as_rchunks`] instead, which will1751 /// give references to arrays of exactly that length, rather than slices.1752 ///1753 /// # Panics1754 ///1755 /// Panics if `chunk_size` is zero.1756 ///1757 /// # Examples1758 ///1759 /// ```1760 /// let slice = ['l', 'o', 'r', 'e', 'm'];1761 /// let mut iter = slice.rchunks_exact(2);1762 /// assert_eq!(iter.next().unwrap(), &['e', 'm']);1763 /// assert_eq!(iter.next().unwrap(), &['o', 'r']);1764 /// assert!(iter.next().is_none());1765 /// assert_eq!(iter.remainder(), &['l']);1766 /// ```1767 ///1768 /// [`chunks`]: slice::chunks1769 /// [`rchunks`]: slice::rchunks1770 /// [`chunks_exact`]: slice::chunks_exact1771 /// [`as_rchunks`]: slice::as_rchunks1772 #[stable(feature = "rchunks", since = "1.31.0")]1773 #[rustc_const_unstable(feature = "const_slice_make_iter", issue = "137737")]1774 #[inline]1775 #[track_caller]1776 pub const fn rchunks_exact(&self, chunk_size: usize) -> RChunksExact<'_, T> {1777 assert!(chunk_size != 0, "chunk size must be non-zero");1778 RChunksExact::new(self, chunk_size)1779 }1780 1781 /// Returns an iterator over `chunk_size` elements of the slice at a time, starting at the end1782 /// of the slice.1783 ///1784 /// The chunks are mutable slices, and do not overlap. If `chunk_size` does not divide the1785 /// length of the slice, then the last up to `chunk_size-1` elements will be omitted and can be1786 /// retrieved from the `into_remainder` function of the iterator.1787 ///1788 /// Due to each chunk having exactly `chunk_size` elements, the compiler can often optimize the1789 /// resulting code better than in the case of [`chunks_mut`].1790 ///1791 /// See [`rchunks_mut`] for a variant of this iterator that also returns the remainder as a1792 /// smaller chunk, and [`chunks_exact_mut`] for the same iterator but starting at the beginning1793 /// of the slice.1794 ///1795 /// If your `chunk_size` is a constant, consider using [`as_rchunks_mut`] instead, which will1796 /// give references to arrays of exactly that length, rather than slices.1797 ///1798 /// # Panics1799 ///1800 /// Panics if `chunk_size` is zero.1801 ///1802 /// # Examples1803 ///1804 /// ```1805 /// let v = &mut [0, 0, 0, 0, 0];1806 /// let mut count = 1;1807 ///1808 /// for chunk in v.rchunks_exact_mut(2) {1809 /// for elem in chunk.iter_mut() {1810 /// *elem += count;1811 /// }1812 /// count += 1;1813 /// }1814 /// assert_eq!(v, &[0, 2, 2, 1, 1]);1815 /// ```1816 ///1817 /// [`chunks_mut`]: slice::chunks_mut1818 /// [`rchunks_mut`]: slice::rchunks_mut1819 /// [`chunks_exact_mut`]: slice::chunks_exact_mut1820 /// [`as_rchunks_mut`]: slice::as_rchunks_mut1821 #[stable(feature = "rchunks", since = "1.31.0")]1822 #[rustc_const_unstable(feature = "const_slice_make_iter", issue = "137737")]1823 #[inline]1824 #[track_caller]1825 pub const fn rchunks_exact_mut(&mut self, chunk_size: usize) -> RChunksExactMut<'_, T> {1826 assert!(chunk_size != 0, "chunk size must be non-zero");1827 RChunksExactMut::new(self, chunk_size)1828 }1829 1830 /// Returns an iterator over the slice producing non-overlapping runs1831 /// of elements using the predicate to separate them.1832 ///1833 /// The predicate is called for every pair of consecutive elements,1834 /// meaning that it is called on `slice[0]` and `slice[1]`,1835 /// followed by `slice[1]` and `slice[2]`, and so on.1836 ///1837 /// # Examples1838 ///1839 /// ```1840 /// let slice = &[1, 1, 1, 3, 3, 2, 2, 2];1841 ///1842 /// let mut iter = slice.chunk_by(|a, b| a == b);1843 ///1844 /// assert_eq!(iter.next(), Some(&[1, 1, 1][..]));1845 /// assert_eq!(iter.next(), Some(&[3, 3][..]));1846 /// assert_eq!(iter.next(), Some(&[2, 2, 2][..]));1847 /// assert_eq!(iter.next(), None);1848 /// ```1849 ///1850 /// This method can be used to extract the sorted subslices:1851 ///1852 /// ```1853 /// let slice = &[1, 1, 2, 3, 2, 3, 2, 3, 4];1854 ///1855 /// let mut iter = slice.chunk_by(|a, b| a <= b);1856 ///1857 /// assert_eq!(iter.next(), Some(&[1, 1, 2, 3][..]));1858 /// assert_eq!(iter.next(), Some(&[2, 3][..]));1859 /// assert_eq!(iter.next(), Some(&[2, 3, 4][..]));1860 /// assert_eq!(iter.next(), None);1861 /// ```1862 #[stable(feature = "slice_group_by", since = "1.77.0")]1863 #[rustc_const_unstable(feature = "const_slice_make_iter", issue = "137737")]1864 #[inline]1865 pub const fn chunk_by<F>(&self, pred: F) -> ChunkBy<'_, T, F>1866 where1867 F: FnMut(&T, &T) -> bool,1868 {1869 ChunkBy::new(self, pred)1870 }1871 1872 /// Returns an iterator over the slice producing non-overlapping mutable1873 /// runs of elements using the predicate to separate them.1874 ///1875 /// The predicate is called for every pair of consecutive elements,1876 /// meaning that it is called on `slice[0]` and `slice[1]`,1877 /// followed by `slice[1]` and `slice[2]`, and so on.1878 ///1879 /// # Examples1880 ///1881 /// ```1882 /// let slice = &mut [1, 1, 1, 3, 3, 2, 2, 2];1883 ///1884 /// let mut iter = slice.chunk_by_mut(|a, b| a == b);1885 ///1886 /// assert_eq!(iter.next(), Some(&mut [1, 1, 1][..]));1887 /// assert_eq!(iter.next(), Some(&mut [3, 3][..]));1888 /// assert_eq!(iter.next(), Some(&mut [2, 2, 2][..]));1889 /// assert_eq!(iter.next(), None);1890 /// ```1891 ///1892 /// This method can be used to extract the sorted subslices:1893 ///1894 /// ```1895 /// let slice = &mut [1, 1, 2, 3, 2, 3, 2, 3, 4];1896 ///1897 /// let mut iter = slice.chunk_by_mut(|a, b| a <= b);1898 ///1899 /// assert_eq!(iter.next(), Some(&mut [1, 1, 2, 3][..]));1900 /// assert_eq!(iter.next(), Some(&mut [2, 3][..]));1901 /// assert_eq!(iter.next(), Some(&mut [2, 3, 4][..]));1902 /// assert_eq!(iter.next(), None);1903 /// ```1904 #[stable(feature = "slice_group_by", since = "1.77.0")]1905 #[rustc_const_unstable(feature = "const_slice_make_iter", issue = "137737")]1906 #[inline]1907 pub const fn chunk_by_mut<F>(&mut self, pred: F) -> ChunkByMut<'_, T, F>1908 where1909 F: FnMut(&T, &T) -> bool,1910 {1911 ChunkByMut::new(self, pred)1912 }1913 1914 /// Divides one slice into two at an index.1915 ///1916 /// The first will contain all indices from `[0, mid)` (excluding1917 /// the index `mid` itself) and the second will contain all1918 /// indices from `[mid, len)` (excluding the index `len` itself).1919 ///1920 /// # Panics1921 ///1922 /// Panics if `mid > len`. For a non-panicking alternative see1923 /// [`split_at_checked`](slice::split_at_checked).1924 ///1925 /// # Examples1926 ///1927 /// ```1928 /// let v = ['a', 'b', 'c'];1929 ///1930 /// {1931 /// let (left, right) = v.split_at(0);1932 /// assert_eq!(left, []);1933 /// assert_eq!(right, ['a', 'b', 'c']);1934 /// }1935 ///1936 /// {1937 /// let (left, right) = v.split_at(2);1938 /// assert_eq!(left, ['a', 'b']);1939 /// assert_eq!(right, ['c']);1940 /// }1941 ///1942 /// {1943 /// let (left, right) = v.split_at(3);1944 /// assert_eq!(left, ['a', 'b', 'c']);1945 /// assert_eq!(right, []);1946 /// }1947 /// ```1948 #[stable(feature = "rust1", since = "1.0.0")]1949 #[rustc_const_stable(feature = "const_slice_split_at_not_mut", since = "1.71.0")]1950 #[inline]1951 #[track_caller]1952 #[must_use]1953 pub const fn split_at(&self, mid: usize) -> (&[T], &[T]) {1954 match self.split_at_checked(mid) {1955 Some(pair) => pair,1956 None => panic!("mid > len"),1957 }1958 }1959 1960 /// Divides one mutable slice into two at an index.1961 ///1962 /// The first will contain all indices from `[0, mid)` (excluding1963 /// the index `mid` itself) and the second will contain all1964 /// indices from `[mid, len)` (excluding the index `len` itself).1965 ///1966 /// # Panics1967 ///1968 /// Panics if `mid > len`. For a non-panicking alternative see1969 /// [`split_at_mut_checked`](slice::split_at_mut_checked).1970 ///1971 /// # Examples1972 ///1973 /// ```1974 /// let mut v = [1, 0, 3, 0, 5, 6];1975 /// let (left, right) = v.split_at_mut(2);1976 /// assert_eq!(left, [1, 0]);1977 /// assert_eq!(right, [3, 0, 5, 6]);1978 /// left[1] = 2;1979 /// right[1] = 4;1980 /// assert_eq!(v, [1, 2, 3, 4, 5, 6]);1981 /// ```1982 #[stable(feature = "rust1", since = "1.0.0")]1983 #[inline]1984 #[track_caller]1985 #[must_use]1986 #[rustc_const_stable(feature = "const_slice_split_at_mut", since = "1.83.0")]1987 pub const fn split_at_mut(&mut self, mid: usize) -> (&mut [T], &mut [T]) {1988 match self.split_at_mut_checked(mid) {1989 Some(pair) => pair,1990 None => panic!("mid > len"),1991 }1992 }1993 1994 /// Divides one slice into two at an index, without doing bounds checking.1995 ///1996 /// The first will contain all indices from `[0, mid)` (excluding1997 /// the index `mid` itself) and the second will contain all1998 /// indices from `[mid, len)` (excluding the index `len` itself).1999 ///2000 /// For a safe alternative see [`split_at`].2001 ///2002 /// # Safety2003 ///2004 /// Calling this method with an out-of-bounds index is *[undefined behavior]*2005 /// even if the resulting reference is not used. The caller has to ensure that2006 /// `0 <= mid <= self.len()`.2007 ///2008 /// [`split_at`]: slice::split_at2009 /// [undefined behavior]: https://doc.rust-lang.org/reference/behavior-considered-undefined.html2010 ///2011 /// # Examples2012 ///2013 /// ```2014 /// let v = ['a', 'b', 'c'];2015 ///2016 /// unsafe {2017 /// let (left, right) = v.split_at_unchecked(0);2018 /// assert_eq!(left, []);2019 /// assert_eq!(right, ['a', 'b', 'c']);2020 /// }2021 ///2022 /// unsafe {2023 /// let (left, right) = v.split_at_unchecked(2);2024 /// assert_eq!(left, ['a', 'b']);2025 /// assert_eq!(right, ['c']);2026 /// }2027 ///2028 /// unsafe {2029 /// let (left, right) = v.split_at_unchecked(3);2030 /// assert_eq!(left, ['a', 'b', 'c']);2031 /// assert_eq!(right, []);2032 /// }2033 /// ```2034 #[stable(feature = "slice_split_at_unchecked", since = "1.79.0")]2035 #[rustc_const_stable(feature = "const_slice_split_at_unchecked", since = "1.77.0")]2036 #[inline]2037 #[must_use]2038 #[track_caller]2039 pub const unsafe fn split_at_unchecked(&self, mid: usize) -> (&[T], &[T]) {2040 // FIXME(const-hack): the const function `from_raw_parts` is used to make this2041 // function const; previously the implementation used2042 // `(self.get_unchecked(..mid), self.get_unchecked(mid..))`2043 2044 let len = self.len();2045 let ptr = self.as_ptr();2046 2047 assert_unsafe_precondition!(2048 check_library_ub,2049 "slice::split_at_unchecked requires the index to be within the slice",2050 (mid: usize = mid, len: usize = len) => mid <= len,2051 );2052 2053 // SAFETY: Caller has to check that `0 <= mid <= self.len()`2054 unsafe { (from_raw_parts(ptr, mid), from_raw_parts(ptr.add(mid), unchecked_sub(len, mid))) }2055 }2056 2057 /// Divides one mutable slice into two at an index, without doing bounds checking.2058 ///2059 /// The first will contain all indices from `[0, mid)` (excluding2060 /// the index `mid` itself) and the second will contain all2061 /// indices from `[mid, len)` (excluding the index `len` itself).2062 ///2063 /// For a safe alternative see [`split_at_mut`].2064 ///2065 /// # Safety2066 ///2067 /// Calling this method with an out-of-bounds index is *[undefined behavior]*2068 /// even if the resulting reference is not used. The caller has to ensure that2069 /// `0 <= mid <= self.len()`.2070 ///2071 /// [`split_at_mut`]: slice::split_at_mut2072 /// [undefined behavior]: https://doc.rust-lang.org/reference/behavior-considered-undefined.html2073 ///2074 /// # Examples2075 ///2076 /// ```2077 /// let mut v = [1, 0, 3, 0, 5, 6];2078 /// // scoped to restrict the lifetime of the borrows2079 /// unsafe {2080 /// let (left, right) = v.split_at_mut_unchecked(2);2081 /// assert_eq!(left, [1, 0]);2082 /// assert_eq!(right, [3, 0, 5, 6]);2083 /// left[1] = 2;2084 /// right[1] = 4;2085 /// }2086 /// assert_eq!(v, [1, 2, 3, 4, 5, 6]);2087 /// ```2088 #[stable(feature = "slice_split_at_unchecked", since = "1.79.0")]2089 #[rustc_const_stable(feature = "const_slice_split_at_mut", since = "1.83.0")]2090 #[inline]2091 #[must_use]2092 #[track_caller]2093 pub const unsafe fn split_at_mut_unchecked(&mut self, mid: usize) -> (&mut [T], &mut [T]) {2094 let len = self.len();2095 let ptr = self.as_mut_ptr();2096 2097 assert_unsafe_precondition!(2098 check_library_ub,2099 "slice::split_at_mut_unchecked requires the index to be within the slice",2100 (mid: usize = mid, len: usize = len) => mid <= len,2101 );2102 2103 // SAFETY: Caller has to check that `0 <= mid <= self.len()`.2104 //2105 // `[ptr; mid]` and `[mid; len]` are not overlapping, so returning a mutable reference2106 // is fine.2107 unsafe {2108 (2109 from_raw_parts_mut(ptr, mid),2110 from_raw_parts_mut(ptr.add(mid), unchecked_sub(len, mid)),2111 )2112 }2113 }2114 2115 /// Divides one slice into two at an index, returning `None` if the slice is2116 /// too short.2117 ///2118 /// If `mid โค len` returns a pair of slices where the first will contain all2119 /// indices from `[0, mid)` (excluding the index `mid` itself) and the2120 /// second will contain all indices from `[mid, len)` (excluding the index2121 /// `len` itself).2122 ///2123 /// Otherwise, if `mid > len`, returns `None`.2124 ///2125 /// # Examples2126 ///2127 /// ```2128 /// let v = [1, -2, 3, -4, 5, -6];2129 ///2130 /// {2131 /// let (left, right) = v.split_at_checked(0).unwrap();2132 /// assert_eq!(left, []);2133 /// assert_eq!(right, [1, -2, 3, -4, 5, -6]);2134 /// }2135 ///2136 /// {2137 /// let (left, right) = v.split_at_checked(2).unwrap();2138 /// assert_eq!(left, [1, -2]);2139 /// assert_eq!(right, [3, -4, 5, -6]);2140 /// }2141 ///2142 /// {2143 /// let (left, right) = v.split_at_checked(6).unwrap();2144 /// assert_eq!(left, [1, -2, 3, -4, 5, -6]);2145 /// assert_eq!(right, []);2146 /// }2147 ///2148 /// assert_eq!(None, v.split_at_checked(7));2149 /// ```2150 #[stable(feature = "split_at_checked", since = "1.80.0")]2151 #[rustc_const_stable(feature = "split_at_checked", since = "1.80.0")]2152 #[inline]2153 #[must_use]2154 pub const fn split_at_checked(&self, mid: usize) -> Option<(&[T], &[T])> {2155 if mid <= self.len() {2156 // SAFETY: `[ptr; mid]` and `[mid; len]` are inside `self`, which2157 // fulfills the requirements of `split_at_unchecked`.2158 Some(unsafe { self.split_at_unchecked(mid) })2159 } else {2160 None2161 }2162 }2163 2164 /// Divides one mutable slice into two at an index, returning `None` if the2165 /// slice is too short.2166 ///2167 /// If `mid โค len` returns a pair of slices where the first will contain all2168 /// indices from `[0, mid)` (excluding the index `mid` itself) and the2169 /// second will contain all indices from `[mid, len)` (excluding the index2170 /// `len` itself).2171 ///2172 /// Otherwise, if `mid > len`, returns `None`.2173 ///2174 /// # Examples2175 ///2176 /// ```2177 /// let mut v = [1, 0, 3, 0, 5, 6];2178 ///2179 /// if let Some((left, right)) = v.split_at_mut_checked(2) {2180 /// assert_eq!(left, [1, 0]);2181 /// assert_eq!(right, [3, 0, 5, 6]);2182 /// left[1] = 2;2183 /// right[1] = 4;2184 /// }2185 /// assert_eq!(v, [1, 2, 3, 4, 5, 6]);2186 ///2187 /// assert_eq!(None, v.split_at_mut_checked(7));2188 /// ```2189 #[stable(feature = "split_at_checked", since = "1.80.0")]2190 #[rustc_const_stable(feature = "const_slice_split_at_mut", since = "1.83.0")]2191 #[inline]2192 #[must_use]2193 pub const fn split_at_mut_checked(&mut self, mid: usize) -> Option<(&mut [T], &mut [T])> {2194 if mid <= self.len() {2195 // SAFETY: `[ptr; mid]` and `[mid; len]` are inside `self`, which2196 // fulfills the requirements of `split_at_unchecked`.2197 Some(unsafe { self.split_at_mut_unchecked(mid) })2198 } else {2199 None2200 }2201 }2202 2203 /// Returns an iterator over subslices separated by elements that match2204 /// `pred`. The matched element is not contained in the subslices.2205 ///2206 /// # Examples2207 ///2208 /// ```2209 /// let slice = [10, 40, 33, 20];2210 /// let mut iter = slice.split(|num| num % 3 == 0);2211 ///2212 /// assert_eq!(iter.next().unwrap(), &[10, 40]);2213 /// assert_eq!(iter.next().unwrap(), &[20]);2214 /// assert!(iter.next().is_none());2215 /// ```2216 ///2217 /// If the first element is matched, an empty slice will be the first item2218 /// returned by the iterator. Similarly, if the last element in the slice2219 /// is matched, an empty slice will be the last item returned by the2220 /// iterator:2221 ///2222 /// ```2223 /// let slice = [10, 40, 33];2224 /// let mut iter = slice.split(|num| num % 3 == 0);2225 ///2226 /// assert_eq!(iter.next().unwrap(), &[10, 40]);2227 /// assert_eq!(iter.next().unwrap(), &[]);2228 /// assert!(iter.next().is_none());2229 /// ```2230 ///2231 /// If two matched elements are directly adjacent, an empty slice will be2232 /// present between them:2233 ///2234 /// ```2235 /// let slice = [10, 6, 33, 20];2236 /// let mut iter = slice.split(|num| num % 3 == 0);2237 ///2238 /// assert_eq!(iter.next().unwrap(), &[10]);2239 /// assert_eq!(iter.next().unwrap(), &[]);2240 /// assert_eq!(iter.next().unwrap(), &[20]);2241 /// assert!(iter.next().is_none());2242 /// ```2243 #[stable(feature = "rust1", since = "1.0.0")]2244 #[inline]2245 pub fn split<F>(&self, pred: F) -> Split<'_, T, F>2246 where2247 F: FnMut(&T) -> bool,2248 {2249 Split::new(self, pred)2250 }2251 2252 /// Returns an iterator over mutable subslices separated by elements that2253 /// match `pred`. The matched element is not contained in the subslices.2254 ///2255 /// # Examples2256 ///2257 /// ```2258 /// let mut v = [10, 40, 30, 20, 60, 50];2259 ///2260 /// for group in v.split_mut(|num| *num % 3 == 0) {2261 /// group[0] = 1;2262 /// }2263 /// assert_eq!(v, [1, 40, 30, 1, 60, 1]);2264 /// ```2265 #[stable(feature = "rust1", since = "1.0.0")]2266 #[inline]2267 pub fn split_mut<F>(&mut self, pred: F) -> SplitMut<'_, T, F>2268 where2269 F: FnMut(&T) -> bool,2270 {2271 SplitMut::new(self, pred)2272 }2273 2274 /// Returns an iterator over subslices separated by elements that match2275 /// `pred`. The matched element is contained in the end of the previous2276 /// subslice as a terminator.2277 ///2278 /// # Examples2279 ///2280 /// ```2281 /// let slice = [10, 40, 33, 20];2282 /// let mut iter = slice.split_inclusive(|num| num % 3 == 0);2283 ///2284 /// assert_eq!(iter.next().unwrap(), &[10, 40, 33]);2285 /// assert_eq!(iter.next().unwrap(), &[20]);2286 /// assert!(iter.next().is_none());2287 /// ```2288 ///2289 /// If the last element of the slice is matched,2290 /// that element will be considered the terminator of the preceding slice.2291 /// That slice will be the last item returned by the iterator.2292 ///2293 /// ```2294 /// let slice = [3, 10, 40, 33];2295 /// let mut iter = slice.split_inclusive(|num| num % 3 == 0);2296 ///2297 /// assert_eq!(iter.next().unwrap(), &[3]);2298 /// assert_eq!(iter.next().unwrap(), &[10, 40, 33]);2299 /// assert!(iter.next().is_none());2300 /// ```2301 #[stable(feature = "split_inclusive", since = "1.51.0")]2302 #[inline]2303 pub fn split_inclusive<F>(&self, pred: F) -> SplitInclusive<'_, T, F>2304 where2305 F: FnMut(&T) -> bool,2306 {2307 SplitInclusive::new(self, pred)2308 }2309 2310 /// Returns an iterator over mutable subslices separated by elements that2311 /// match `pred`. The matched element is contained in the previous2312 /// subslice as a terminator.2313 ///2314 /// # Examples2315 ///2316 /// ```2317 /// let mut v = [10, 40, 30, 20, 60, 50];2318 ///2319 /// for group in v.split_inclusive_mut(|num| *num % 3 == 0) {2320 /// let terminator_idx = group.len()-1;2321 /// group[terminator_idx] = 1;2322 /// }2323 /// assert_eq!(v, [10, 40, 1, 20, 1, 1]);2324 /// ```2325 #[stable(feature = "split_inclusive", since = "1.51.0")]2326 #[inline]2327 pub fn split_inclusive_mut<F>(&mut self, pred: F) -> SplitInclusiveMut<'_, T, F>2328 where2329 F: FnMut(&T) -> bool,2330 {2331 SplitInclusiveMut::new(self, pred)2332 }2333 2334 /// Returns an iterator over subslices separated by elements that match2335 /// `pred`, starting at the end of the slice and working backwards.2336 /// The matched element is not contained in the subslices.2337 ///2338 /// # Examples2339 ///2340 /// ```2341 /// let slice = [11, 22, 33, 0, 44, 55];2342 /// let mut iter = slice.rsplit(|num| *num == 0);2343 ///2344 /// assert_eq!(iter.next().unwrap(), &[44, 55]);2345 /// assert_eq!(iter.next().unwrap(), &[11, 22, 33]);2346 /// assert_eq!(iter.next(), None);2347 /// ```2348 ///2349 /// As with `split()`, if the first or last element is matched, an empty2350 /// slice will be the first (or last) item returned by the iterator.2351 ///2352 /// ```2353 /// let v = &[0, 1, 1, 2, 3, 5, 8];2354 /// let mut it = v.rsplit(|n| *n % 2 == 0);2355 /// assert_eq!(it.next().unwrap(), &[]);2356 /// assert_eq!(it.next().unwrap(), &[3, 5]);2357 /// assert_eq!(it.next().unwrap(), &[1, 1]);2358 /// assert_eq!(it.next().unwrap(), &[]);2359 /// assert_eq!(it.next(), None);2360 /// ```2361 #[stable(feature = "slice_rsplit", since = "1.27.0")]2362 #[inline]2363 pub fn rsplit<F>(&self, pred: F) -> RSplit<'_, T, F>2364 where2365 F: FnMut(&T) -> bool,2366 {2367 RSplit::new(self, pred)2368 }2369 2370 /// Returns an iterator over mutable subslices separated by elements that2371 /// match `pred`, starting at the end of the slice and working2372 /// backwards. The matched element is not contained in the subslices.2373 ///2374 /// # Examples2375 ///2376 /// ```2377 /// let mut v = [100, 400, 300, 200, 600, 500];2378 ///2379 /// let mut count = 0;2380 /// for group in v.rsplit_mut(|num| *num % 3 == 0) {2381 /// count += 1;2382 /// group[0] = count;2383 /// }2384 /// assert_eq!(v, [3, 400, 300, 2, 600, 1]);2385 /// ```2386 ///2387 #[stable(feature = "slice_rsplit", since = "1.27.0")]2388 #[inline]2389 pub fn rsplit_mut<F>(&mut self, pred: F) -> RSplitMut<'_, T, F>2390 where2391 F: FnMut(&T) -> bool,2392 {2393 RSplitMut::new(self, pred)2394 }2395 2396 /// Returns an iterator over subslices separated by elements that match2397 /// `pred`, limited to returning at most `n` items. The matched element is2398 /// not contained in the subslices.2399 ///2400 /// The last element returned, if any, will contain the remainder of the2401 /// slice.2402 ///2403 /// # Examples2404 ///2405 /// Print the slice split once by numbers divisible by 3 (i.e., `[10, 40]`,2406 /// `[20, 60, 50]`):2407 ///2408 /// ```2409 /// let v = [10, 40, 30, 20, 60, 50];2410 ///2411 /// for group in v.splitn(2, |num| *num % 3 == 0) {2412 /// println!("{group:?}");2413 /// }2414 /// ```2415 #[stable(feature = "rust1", since = "1.0.0")]2416 #[inline]2417 pub fn splitn<F>(&self, n: usize, pred: F) -> SplitN<'_, T, F>2418 where2419 F: FnMut(&T) -> bool,2420 {2421 SplitN::new(self.split(pred), n)2422 }2423 2424 /// Returns an iterator over mutable subslices separated by elements that match2425 /// `pred`, limited to returning at most `n` items. The matched element is2426 /// not contained in the subslices.2427 ///2428 /// The last element returned, if any, will contain the remainder of the2429 /// slice.2430 ///2431 /// # Examples2432 ///2433 /// ```2434 /// let mut v = [10, 40, 30, 20, 60, 50];2435 ///2436 /// for group in v.splitn_mut(2, |num| *num % 3 == 0) {2437 /// group[0] = 1;2438 /// }2439 /// assert_eq!(v, [1, 40, 30, 1, 60, 50]);2440 /// ```2441 #[stable(feature = "rust1", since = "1.0.0")]2442 #[inline]2443 pub fn splitn_mut<F>(&mut self, n: usize, pred: F) -> SplitNMut<'_, T, F>2444 where2445 F: FnMut(&T) -> bool,2446 {2447 SplitNMut::new(self.split_mut(pred), n)2448 }2449 2450 /// Returns an iterator over subslices separated by elements that match2451 /// `pred` limited to returning at most `n` items. This starts at the end of2452 /// the slice and works backwards. The matched element is not contained in2453 /// the subslices.2454 ///2455 /// The last element returned, if any, will contain the remainder of the2456 /// slice.2457 ///2458 /// # Examples2459 ///2460 /// Print the slice split once, starting from the end, by numbers divisible2461 /// by 3 (i.e., `[50]`, `[10, 40, 30, 20]`):2462 ///2463 /// ```2464 /// let v = [10, 40, 30, 20, 60, 50];2465 ///2466 /// for group in v.rsplitn(2, |num| *num % 3 == 0) {2467 /// println!("{group:?}");2468 /// }2469 /// ```2470 #[stable(feature = "rust1", since = "1.0.0")]2471 #[inline]2472 pub fn rsplitn<F>(&self, n: usize, pred: F) -> RSplitN<'_, T, F>2473 where2474 F: FnMut(&T) -> bool,2475 {2476 RSplitN::new(self.rsplit(pred), n)2477 }2478 2479 /// Returns an iterator over subslices separated by elements that match2480 /// `pred` limited to returning at most `n` items. This starts at the end of2481 /// the slice and works backwards. The matched element is not contained in2482 /// the subslices.2483 ///2484 /// The last element returned, if any, will contain the remainder of the2485 /// slice.2486 ///2487 /// # Examples2488 ///2489 /// ```2490 /// let mut s = [10, 40, 30, 20, 60, 50];2491 ///2492 /// for group in s.rsplitn_mut(2, |num| *num % 3 == 0) {2493 /// group[0] = 1;2494 /// }2495 /// assert_eq!(s, [1, 40, 30, 20, 60, 1]);2496 /// ```2497 #[stable(feature = "rust1", since = "1.0.0")]2498 #[inline]2499 pub fn rsplitn_mut<F>(&mut self, n: usize, pred: F) -> RSplitNMut<'_, T, F>2500 where2501 F: FnMut(&T) -> bool,2502 {2503 RSplitNMut::new(self.rsplit_mut(pred), n)2504 }2505 2506 /// Splits the slice on the first element that matches the specified2507 /// predicate.2508 ///2509 /// If any matching elements are present in the slice, returns the prefix2510 /// before the match and suffix after. The matching element itself is not2511 /// included. If no elements match, returns `None`.2512 ///2513 /// # Examples2514 ///2515 /// ```2516 /// #![feature(slice_split_once)]2517 /// let s = [1, 2, 3, 2, 4];2518 /// assert_eq!(s.split_once(|&x| x == 2), Some((2519 /// &[1][..],2520 /// &[3, 2, 4][..]2521 /// )));2522 /// assert_eq!(s.split_once(|&x| x == 0), None);2523 /// ```2524 #[unstable(feature = "slice_split_once", issue = "112811")]2525 #[inline]2526 pub fn split_once<F>(&self, pred: F) -> Option<(&[T], &[T])>2527 where2528 F: FnMut(&T) -> bool,2529 {2530 let index = self.iter().position(pred)?;2531 Some((&self[..index], &self[index + 1..]))2532 }2533 2534 /// Splits the slice on the last element that matches the specified2535 /// predicate.2536 ///2537 /// If any matching elements are present in the slice, returns the prefix2538 /// before the match and suffix after. The matching element itself is not2539 /// included. If no elements match, returns `None`.2540 ///2541 /// # Examples2542 ///2543 /// ```2544 /// #![feature(slice_split_once)]2545 /// let s = [1, 2, 3, 2, 4];2546 /// assert_eq!(s.rsplit_once(|&x| x == 2), Some((2547 /// &[1, 2, 3][..],2548 /// &[4][..]2549 /// )));2550 /// assert_eq!(s.rsplit_once(|&x| x == 0), None);2551 /// ```2552 #[unstable(feature = "slice_split_once", issue = "112811")]2553 #[inline]2554 pub fn rsplit_once<F>(&self, pred: F) -> Option<(&[T], &[T])>2555 where2556 F: FnMut(&T) -> bool,2557 {2558 let index = self.iter().rposition(pred)?;2559 Some((&self[..index], &self[index + 1..]))2560 }2561 2562 /// Returns `true` if the slice contains an element with the given value.2563 ///2564 /// This operation is *O*(*n*).2565 ///2566 /// Note that if you have a sorted slice, [`binary_search`] may be faster.2567 ///2568 /// [`binary_search`]: slice::binary_search2569 ///2570 /// # Examples2571 ///2572 /// ```2573 /// let v = [10, 40, 30];2574 /// assert!(v.contains(&30));2575 /// assert!(!v.contains(&50));2576 /// ```2577 ///2578 /// If you do not have a `&T`, but some other value that you can compare2579 /// with one (for example, `String` implements `PartialEq<str>`), you can2580 /// use `iter().any`:2581 ///2582 /// ```2583 /// let v = [String::from("hello"), String::from("world")]; // slice of `String`2584 /// assert!(v.iter().any(|e| e == "hello")); // search with `&str`2585 /// assert!(!v.iter().any(|e| e == "hi"));2586 /// ```2587 #[stable(feature = "rust1", since = "1.0.0")]2588 #[inline]2589 #[must_use]2590 pub fn contains(&self, x: &T) -> bool2591 where2592 T: PartialEq,2593 {2594 cmp::SliceContains::slice_contains(x, self)2595 }2596 2597 /// Returns `true` if `needle` is a prefix of the slice or equal to the slice.2598 ///2599 /// # Examples2600 ///2601 /// ```2602 /// let v = [10, 40, 30];2603 /// assert!(v.starts_with(&[10]));2604 /// assert!(v.starts_with(&[10, 40]));2605 /// assert!(v.starts_with(&v));2606 /// assert!(!v.starts_with(&[50]));2607 /// assert!(!v.starts_with(&[10, 50]));2608 /// ```2609 ///2610 /// Always returns `true` if `needle` is an empty slice:2611 ///2612 /// ```2613 /// let v = &[10, 40, 30];2614 /// assert!(v.starts_with(&[]));2615 /// let v: &[u8] = &[];2616 /// assert!(v.starts_with(&[]));2617 /// ```2618 #[stable(feature = "rust1", since = "1.0.0")]2619 #[must_use]2620 pub fn starts_with(&self, needle: &[T]) -> bool2621 where2622 T: PartialEq,2623 {2624 let n = needle.len();2625 self.len() >= n && needle == &self[..n]2626 }2627 2628 /// Returns `true` if `needle` is a suffix of the slice or equal to the slice.2629 ///2630 /// # Examples2631 ///2632 /// ```2633 /// let v = [10, 40, 30];2634 /// assert!(v.ends_with(&[30]));2635 /// assert!(v.ends_with(&[40, 30]));2636 /// assert!(v.ends_with(&v));2637 /// assert!(!v.ends_with(&[50]));2638 /// assert!(!v.ends_with(&[50, 30]));2639 /// ```2640 ///2641 /// Always returns `true` if `needle` is an empty slice:2642 ///2643 /// ```2644 /// let v = &[10, 40, 30];2645 /// assert!(v.ends_with(&[]));2646 /// let v: &[u8] = &[];2647 /// assert!(v.ends_with(&[]));2648 /// ```2649 #[stable(feature = "rust1", since = "1.0.0")]2650 #[must_use]2651 pub fn ends_with(&self, needle: &[T]) -> bool2652 where2653 T: PartialEq,2654 {2655 let (m, n) = (self.len(), needle.len());2656 m >= n && needle == &self[m - n..]2657 }2658 2659 /// Returns a subslice with the prefix removed.2660 ///2661 /// If the slice starts with `prefix`, returns the subslice after the prefix, wrapped in `Some`.2662 /// If `prefix` is empty, simply returns the original slice. If `prefix` is equal to the2663 /// original slice, returns an empty slice.2664 ///2665 /// If the slice does not start with `prefix`, returns `None`.2666 ///2667 /// # Examples2668 ///2669 /// ```2670 /// let v = &[10, 40, 30];2671 /// assert_eq!(v.strip_prefix(&[10]), Some(&[40, 30][..]));2672 /// assert_eq!(v.strip_prefix(&[10, 40]), Some(&[30][..]));2673 /// assert_eq!(v.strip_prefix(&[10, 40, 30]), Some(&[][..]));2674 /// assert_eq!(v.strip_prefix(&[50]), None);2675 /// assert_eq!(v.strip_prefix(&[10, 50]), None);2676 ///2677 /// let prefix : &str = "he";2678 /// assert_eq!(b"hello".strip_prefix(prefix.as_bytes()),2679 /// Some(b"llo".as_ref()));2680 /// ```2681 #[must_use = "returns the subslice without modifying the original"]2682 #[stable(feature = "slice_strip", since = "1.51.0")]2683 pub fn strip_prefix<P: SlicePattern<Item = T> + ?Sized>(&self, prefix: &P) -> Option<&[T]>2684 where2685 T: PartialEq,2686 {2687 // This function will need rewriting if and when SlicePattern becomes more sophisticated.2688 let prefix = prefix.as_slice();2689 let n = prefix.len();2690 if n <= self.len() {2691 let (head, tail) = self.split_at(n);2692 if head == prefix {2693 return Some(tail);2694 }2695 }2696 None2697 }2698 2699 /// Returns a subslice with the suffix removed.2700 ///2701 /// If the slice ends with `suffix`, returns the subslice before the suffix, wrapped in `Some`.2702 /// If `suffix` is empty, simply returns the original slice. If `suffix` is equal to the2703 /// original slice, returns an empty slice.2704 ///2705 /// If the slice does not end with `suffix`, returns `None`.2706 ///2707 /// # Examples2708 ///2709 /// ```2710 /// let v = &[10, 40, 30];2711 /// assert_eq!(v.strip_suffix(&[30]), Some(&[10, 40][..]));2712 /// assert_eq!(v.strip_suffix(&[40, 30]), Some(&[10][..]));2713 /// assert_eq!(v.strip_suffix(&[10, 40, 30]), Some(&[][..]));2714 /// assert_eq!(v.strip_suffix(&[50]), None);2715 /// assert_eq!(v.strip_suffix(&[50, 30]), None);2716 /// ```2717 #[must_use = "returns the subslice without modifying the original"]2718 #[stable(feature = "slice_strip", since = "1.51.0")]2719 pub fn strip_suffix<P: SlicePattern<Item = T> + ?Sized>(&self, suffix: &P) -> Option<&[T]>2720 where2721 T: PartialEq,2722 {2723 // This function will need rewriting if and when SlicePattern becomes more sophisticated.2724 let suffix = suffix.as_slice();2725 let (len, n) = (self.len(), suffix.len());2726 if n <= len {2727 let (head, tail) = self.split_at(len - n);2728 if tail == suffix {2729 return Some(head);2730 }2731 }2732 None2733 }2734 2735 /// Returns a subslice with the prefix and suffix removed.2736 ///2737 /// If the slice starts with `prefix` and ends with `suffix`, returns the subslice after the2738 /// prefix and before the suffix, wrapped in `Some`.2739 ///2740 /// If the slice does not start with `prefix` or does not end with `suffix`, returns `None`.2741 ///2742 /// # Examples2743 ///2744 /// ```2745 /// #![feature(strip_circumfix)]2746 ///2747 /// let v = &[10, 50, 40, 30];2748 /// assert_eq!(v.strip_circumfix(&[10], &[30]), Some(&[50, 40][..]));2749 /// assert_eq!(v.strip_circumfix(&[10], &[40, 30]), Some(&[50][..]));2750 /// assert_eq!(v.strip_circumfix(&[10, 50], &[40, 30]), Some(&[][..]));2751 /// assert_eq!(v.strip_circumfix(&[50], &[30]), None);2752 /// assert_eq!(v.strip_circumfix(&[10], &[40]), None);2753 /// assert_eq!(v.strip_circumfix(&[], &[40, 30]), Some(&[10, 50][..]));2754 /// assert_eq!(v.strip_circumfix(&[10, 50], &[]), Some(&[40, 30][..]));2755 /// ```2756 #[must_use = "returns the subslice without modifying the original"]2757 #[unstable(feature = "strip_circumfix", issue = "147946")]2758 pub fn strip_circumfix<S, P>(&self, prefix: &P, suffix: &S) -> Option<&[T]>2759 where2760 T: PartialEq,2761 S: SlicePattern<Item = T> + ?Sized,2762 P: SlicePattern<Item = T> + ?Sized,2763 {2764 self.strip_prefix(prefix)?.strip_suffix(suffix)2765 }2766 2767 /// Returns a subslice with the optional prefix removed.2768 ///2769 /// If the slice starts with `prefix`, returns the subslice after the prefix. If `prefix`2770 /// is empty or the slice does not start with `prefix`, simply returns the original slice.2771 /// If `prefix` is equal to the original slice, returns an empty slice.2772 ///2773 /// # Examples2774 ///2775 /// ```2776 /// #![feature(trim_prefix_suffix)]2777 ///2778 /// let v = &[10, 40, 30];2779 ///2780 /// // Prefix present - removes it2781 /// assert_eq!(v.trim_prefix(&[10]), &[40, 30][..]);2782 /// assert_eq!(v.trim_prefix(&[10, 40]), &[30][..]);2783 /// assert_eq!(v.trim_prefix(&[10, 40, 30]), &[][..]);2784 ///2785 /// // Prefix absent - returns original slice2786 /// assert_eq!(v.trim_prefix(&[50]), &[10, 40, 30][..]);2787 /// assert_eq!(v.trim_prefix(&[10, 50]), &[10, 40, 30][..]);2788 ///2789 /// let prefix : &str = "he";2790 /// assert_eq!(b"hello".trim_prefix(prefix.as_bytes()), b"llo".as_ref());2791 /// ```2792 #[must_use = "returns the subslice without modifying the original"]2793 #[unstable(feature = "trim_prefix_suffix", issue = "142312")]2794 pub fn trim_prefix<P: SlicePattern<Item = T> + ?Sized>(&self, prefix: &P) -> &[T]2795 where2796 T: PartialEq,2797 {2798 // This function will need rewriting if and when SlicePattern becomes more sophisticated.2799 let prefix = prefix.as_slice();2800 let n = prefix.len();2801 if n <= self.len() {2802 let (head, tail) = self.split_at(n);2803 if head == prefix {2804 return tail;2805 }2806 }2807 self2808 }2809 2810 /// Returns a subslice with the optional suffix removed.2811 ///2812 /// If the slice ends with `suffix`, returns the subslice before the suffix. If `suffix`2813 /// is empty or the slice does not end with `suffix`, simply returns the original slice.2814 /// If `suffix` is equal to the original slice, returns an empty slice.2815 ///2816 /// # Examples2817 ///2818 /// ```2819 /// #![feature(trim_prefix_suffix)]2820 ///2821 /// let v = &[10, 40, 30];2822 ///2823 /// // Suffix present - removes it2824 /// assert_eq!(v.trim_suffix(&[30]), &[10, 40][..]);2825 /// assert_eq!(v.trim_suffix(&[40, 30]), &[10][..]);2826 /// assert_eq!(v.trim_suffix(&[10, 40, 30]), &[][..]);2827 ///2828 /// // Suffix absent - returns original slice2829 /// assert_eq!(v.trim_suffix(&[50]), &[10, 40, 30][..]);2830 /// assert_eq!(v.trim_suffix(&[50, 30]), &[10, 40, 30][..]);2831 /// ```2832 #[must_use = "returns the subslice without modifying the original"]2833 #[unstable(feature = "trim_prefix_suffix", issue = "142312")]2834 pub fn trim_suffix<P: SlicePattern<Item = T> + ?Sized>(&self, suffix: &P) -> &[T]2835 where2836 T: PartialEq,2837 {2838 // This function will need rewriting if and when SlicePattern becomes more sophisticated.2839 let suffix = suffix.as_slice();2840 let (len, n) = (self.len(), suffix.len());2841 if n <= len {2842 let (head, tail) = self.split_at(len - n);2843 if tail == suffix {2844 return head;2845 }2846 }2847 self2848 }2849 2850 /// Binary searches this slice for a given element.2851 /// If the slice is not sorted, the returned result is unspecified and2852 /// meaningless.2853 ///2854 /// If the value is found then [`Result::Ok`] is returned, containing the2855 /// index of the matching element. If there are multiple matches, then any2856 /// one of the matches could be returned. The index is chosen2857 /// deterministically, but is subject to change in future versions of Rust.2858 /// If the value is not found then [`Result::Err`] is returned, containing2859 /// the index where a matching element could be inserted while maintaining2860 /// sorted order.2861 ///2862 /// See also [`binary_search_by`], [`binary_search_by_key`], and [`partition_point`].2863 ///2864 /// [`binary_search_by`]: slice::binary_search_by2865 /// [`binary_search_by_key`]: slice::binary_search_by_key2866 /// [`partition_point`]: slice::partition_point2867 ///2868 /// # Examples2869 ///2870 /// Looks up a series of four elements. The first is found, with a2871 /// uniquely determined position; the second and third are not2872 /// found; the fourth could match any position in `[1, 4]`.2873 ///2874 /// ```2875 /// let s = [0, 1, 1, 1, 1, 2, 3, 5, 8, 13, 21, 34, 55];2876 ///2877 /// assert_eq!(s.binary_search(&13), Ok(9));2878 /// assert_eq!(s.binary_search(&4), Err(7));2879 /// assert_eq!(s.binary_search(&100), Err(13));2880 /// let r = s.binary_search(&1);2881 /// assert!(match r { Ok(1..=4) => true, _ => false, });2882 /// ```2883 ///2884 /// If you want to find that whole *range* of matching items, rather than2885 /// an arbitrary matching one, that can be done using [`partition_point`]:2886 /// ```2887 /// let s = [0, 1, 1, 1, 1, 2, 3, 5, 8, 13, 21, 34, 55];2888 ///2889 /// let low = s.partition_point(|x| x < &1);2890 /// assert_eq!(low, 1);2891 /// let high = s.partition_point(|x| x <= &1);2892 /// assert_eq!(high, 5);2893 /// let r = s.binary_search(&1);2894 /// assert!((low..high).contains(&r.unwrap()));2895 ///2896 /// assert!(s[..low].iter().all(|&x| x < 1));2897 /// assert!(s[low..high].iter().all(|&x| x == 1));2898 /// assert!(s[high..].iter().all(|&x| x > 1));2899 ///2900 /// // For something not found, the "range" of equal items is empty2901 /// assert_eq!(s.partition_point(|x| x < &11), 9);2902 /// assert_eq!(s.partition_point(|x| x <= &11), 9);2903 /// assert_eq!(s.binary_search(&11), Err(9));2904 /// ```2905 ///2906 /// If you want to insert an item to a sorted vector, while maintaining2907 /// sort order, consider using [`partition_point`]:2908 ///2909 /// ```2910 /// let mut s = vec![0, 1, 1, 1, 1, 2, 3, 5, 8, 13, 21, 34, 55];2911 /// let num = 42;2912 /// let idx = s.partition_point(|&x| x <= num);2913 /// // If `num` is unique, `s.partition_point(|&x| x < num)` (with `<`) is equivalent to2914 /// // `s.binary_search(&num).unwrap_or_else(|x| x)`, but using `<=` will allow `insert`2915 /// // to shift less elements.2916 /// s.insert(idx, num);2917 /// assert_eq!(s, [0, 1, 1, 1, 1, 2, 3, 5, 8, 13, 21, 34, 42, 55]);2918 /// ```2919 #[stable(feature = "rust1", since = "1.0.0")]2920 pub fn binary_search(&self, x: &T) -> Result<usize, usize>2921 where2922 T: Ord,2923 {2924 self.binary_search_by(|p| p.cmp(x))2925 }2926 2927 /// Binary searches this slice with a comparator function.2928 ///2929 /// The comparator function should return an order code that indicates2930 /// whether its argument is `Less`, `Equal` or `Greater` the desired2931 /// target.2932 /// If the slice is not sorted or if the comparator function does not2933 /// implement an order consistent with the sort order of the underlying2934 /// slice, the returned result is unspecified and meaningless.2935 ///2936 /// If the value is found then [`Result::Ok`] is returned, containing the2937 /// index of the matching element. If there are multiple matches, then any2938 /// one of the matches could be returned. The index is chosen2939 /// deterministically, but is subject to change in future versions of Rust.2940 /// If the value is not found then [`Result::Err`] is returned, containing2941 /// the index where a matching element could be inserted while maintaining2942 /// sorted order.2943 ///2944 /// See also [`binary_search`], [`binary_search_by_key`], and [`partition_point`].2945 ///2946 /// [`binary_search`]: slice::binary_search2947 /// [`binary_search_by_key`]: slice::binary_search_by_key2948 /// [`partition_point`]: slice::partition_point2949 ///2950 /// # Examples2951 ///2952 /// Looks up a series of four elements. The first is found, with a2953 /// uniquely determined position; the second and third are not2954 /// found; the fourth could match any position in `[1, 4]`.2955 ///2956 /// ```2957 /// let s = [0, 1, 1, 1, 1, 2, 3, 5, 8, 13, 21, 34, 55];2958 ///2959 /// let seek = 13;2960 /// assert_eq!(s.binary_search_by(|probe| probe.cmp(&seek)), Ok(9));2961 /// let seek = 4;2962 /// assert_eq!(s.binary_search_by(|probe| probe.cmp(&seek)), Err(7));2963 /// let seek = 100;2964 /// assert_eq!(s.binary_search_by(|probe| probe.cmp(&seek)), Err(13));2965 /// let seek = 1;2966 /// let r = s.binary_search_by(|probe| probe.cmp(&seek));2967 /// assert!(match r { Ok(1..=4) => true, _ => false, });2968 /// ```2969 #[stable(feature = "rust1", since = "1.0.0")]2970 #[inline]2971 pub fn binary_search_by<'a, F>(&'a self, mut f: F) -> Result<usize, usize>2972 where2973 F: FnMut(&'a T) -> Ordering,2974 {2975 let mut size = self.len();2976 if size == 0 {2977 return Err(0);2978 }2979 let mut base = 0usize;2980 2981 // This loop intentionally doesn't have an early exit if the comparison2982 // returns Equal. We want the number of loop iterations to depend *only*2983 // on the size of the input slice so that the CPU can reliably predict2984 // the loop count.2985 while size > 1 {2986 let half = size / 2;2987 let mid = base + half;2988 2989 // SAFETY: the call is made safe by the following invariants:2990 // - `mid >= 0`: by definition2991 // - `mid < size`: `mid = size / 2 + size / 4 + size / 8 ...`2992 let cmp = f(unsafe { self.get_unchecked(mid) });2993 2994 // Binary search interacts poorly with branch prediction, so force2995 // the compiler to use conditional moves if supported by the target2996 // architecture.2997 base = hint::select_unpredictable(cmp == Greater, base, mid);2998 2999 // This is imprecise in the case where `size` is odd and the3000 // comparison returns Greater: the mid element still gets included3001 // by `size` even though it's known to be larger than the element3002 // being searched for.3003 //3004 // This is fine though: we gain more performance by keeping the3005 // loop iteration count invariant (and thus predictable) than we3006 // lose from considering one additional element.3007 size -= half;3008 }3009 3010 // SAFETY: base is always in [0, size) because base <= mid.3011 let cmp = f(unsafe { self.get_unchecked(base) });3012 if cmp == Equal {3013 // SAFETY: same as the `get_unchecked` above.3014 unsafe { hint::assert_unchecked(base < self.len()) };3015 Ok(base)3016 } else {3017 let result = base + (cmp == Less) as usize;3018 // SAFETY: same as the `get_unchecked` above.3019 // Note that this is `<=`, unlike the assume in the `Ok` path.3020 unsafe { hint::assert_unchecked(result <= self.len()) };3021 Err(result)3022 }3023 }3024 3025 /// Binary searches this slice with a key extraction function.3026 ///3027 /// Assumes that the slice is sorted by the key, for instance with3028 /// [`sort_by_key`] using the same key extraction function.3029 /// If the slice is not sorted by the key, the returned result is3030 /// unspecified and meaningless.3031 ///3032 /// If the value is found then [`Result::Ok`] is returned, containing the3033 /// index of the matching element. If there are multiple matches, then any3034 /// one of the matches could be returned. The index is chosen3035 /// deterministically, but is subject to change in future versions of Rust.3036 /// If the value is not found then [`Result::Err`] is returned, containing3037 /// the index where a matching element could be inserted while maintaining3038 /// sorted order.3039 ///3040 /// See also [`binary_search`], [`binary_search_by`], and [`partition_point`].3041 ///3042 /// [`sort_by_key`]: slice::sort_by_key3043 /// [`binary_search`]: slice::binary_search3044 /// [`binary_search_by`]: slice::binary_search_by3045 /// [`partition_point`]: slice::partition_point3046 ///3047 /// # Examples3048 ///3049 /// Looks up a series of four elements in a slice of pairs sorted by3050 /// their second elements. The first is found, with a uniquely3051 /// determined position; the second and third are not found; the3052 /// fourth could match any position in `[1, 4]`.3053 ///3054 /// ```3055 /// let s = [(0, 0), (2, 1), (4, 1), (5, 1), (3, 1),3056 /// (1, 2), (2, 3), (4, 5), (5, 8), (3, 13),3057 /// (1, 21), (2, 34), (4, 55)];3058 ///3059 /// assert_eq!(s.binary_search_by_key(&13, |&(a, b)| b), Ok(9));3060 /// assert_eq!(s.binary_search_by_key(&4, |&(a, b)| b), Err(7));3061 /// assert_eq!(s.binary_search_by_key(&100, |&(a, b)| b), Err(13));3062 /// let r = s.binary_search_by_key(&1, |&(a, b)| b);3063 /// assert!(match r { Ok(1..=4) => true, _ => false, });3064 /// ```3065 // Lint rustdoc::broken_intra_doc_links is allowed as `slice::sort_by_key` is3066 // in crate `alloc`, and as such doesn't exists yet when building `core`: #74481.3067 // This breaks links when slice is displayed in core, but changing it to use relative links3068 // would break when the item is re-exported. So allow the core links to be broken for now.3069 #[allow(rustdoc::broken_intra_doc_links)]3070 #[stable(feature = "slice_binary_search_by_key", since = "1.10.0")]3071 #[inline]3072 pub fn binary_search_by_key<'a, B, F>(&'a self, b: &B, mut f: F) -> Result<usize, usize>3073 where3074 F: FnMut(&'a T) -> B,3075 B: Ord,3076 {3077 self.binary_search_by(|k| f(k).cmp(b))3078 }3079 3080 /// Sorts the slice in ascending order **without** preserving the initial order of equal elements.3081 ///3082 /// This sort is unstable (i.e., may reorder equal elements), in-place (i.e., does not3083 /// allocate), and *O*(*n* \* log(*n*)) worst-case.3084 ///3085 /// If the implementation of [`Ord`] for `T` does not implement a [total order], the function3086 /// may panic; even if the function exits normally, the resulting order of elements in the slice3087 /// is unspecified. See also the note on panicking below.3088 ///3089 /// For example `|a, b| (a - b).cmp(a)` is a comparison function that is neither transitive nor3090 /// reflexive nor total, `a < b < c < a` with `a = 1, b = 2, c = 3`. For more information and3091 /// examples see the [`Ord`] documentation.3092 ///3093 ///3094 /// All original elements will remain in the slice and any possible modifications via interior3095 /// mutability are observed in the input. Same is true if the implementation of [`Ord`] for `T` panics.3096 ///3097 /// Sorting types that only implement [`PartialOrd`] such as [`f32`] and [`f64`] require3098 /// additional precautions. For example, `f32::NAN != f32::NAN`, which doesn't fulfill the3099 /// reflexivity requirement of [`Ord`]. By using an alternative comparison function with3100 /// `slice::sort_unstable_by` such as [`f32::total_cmp`] or [`f64::total_cmp`] that defines a3101 /// [total order] users can sort slices containing floating-point values. Alternatively, if all3102 /// values in the slice are guaranteed to be in a subset for which [`PartialOrd::partial_cmp`]3103 /// forms a [total order], it's possible to sort the slice with `sort_unstable_by(|a, b|3104 /// a.partial_cmp(b).unwrap())`.3105 ///3106 /// # Current implementation3107 ///3108 /// The current implementation is based on [ipnsort] by Lukas Bergdoll and Orson Peters, which3109 /// combines the fast average case of quicksort with the fast worst case of heapsort, achieving3110 /// linear time on fully sorted and reversed inputs. On inputs with k distinct elements, the3111 /// expected time to sort the data is *O*(*n* \* log(*k*)).3112 ///3113 /// It is typically faster than stable sorting, except in a few special cases, e.g., when the3114 /// slice is partially sorted.3115 ///3116 /// # Panics3117 ///3118 /// May panic if the implementation of [`Ord`] for `T` does not implement a [total order], or if3119 /// the [`Ord`] implementation panics.3120 ///3121 /// # Examples3122 ///3123 /// ```3124 /// let mut v = [4, -5, 1, -3, 2];3125 ///3126 /// v.sort_unstable();3127 /// assert_eq!(v, [-5, -3, 1, 2, 4]);3128 /// ```3129 ///3130 /// [ipnsort]: https://github.com/Voultapher/sort-research-rs/tree/main/ipnsort3131 /// [total order]: https://en.wikipedia.org/wiki/Total_order3132 #[stable(feature = "sort_unstable", since = "1.20.0")]3133 #[inline]3134 pub fn sort_unstable(&mut self)3135 where3136 T: Ord,3137 {3138 sort::unstable::sort(self, &mut T::lt);3139 }3140 3141 /// Sorts the slice in ascending order with a comparison function, **without** preserving the3142 /// initial order of equal elements.3143 ///3144 /// This sort is unstable (i.e., may reorder equal elements), in-place (i.e., does not3145 /// allocate), and *O*(*n* \* log(*n*)) worst-case.3146 ///3147 /// If the comparison function `compare` does not implement a [total order], the function3148 /// may panic; even if the function exits normally, the resulting order of elements in the slice3149 /// is unspecified. See also the note on panicking below.3150 ///3151 /// For example `|a, b| (a - b).cmp(a)` is a comparison function that is neither transitive nor3152 /// reflexive nor total, `a < b < c < a` with `a = 1, b = 2, c = 3`. For more information and3153 /// examples see the [`Ord`] documentation.3154 ///3155 /// All original elements will remain in the slice and any possible modifications via interior3156 /// mutability are observed in the input. Same is true if `compare` panics.3157 ///3158 /// # Current implementation3159 ///3160 /// The current implementation is based on [ipnsort] by Lukas Bergdoll and Orson Peters, which3161 /// combines the fast average case of quicksort with the fast worst case of heapsort, achieving3162 /// linear time on fully sorted and reversed inputs. On inputs with k distinct elements, the3163 /// expected time to sort the data is *O*(*n* \* log(*k*)).3164 ///3165 /// It is typically faster than stable sorting, except in a few special cases, e.g., when the3166 /// slice is partially sorted.3167 ///3168 /// # Panics3169 ///3170 /// May panic if the `compare` does not implement a [total order], or if3171 /// the `compare` itself panics.3172 ///3173 /// # Examples3174 ///3175 /// ```3176 /// let mut v = [4, -5, 1, -3, 2];3177 /// v.sort_unstable_by(|a, b| a.cmp(b));3178 /// assert_eq!(v, [-5, -3, 1, 2, 4]);3179 ///3180 /// // reverse sorting3181 /// v.sort_unstable_by(|a, b| b.cmp(a));3182 /// assert_eq!(v, [4, 2, 1, -3, -5]);3183 /// ```3184 ///3185 /// [ipnsort]: https://github.com/Voultapher/sort-research-rs/tree/main/ipnsort3186 /// [total order]: https://en.wikipedia.org/wiki/Total_order3187 #[stable(feature = "sort_unstable", since = "1.20.0")]3188 #[inline]3189 pub fn sort_unstable_by<F>(&mut self, mut compare: F)3190 where3191 F: FnMut(&T, &T) -> Ordering,3192 {3193 sort::unstable::sort(self, &mut |a, b| compare(a, b) == Ordering::Less);3194 }3195 3196 /// Sorts the slice in ascending order with a key extraction function, **without** preserving3197 /// the initial order of equal elements.3198 ///3199 /// This sort is unstable (i.e., may reorder equal elements), in-place (i.e., does not3200 /// allocate), and *O*(*n* \* log(*n*)) worst-case.3201 ///3202 /// If the implementation of [`Ord`] for `K` does not implement a [total order], the function3203 /// may panic; even if the function exits normally, the resulting order of elements in the slice3204 /// is unspecified. See also the note on panicking below.3205 ///3206 /// For example `|a, b| (a - b).cmp(a)` is a comparison function that is neither transitive nor3207 /// reflexive nor total, `a < b < c < a` with `a = 1, b = 2, c = 3`. For more information and3208 /// examples see the [`Ord`] documentation.3209 ///3210 /// All original elements will remain in the slice and any possible modifications via interior3211 /// mutability are observed in the input. Same is true if the implementation of [`Ord`] for `K` panics.3212 ///3213 /// # Current implementation3214 ///3215 /// The current implementation is based on [ipnsort] by Lukas Bergdoll and Orson Peters, which3216 /// combines the fast average case of quicksort with the fast worst case of heapsort, achieving3217 /// linear time on fully sorted and reversed inputs. On inputs with k distinct elements, the3218 /// expected time to sort the data is *O*(*n* \* log(*k*)).3219 ///3220 /// It is typically faster than stable sorting, except in a few special cases, e.g., when the3221 /// slice is partially sorted.3222 ///3223 /// # Panics3224 ///3225 /// May panic if the implementation of [`Ord`] for `K` does not implement a [total order], or if3226 /// the [`Ord`] implementation panics.3227 ///3228 /// # Examples3229 ///3230 /// ```3231 /// let mut v = [4i32, -5, 1, -3, 2];3232 ///3233 /// v.sort_unstable_by_key(|k| k.abs());3234 /// assert_eq!(v, [1, 2, -3, 4, -5]);3235 /// ```3236 ///3237 /// [ipnsort]: https://github.com/Voultapher/sort-research-rs/tree/main/ipnsort3238 /// [total order]: https://en.wikipedia.org/wiki/Total_order3239 #[stable(feature = "sort_unstable", since = "1.20.0")]3240 #[inline]3241 pub fn sort_unstable_by_key<K, F>(&mut self, mut f: F)3242 where3243 F: FnMut(&T) -> K,3244 K: Ord,3245 {3246 sort::unstable::sort(self, &mut |a, b| f(a).lt(&f(b)));3247 }3248 3249 /// Partially sorts the slice in ascending order **without** preserving the initial order of equal elements.3250 ///3251 /// Upon completion, for the specified range `start..end`, it's guaranteed that:3252 ///3253 /// 1. Every element in `self[..start]` is smaller than or equal to3254 /// 2. Every element in `self[start..end]`, which is sorted, and smaller than or equal to3255 /// 3. Every element in `self[end..]`.3256 ///3257 /// This partial sort is unstable, meaning it may reorder equal elements in the specified range.3258 /// It may reorder elements outside the specified range as well, but the guarantees above still hold.3259 ///3260 /// This partial sort is in-place (i.e., does not allocate), and *O*(*n* + *k* \* log(*k*)) worst-case,3261 /// where *n* is the length of the slice and *k* is the length of the specified range.3262 ///3263 /// See the documentation of [`sort_unstable`] for implementation notes.3264 ///3265 /// # Panics3266 ///3267 /// May panic if the implementation of [`Ord`] for `T` does not implement a total order, or if3268 /// the [`Ord`] implementation panics, or if the specified range is out of bounds.3269 ///3270 /// # Examples3271 ///3272 /// ```3273 /// #![feature(slice_partial_sort_unstable)]3274 ///3275 /// let mut v = [4, -5, 1, -3, 2];3276 ///3277 /// // empty range at the beginning, nothing changed3278 /// v.partial_sort_unstable(0..0);3279 /// assert_eq!(v, [4, -5, 1, -3, 2]);3280 ///3281 /// // empty range in the middle, partitioning the slice3282 /// v.partial_sort_unstable(2..2);3283 /// for i in 0..2 {3284 /// assert!(v[i] <= v[2]);3285 /// }3286 /// for i in 3..v.len() {3287 /// assert!(v[2] <= v[i]);3288 /// }3289 ///3290 /// // single element range, same as select_nth_unstable3291 /// v.partial_sort_unstable(2..3);3292 /// for i in 0..2 {3293 /// assert!(v[i] <= v[2]);3294 /// }3295 /// for i in 3..v.len() {3296 /// assert!(v[2] <= v[i]);3297 /// }3298 ///3299 /// // partial sort a subrange3300 /// v.partial_sort_unstable(1..4);3301 /// assert_eq!(&v[1..4], [-3, 1, 2]);3302 ///3303 /// // partial sort the whole range, same as sort_unstable3304 /// v.partial_sort_unstable(..);3305 /// assert_eq!(v, [-5, -3, 1, 2, 4]);3306 /// ```3307 ///3308 /// [`sort_unstable`]: slice::sort_unstable3309 #[unstable(feature = "slice_partial_sort_unstable", issue = "149046")]3310 #[inline]3311 pub fn partial_sort_unstable<R>(&mut self, range: R)3312 where3313 T: Ord,3314 R: RangeBounds<usize>,3315 {3316 sort::unstable::partial_sort(self, range, T::lt);3317 }3318 3319 /// Partially sorts the slice in ascending order with a comparison function, **without**3320 /// preserving the initial order of equal elements.3321 ///3322 /// Upon completion, for the specified range `start..end`, it's guaranteed that:3323 ///3324 /// 1. Every element in `self[..start]` is smaller than or equal to3325 /// 2. Every element in `self[start..end]`, which is sorted, and smaller than or equal to3326 /// 3. Every element in `self[end..]`.3327 ///3328 /// This partial sort is unstable, meaning it may reorder equal elements in the specified range.3329 /// It may reorder elements outside the specified range as well, but the guarantees above still hold.3330 ///3331 /// This partial sort is in-place (i.e., does not allocate), and *O*(*n* + *k* \* log(*k*)) worst-case,3332 /// where *n* is the length of the slice and *k* is the length of the specified range.3333 ///3334 /// See the documentation of [`sort_unstable_by`] for implementation notes.3335 ///3336 /// # Panics3337 ///3338 /// May panic if the `compare` does not implement a total order, or if3339 /// the `compare` itself panics, or if the specified range is out of bounds.3340 ///3341 /// # Examples3342 ///3343 /// ```3344 /// #![feature(slice_partial_sort_unstable)]3345 ///3346 /// let mut v = [4, -5, 1, -3, 2];3347 ///3348 /// // empty range at the beginning, nothing changed3349 /// v.partial_sort_unstable_by(0..0, |a, b| b.cmp(a));3350 /// assert_eq!(v, [4, -5, 1, -3, 2]);3351 ///3352 /// // empty range in the middle, partitioning the slice3353 /// v.partial_sort_unstable_by(2..2, |a, b| b.cmp(a));3354 /// for i in 0..2 {3355 /// assert!(v[i] >= v[2]);3356 /// }3357 /// for i in 3..v.len() {3358 /// assert!(v[2] >= v[i]);3359 /// }3360 ///3361 /// // single element range, same as select_nth_unstable3362 /// v.partial_sort_unstable_by(2..3, |a, b| b.cmp(a));3363 /// for i in 0..2 {3364 /// assert!(v[i] >= v[2]);3365 /// }3366 /// for i in 3..v.len() {3367 /// assert!(v[2] >= v[i]);3368 /// }3369 ///3370 /// // partial sort a subrange3371 /// v.partial_sort_unstable_by(1..4, |a, b| b.cmp(a));3372 /// assert_eq!(&v[1..4], [2, 1, -3]);3373 ///3374 /// // partial sort the whole range, same as sort_unstable3375 /// v.partial_sort_unstable_by(.., |a, b| b.cmp(a));3376 /// assert_eq!(v, [4, 2, 1, -3, -5]);3377 /// ```3378 ///3379 /// [`sort_unstable_by`]: slice::sort_unstable_by3380 #[unstable(feature = "slice_partial_sort_unstable", issue = "149046")]3381 #[inline]3382 pub fn partial_sort_unstable_by<F, R>(&mut self, range: R, mut compare: F)3383 where3384 F: FnMut(&T, &T) -> Ordering,3385 R: RangeBounds<usize>,3386 {3387 sort::unstable::partial_sort(self, range, |a, b| compare(a, b) == Less);3388 }3389 3390 /// Partially sorts the slice in ascending order with a key extraction function, **without**3391 /// preserving the initial order of equal elements.3392 ///3393 /// Upon completion, for the specified range `start..end`, it's guaranteed that:3394 ///3395 /// 1. Every element in `self[..start]` is smaller than or equal to3396 /// 2. Every element in `self[start..end]`, which is sorted, and smaller than or equal to3397 /// 3. Every element in `self[end..]`.3398 ///3399 /// This partial sort is unstable, meaning it may reorder equal elements in the specified range.3400 /// It may reorder elements outside the specified range as well, but the guarantees above still hold.3401 ///3402 /// This partial sort is in-place (i.e., does not allocate), and *O*(*n* + *k* \* log(*k*)) worst-case,3403 /// where *n* is the length of the slice and *k* is the length of the specified range.3404 ///3405 /// See the documentation of [`sort_unstable_by_key`] for implementation notes.3406 ///3407 /// # Panics3408 ///3409 /// May panic if the implementation of [`Ord`] for `K` does not implement a total order, or if3410 /// the [`Ord`] implementation panics, or if the specified range is out of bounds.3411 ///3412 /// # Examples3413 ///3414 /// ```3415 /// #![feature(slice_partial_sort_unstable)]3416 ///3417 /// let mut v = [4i32, -5, 1, -3, 2];3418 ///3419 /// // empty range at the beginning, nothing changed3420 /// v.partial_sort_unstable_by_key(0..0, |k| k.abs());3421 /// assert_eq!(v, [4, -5, 1, -3, 2]);3422 ///3423 /// // empty range in the middle, partitioning the slice3424 /// v.partial_sort_unstable_by_key(2..2, |k| k.abs());3425 /// for i in 0..2 {3426 /// assert!(v[i].abs() <= v[2].abs());3427 /// }3428 /// for i in 3..v.len() {3429 /// assert!(v[2].abs() <= v[i].abs());3430 /// }3431 ///3432 /// // single element range, same as select_nth_unstable3433 /// v.partial_sort_unstable_by_key(2..3, |k| k.abs());3434 /// for i in 0..2 {3435 /// assert!(v[i].abs() <= v[2].abs());3436 /// }3437 /// for i in 3..v.len() {3438 /// assert!(v[2].abs() <= v[i].abs());3439 /// }3440 ///3441 /// // partial sort a subrange3442 /// v.partial_sort_unstable_by_key(1..4, |k| k.abs());3443 /// assert_eq!(&v[1..4], [2, -3, 4]);3444 ///3445 /// // partial sort the whole range, same as sort_unstable3446 /// v.partial_sort_unstable_by_key(.., |k| k.abs());3447 /// assert_eq!(v, [1, 2, -3, 4, -5]);3448 /// ```3449 ///3450 /// [`sort_unstable_by_key`]: slice::sort_unstable_by_key3451 #[unstable(feature = "slice_partial_sort_unstable", issue = "149046")]3452 #[inline]3453 pub fn partial_sort_unstable_by_key<K, F, R>(&mut self, range: R, mut f: F)3454 where3455 F: FnMut(&T) -> K,3456 K: Ord,3457 R: RangeBounds<usize>,3458 {3459 sort::unstable::partial_sort(self, range, |a, b| f(a).lt(&f(b)));3460 }3461 3462 /// Reorders the slice such that the element at `index` is at a sort-order position. All3463 /// elements before `index` will be `<=` to this value, and all elements after will be `>=` to3464 /// it.3465 ///3466 /// This reordering is unstable (i.e. any element that compares equal to the nth element may end3467 /// up at that position), in-place (i.e. does not allocate), and runs in *O*(*n*) time. This3468 /// function is also known as "kth element" in other libraries.3469 ///3470 /// Returns a triple that partitions the reordered slice:3471 ///3472 /// * The unsorted subslice before `index`, whose elements all satisfy `x <= self[index]`.3473 ///3474 /// * The element at `index`.3475 ///3476 /// * The unsorted subslice after `index`, whose elements all satisfy `x >= self[index]`.3477 ///3478 /// # Current implementation3479 ///3480 /// The current algorithm is an introselect implementation based on [ipnsort] by Lukas Bergdoll3481 /// and Orson Peters, which is also the basis for [`sort_unstable`]. The fallback algorithm is3482 /// Median of Medians using Tukey's Ninther for pivot selection, which guarantees linear runtime3483 /// for all inputs.3484 ///3485 /// [`sort_unstable`]: slice::sort_unstable3486 ///3487 /// # Panics3488 ///3489 /// Panics when `index >= len()`, and so always panics on empty slices.3490 ///3491 /// May panic if the implementation of [`Ord`] for `T` does not implement a [total order].3492 ///3493 /// # Examples3494 ///3495 /// ```3496 /// let mut v = [-5i32, 4, 2, -3, 1];3497 ///3498 /// // Find the items `<=` to the median, the median itself, and the items `>=` to it.3499 /// let (lesser, median, greater) = v.select_nth_unstable(2);3500 ///3501 /// assert!(lesser == [-3, -5] || lesser == [-5, -3]);3502 /// assert_eq!(median, &mut 1);3503 /// assert!(greater == [4, 2] || greater == [2, 4]);3504 ///3505 /// // We are only guaranteed the slice will be one of the following, based on the way we sort3506 /// // about the specified index.3507 /// assert!(v == [-3, -5, 1, 2, 4] ||3508 /// v == [-5, -3, 1, 2, 4] ||3509 /// v == [-3, -5, 1, 4, 2] ||3510 /// v == [-5, -3, 1, 4, 2]);3511 /// ```3512 ///3513 /// [ipnsort]: https://github.com/Voultapher/sort-research-rs/tree/main/ipnsort3514 /// [total order]: https://en.wikipedia.org/wiki/Total_order3515 #[stable(feature = "slice_select_nth_unstable", since = "1.49.0")]3516 #[inline]3517 pub fn select_nth_unstable(&mut self, index: usize) -> (&mut [T], &mut T, &mut [T])3518 where3519 T: Ord,3520 {3521 sort::select::partition_at_index(self, index, T::lt)3522 }3523 3524 /// Reorders the slice with a comparator function such that the element at `index` is at a3525 /// sort-order position. All elements before `index` will be `<=` to this value, and all3526 /// elements after will be `>=` to it, according to the comparator function.3527 ///3528 /// This reordering is unstable (i.e. any element that compares equal to the nth element may end3529 /// up at that position), in-place (i.e. does not allocate), and runs in *O*(*n*) time. This3530 /// function is also known as "kth element" in other libraries.3531 ///3532 /// Returns a triple partitioning the reordered slice:3533 ///3534 /// * The unsorted subslice before `index`, whose elements all satisfy3535 /// `compare(x, self[index]).is_le()`.3536 ///3537 /// * The element at `index`.3538 ///3539 /// * The unsorted subslice after `index`, whose elements all satisfy3540 /// `compare(x, self[index]).is_ge()`.3541 ///3542 /// # Current implementation3543 ///3544 /// The current algorithm is an introselect implementation based on [ipnsort] by Lukas Bergdoll3545 /// and Orson Peters, which is also the basis for [`sort_unstable`]. The fallback algorithm is3546 /// Median of Medians using Tukey's Ninther for pivot selection, which guarantees linear runtime3547 /// for all inputs.3548 ///3549 /// [`sort_unstable`]: slice::sort_unstable3550 ///3551 /// # Panics3552 ///3553 /// Panics when `index >= len()`, and so always panics on empty slices.3554 ///3555 /// May panic if `compare` does not implement a [total order].3556 ///3557 /// # Examples3558 ///3559 /// ```3560 /// let mut v = [-5i32, 4, 2, -3, 1];3561 ///3562 /// // Find the items `>=` to the median, the median itself, and the items `<=` to it, by using3563 /// // a reversed comparator.3564 /// let (before, median, after) = v.select_nth_unstable_by(2, |a, b| b.cmp(a));3565 ///3566 /// assert!(before == [4, 2] || before == [2, 4]);3567 /// assert_eq!(median, &mut 1);3568 /// assert!(after == [-3, -5] || after == [-5, -3]);3569 ///3570 /// // We are only guaranteed the slice will be one of the following, based on the way we sort3571 /// // about the specified index.3572 /// assert!(v == [2, 4, 1, -5, -3] ||3573 /// v == [2, 4, 1, -3, -5] ||3574 /// v == [4, 2, 1, -5, -3] ||3575 /// v == [4, 2, 1, -3, -5]);3576 /// ```3577 ///3578 /// [ipnsort]: https://github.com/Voultapher/sort-research-rs/tree/main/ipnsort3579 /// [total order]: https://en.wikipedia.org/wiki/Total_order3580 #[stable(feature = "slice_select_nth_unstable", since = "1.49.0")]3581 #[inline]3582 pub fn select_nth_unstable_by<F>(3583 &mut self,3584 index: usize,3585 mut compare: F,3586 ) -> (&mut [T], &mut T, &mut [T])3587 where3588 F: FnMut(&T, &T) -> Ordering,3589 {3590 sort::select::partition_at_index(self, index, |a: &T, b: &T| compare(a, b) == Less)3591 }3592 3593 /// Reorders the slice with a key extraction function such that the element at `index` is at a3594 /// sort-order position. All elements before `index` will have keys `<=` to the key at `index`,3595 /// and all elements after will have keys `>=` to it.3596 ///3597 /// This reordering is unstable (i.e. any element that compares equal to the nth element may end3598 /// up at that position), in-place (i.e. does not allocate), and runs in *O*(*n*) time. This3599 /// function is also known as "kth element" in other libraries.3600 ///3601 /// Returns a triple partitioning the reordered slice:3602 ///3603 /// * The unsorted subslice before `index`, whose elements all satisfy `f(x) <= f(self[index])`.3604 ///3605 /// * The element at `index`.3606 ///3607 /// * The unsorted subslice after `index`, whose elements all satisfy `f(x) >= f(self[index])`.3608 ///3609 /// # Current implementation3610 ///3611 /// The current algorithm is an introselect implementation based on [ipnsort] by Lukas Bergdoll3612 /// and Orson Peters, which is also the basis for [`sort_unstable`]. The fallback algorithm is3613 /// Median of Medians using Tukey's Ninther for pivot selection, which guarantees linear runtime3614 /// for all inputs.3615 ///3616 /// [`sort_unstable`]: slice::sort_unstable3617 ///3618 /// # Panics3619 ///3620 /// Panics when `index >= len()`, meaning it always panics on empty slices.3621 ///3622 /// May panic if `K: Ord` does not implement a total order.3623 ///3624 /// # Examples3625 ///3626 /// ```3627 /// let mut v = [-5i32, 4, 1, -3, 2];3628 ///3629 /// // Find the items `<=` to the absolute median, the absolute median itself, and the items3630 /// // `>=` to it.3631 /// let (lesser, median, greater) = v.select_nth_unstable_by_key(2, |a| a.abs());3632 ///3633 /// assert!(lesser == [1, 2] || lesser == [2, 1]);3634 /// assert_eq!(median, &mut -3);3635 /// assert!(greater == [4, -5] || greater == [-5, 4]);3636 ///3637 /// // We are only guaranteed the slice will be one of the following, based on the way we sort3638 /// // about the specified index.3639 /// assert!(v == [1, 2, -3, 4, -5] ||3640 /// v == [1, 2, -3, -5, 4] ||3641 /// v == [2, 1, -3, 4, -5] ||3642 /// v == [2, 1, -3, -5, 4]);3643 /// ```3644 ///3645 /// [ipnsort]: https://github.com/Voultapher/sort-research-rs/tree/main/ipnsort3646 /// [total order]: https://en.wikipedia.org/wiki/Total_order3647 #[stable(feature = "slice_select_nth_unstable", since = "1.49.0")]3648 #[inline]3649 pub fn select_nth_unstable_by_key<K, F>(3650 &mut self,3651 index: usize,3652 mut f: F,3653 ) -> (&mut [T], &mut T, &mut [T])3654 where3655 F: FnMut(&T) -> K,3656 K: Ord,3657 {3658 sort::select::partition_at_index(self, index, |a: &T, b: &T| f(a).lt(&f(b)))3659 }3660 3661 /// Moves all consecutive repeated elements to the end of the slice according to the3662 /// [`PartialEq`] trait implementation.3663 ///3664 /// Returns two slices. The first contains no consecutive repeated elements.3665 /// The second contains all the duplicates in no specified order.3666 ///3667 /// If the slice is sorted, the first returned slice contains no duplicates.3668 ///3669 /// # Examples3670 ///3671 /// ```3672 /// #![feature(slice_partition_dedup)]3673 ///3674 /// let mut slice = [1, 2, 2, 3, 3, 2, 1, 1];3675 ///3676 /// let (dedup, duplicates) = slice.partition_dedup();3677 ///3678 /// assert_eq!(dedup, [1, 2, 3, 2, 1]);3679 /// assert_eq!(duplicates, [2, 3, 1]);3680 /// ```3681 #[unstable(feature = "slice_partition_dedup", issue = "54279")]3682 #[inline]3683 pub fn partition_dedup(&mut self) -> (&mut [T], &mut [T])3684 where3685 T: PartialEq,3686 {3687 self.partition_dedup_by(|a, b| a == b)3688 }3689 3690 /// Moves all but the first of consecutive elements to the end of the slice satisfying3691 /// a given equality relation.3692 ///3693 /// Returns two slices. The first contains no consecutive repeated elements.3694 /// The second contains all the duplicates in no specified order.3695 ///3696 /// The `same_bucket` function is passed references to two elements from the slice and3697 /// must determine if the elements compare equal. The elements are passed in opposite order3698 /// from their order in the slice, so if `same_bucket(a, b)` returns `true`, `a` is moved3699 /// at the end of the slice.3700 ///3701 /// If the slice is sorted, the first returned slice contains no duplicates.3702 ///3703 /// # Examples3704 ///3705 /// ```3706 /// #![feature(slice_partition_dedup)]3707 ///3708 /// let mut slice = ["foo", "Foo", "BAZ", "Bar", "bar", "baz", "BAZ"];3709 ///3710 /// let (dedup, duplicates) = slice.partition_dedup_by(|a, b| a.eq_ignore_ascii_case(b));3711 ///3712 /// assert_eq!(dedup, ["foo", "BAZ", "Bar", "baz"]);3713 /// assert_eq!(duplicates, ["bar", "Foo", "BAZ"]);3714 /// ```3715 #[unstable(feature = "slice_partition_dedup", issue = "54279")]3716 #[inline]3717 pub fn partition_dedup_by<F>(&mut self, mut same_bucket: F) -> (&mut [T], &mut [T])3718 where3719 F: FnMut(&mut T, &mut T) -> bool,3720 {3721 // Although we have a mutable reference to `self`, we cannot make3722 // *arbitrary* changes. The `same_bucket` calls could panic, so we3723 // must ensure that the slice is in a valid state at all times.3724 //3725 // The way that we handle this is by using swaps; we iterate3726 // over all the elements, swapping as we go so that at the end3727 // the elements we wish to keep are in the front, and those we3728 // wish to reject are at the back. We can then split the slice.3729 // This operation is still `O(n)`.3730 //3731 // Example: We start in this state, where `r` represents "next3732 // read" and `w` represents "next_write".3733 //3734 // r3735 // +---+---+---+---+---+---+3736 // | 0 | 1 | 1 | 2 | 3 | 3 |3737 // +---+---+---+---+---+---+3738 // w3739 //3740 // Comparing self[r] against self[w-1], this is not a duplicate, so3741 // we swap self[r] and self[w] (no effect as r==w) and then increment both3742 // r and w, leaving us with:3743 //3744 // r3745 // +---+---+---+---+---+---+3746 // | 0 | 1 | 1 | 2 | 3 | 3 |3747 // +---+---+---+---+---+---+3748 // w3749 //3750 // Comparing self[r] against self[w-1], this value is a duplicate,3751 // so we increment `r` but leave everything else unchanged:3752 //3753 // r3754 // +---+---+---+---+---+---+3755 // | 0 | 1 | 1 | 2 | 3 | 3 |3756 // +---+---+---+---+---+---+3757 // w3758 //3759 // Comparing self[r] against self[w-1], this is not a duplicate,3760 // so swap self[r] and self[w] and advance r and w:3761 //3762 // r3763 // +---+---+---+---+---+---+3764 // | 0 | 1 | 2 | 1 | 3 | 3 |3765 // +---+---+---+---+---+---+3766 // w3767 //3768 // Not a duplicate, repeat:3769 //3770 // r3771 // +---+---+---+---+---+---+3772 // | 0 | 1 | 2 | 3 | 1 | 3 |3773 // +---+---+---+---+---+---+3774 // w3775 //3776 // Duplicate, advance r. End of slice. Split at w.3777 3778 let len = self.len();3779 if len <= 1 {3780 return (self, &mut []);3781 }3782 3783 let ptr = self.as_mut_ptr();3784 let mut next_read: usize = 1;3785 let mut next_write: usize = 1;3786 3787 // SAFETY: the `while` condition guarantees `next_read` and `next_write`3788 // are less than `len`, thus are inside `self`. `prev_ptr_write` points to3789 // one element before `ptr_write`, but `next_write` starts at 1, so3790 // `prev_ptr_write` is never less than 0 and is inside the slice.3791 // This fulfils the requirements for dereferencing `ptr_read`, `prev_ptr_write`3792 // and `ptr_write`, and for using `ptr.add(next_read)`, `ptr.add(next_write - 1)`3793 // and `prev_ptr_write.offset(1)`.3794 //3795 // `next_write` is also incremented at most once per loop at most meaning3796 // no element is skipped when it may need to be swapped.3797 //3798 // `ptr_read` and `prev_ptr_write` never point to the same element. This3799 // is required for `&mut *ptr_read`, `&mut *prev_ptr_write` to be safe.3800 // The explanation is simply that `next_read >= next_write` is always true,3801 // thus `next_read > next_write - 1` is too.3802 unsafe {3803 // Avoid bounds checks by using raw pointers.3804 while next_read < len {3805 let ptr_read = ptr.add(next_read);3806 let prev_ptr_write = ptr.add(next_write - 1);3807 if !same_bucket(&mut *ptr_read, &mut *prev_ptr_write) {3808 if next_read != next_write {3809 let ptr_write = prev_ptr_write.add(1);3810 mem::swap(&mut *ptr_read, &mut *ptr_write);3811 }3812 next_write += 1;3813 }3814 next_read += 1;3815 }3816 }3817 3818 self.split_at_mut(next_write)3819 }3820 3821 /// Moves all but the first of consecutive elements to the end of the slice that resolve3822 /// to the same key.3823 ///3824 /// Returns two slices. The first contains no consecutive repeated elements.3825 /// The second contains all the duplicates in no specified order.3826 ///3827 /// If the slice is sorted, the first returned slice contains no duplicates.3828 ///3829 /// # Examples3830 ///3831 /// ```3832 /// #![feature(slice_partition_dedup)]3833 ///3834 /// let mut slice = [10, 20, 21, 30, 30, 20, 11, 13];3835 ///3836 /// let (dedup, duplicates) = slice.partition_dedup_by_key(|i| *i / 10);3837 ///3838 /// assert_eq!(dedup, [10, 20, 30, 20, 11]);3839 /// assert_eq!(duplicates, [21, 30, 13]);3840 /// ```3841 #[unstable(feature = "slice_partition_dedup", issue = "54279")]3842 #[inline]3843 pub fn partition_dedup_by_key<K, F>(&mut self, mut key: F) -> (&mut [T], &mut [T])3844 where3845 F: FnMut(&mut T) -> K,3846 K: PartialEq,3847 {3848 self.partition_dedup_by(|a, b| key(a) == key(b))3849 }3850 3851 /// Rotates the slice in-place such that the first `mid` elements of the3852 /// slice move to the end while the last `self.len() - mid` elements move to3853 /// the front.3854 ///3855 /// After calling `rotate_left`, the element previously at index `mid` will3856 /// become the first element in the slice.3857 ///3858 /// # Panics3859 ///3860 /// This function will panic if `mid` is greater than the length of the3861 /// slice. Note that `mid == self.len()` does _not_ panic and is a no-op3862 /// rotation.3863 ///3864 /// # Complexity3865 ///3866 /// Takes linear (in `self.len()`) time.3867 ///3868 /// # Examples3869 ///3870 /// ```3871 /// let mut a = ['a', 'b', 'c', 'd', 'e', 'f'];3872 /// a.rotate_left(2);3873 /// assert_eq!(a, ['c', 'd', 'e', 'f', 'a', 'b']);3874 /// ```3875 ///3876 /// Rotating a subslice:3877 ///3878 /// ```3879 /// let mut a = ['a', 'b', 'c', 'd', 'e', 'f'];3880 /// a[1..5].rotate_left(1);3881 /// assert_eq!(a, ['a', 'c', 'd', 'e', 'b', 'f']);3882 /// ```3883 #[stable(feature = "slice_rotate", since = "1.26.0")]3884 #[rustc_const_stable(feature = "const_slice_rotate", since = "1.92.0")]3885 pub const fn rotate_left(&mut self, mid: usize) {3886 assert!(mid <= self.len());3887 let k = self.len() - mid;3888 let p = self.as_mut_ptr();3889 3890 // SAFETY: The range `[p.add(mid) - mid, p.add(mid) + k)` is trivially3891 // valid for reading and writing, as required by `ptr_rotate`.3892 unsafe {3893 rotate::ptr_rotate(mid, p.add(mid), k);3894 }3895 }3896 3897 /// Rotates the slice in-place such that the first `self.len() - k`3898 /// elements of the slice move to the end while the last `k` elements move3899 /// to the front.3900 ///3901 /// After calling `rotate_right`, the element previously at index3902 /// `self.len() - k` will become the first element in the slice.3903 ///3904 /// # Panics3905 ///3906 /// This function will panic if `k` is greater than the length of the3907 /// slice. Note that `k == self.len()` does _not_ panic and is a no-op3908 /// rotation.3909 ///3910 /// # Complexity3911 ///3912 /// Takes linear (in `self.len()`) time.3913 ///3914 /// # Examples3915 ///3916 /// ```3917 /// let mut a = ['a', 'b', 'c', 'd', 'e', 'f'];3918 /// a.rotate_right(2);3919 /// assert_eq!(a, ['e', 'f', 'a', 'b', 'c', 'd']);3920 /// ```3921 ///3922 /// Rotating a subslice:3923 ///3924 /// ```3925 /// let mut a = ['a', 'b', 'c', 'd', 'e', 'f'];3926 /// a[1..5].rotate_right(1);3927 /// assert_eq!(a, ['a', 'e', 'b', 'c', 'd', 'f']);3928 /// ```3929 #[stable(feature = "slice_rotate", since = "1.26.0")]3930 #[rustc_const_stable(feature = "const_slice_rotate", since = "1.92.0")]3931 pub const fn rotate_right(&mut self, k: usize) {3932 assert!(k <= self.len());3933 let mid = self.len() - k;3934 let p = self.as_mut_ptr();3935 3936 // SAFETY: The range `[p.add(mid) - mid, p.add(mid) + k)` is trivially3937 // valid for reading and writing, as required by `ptr_rotate`.3938 unsafe {3939 rotate::ptr_rotate(mid, p.add(mid), k);3940 }3941 }3942 3943 /// Moves the elements of this slice `N` places to the left, returning the ones3944 /// that "fall off" the front, and putting `inserted` at the end.3945 ///3946 /// Equivalently, you can think of concatenating `self` and `inserted` into one3947 /// long sequence, then returning the left-most `N` items and the rest into `self`:3948 ///3949 /// ```text3950 /// self (before) inserted3951 /// vvvvvvvvvvvvvvv vvv3952 /// [1, 2, 3, 4, 5] [9]3953 /// โ โ โ โ โ โ3954 /// [1] [2, 3, 4, 5, 9]3955 /// ^^^ ^^^^^^^^^^^^^^^3956 /// returned self (after)3957 /// ```3958 ///3959 /// See also [`Self::shift_right`] and compare [`Self::rotate_left`].3960 ///3961 /// # Examples3962 ///3963 /// ```3964 /// #![feature(slice_shift)]3965 ///3966 /// // Same as the diagram above3967 /// let mut a = [1, 2, 3, 4, 5];3968 /// let inserted = [9];3969 /// let returned = a.shift_left(inserted);3970 /// assert_eq!(returned, [1]);3971 /// assert_eq!(a, [2, 3, 4, 5, 9]);3972 ///3973 /// // You can shift multiple items at a time3974 /// let mut a = *b"Hello world";3975 /// assert_eq!(a.shift_left(*b" peace"), *b"Hello ");3976 /// assert_eq!(a, *b"world peace");3977 ///3978 /// // The name comes from this operation's similarity to bitshifts3979 /// let mut a: u8 = 0b10010110;3980 /// a <<= 3;3981 /// assert_eq!(a, 0b10110000_u8);3982 /// let mut a: [_; 8] = [1, 0, 0, 1, 0, 1, 1, 0];3983 /// a.shift_left([0; 3]);3984 /// assert_eq!(a, [1, 0, 1, 1, 0, 0, 0, 0]);3985 ///3986 /// // Remember you can sub-slice to affect less that the whole slice.3987 /// // For example, this is similar to `.remove(1)` + `.insert(4, 'Z')`3988 /// let mut a = ['a', 'b', 'c', 'd', 'e', 'f'];3989 /// assert_eq!(a[1..=4].shift_left(['Z']), ['b']);3990 /// assert_eq!(a, ['a', 'c', 'd', 'e', 'Z', 'f']);3991 ///3992 /// // If the size matches it's equivalent to `mem::replace`3993 /// let mut a = [1, 2, 3];3994 /// assert_eq!(a.shift_left([7, 8, 9]), [1, 2, 3]);3995 /// assert_eq!(a, [7, 8, 9]);3996 ///3997 /// // Some of the "inserted" elements end up returned if the slice is too short3998 /// let mut a = [];3999 /// assert_eq!(a.shift_left([1, 2, 3]), [1, 2, 3]);4000 /// let mut a = [9];4001 /// assert_eq!(a.shift_left([1, 2, 3]), [9, 1, 2]);4002 /// assert_eq!(a, [3]);4003 /// ```4004 #[unstable(feature = "slice_shift", issue = "151772")]4005 pub const fn shift_left<const N: usize>(&mut self, inserted: [T; N]) -> [T; N] {4006 if let Some(shift) = self.len().checked_sub(N) {4007 // SAFETY: Having just checked that the inserted/returned arrays are4008 // shorter than (or the same length as) the slice:4009 // 1. The read for the items to return is in-bounds4010 // 2. We can `memmove` the slice over to cover the items we're returning4011 // to ensure those aren't double-dropped4012 // 3. Then we write (in-bounds for the same reason as the read) the4013 // inserted items atop the items of the slice that we just duplicated4014 //4015 // And none of this can panic, so there's no risk of intermediate unwinds.4016 unsafe {4017 let ptr = self.as_mut_ptr();4018 let returned = ptr.cast_array::<N>().read();4019 ptr.copy_from(ptr.add(N), shift);4020 ptr.add(shift).cast_array::<N>().write(inserted);4021 returned4022 }4023 } else {4024 // SAFETY: Having checked that the slice is strictly shorter than the4025 // inserted/returned arrays, it means we'll be copying the whole slice4026 // into the returned array, but that's not enough on its own. We also4027 // need to copy some of the inserted array into the returned array,4028 // with the rest going into the slice. Because `&mut` is exclusive4029 // and we own both `inserted` and `returned`, they're all disjoint4030 // allocations from each other as we can use `nonoverlapping` copies.4031 //4032 // We avoid double-frees by `ManuallyDrop`ing the inserted items,4033 // since we always copy them to other locations that will drop them4034 // instead. Plus nothing in here can panic -- it's just memcpy three4035 // times -- so there's no intermediate unwinds to worry about.4036 unsafe {4037 let len = self.len();4038 let slice = self.as_mut_ptr();4039 let inserted = mem::ManuallyDrop::new(inserted);4040 let inserted = (&raw const inserted).cast::<T>();4041 4042 let mut returned = MaybeUninit::<[T; N]>::uninit();4043 let ptr = returned.as_mut_ptr().cast::<T>();4044 ptr.copy_from_nonoverlapping(slice, len);4045 ptr.add(len).copy_from_nonoverlapping(inserted, N - len);4046 slice.copy_from_nonoverlapping(inserted.add(N - len), len);4047 returned.assume_init()4048 }4049 }4050 }4051 4052 /// Moves the elements of this slice `N` places to the right, returning the ones4053 /// that "fall off" the back, and putting `inserted` at the beginning.4054 ///4055 /// Equivalently, you can think of concatenating `inserted` and `self` into one4056 /// long sequence, then returning the right-most `N` items and the rest into `self`:4057 ///4058 /// ```text4059 /// inserted self (before)4060 /// vvv vvvvvvvvvvvvvvv4061 /// [0] [5, 6, 7, 8, 9]4062 /// โ โ โ โ โ โ4063 /// [0, 5, 6, 7, 8] [9]4064 /// ^^^^^^^^^^^^^^^ ^^^4065 /// self (after) returned4066 /// ```4067 ///4068 /// See also [`Self::shift_left`] and compare [`Self::rotate_right`].4069 ///4070 /// # Examples4071 ///4072 /// ```4073 /// #![feature(slice_shift)]4074 ///4075 /// // Same as the diagram above4076 /// let mut a = [5, 6, 7, 8, 9];4077 /// let inserted = [0];4078 /// let returned = a.shift_right(inserted);4079 /// assert_eq!(returned, [9]);4080 /// assert_eq!(a, [0, 5, 6, 7, 8]);4081 ///4082 /// // The name comes from this operation's similarity to bitshifts4083 /// let mut a: u8 = 0b10010110;4084 /// a >>= 3;4085 /// assert_eq!(a, 0b00010010_u8);4086 /// let mut a: [_; 8] = [1, 0, 0, 1, 0, 1, 1, 0];4087 /// a.shift_right([0; 3]);4088 /// assert_eq!(a, [0, 0, 0, 1, 0, 0, 1, 0]);4089 ///4090 /// // Remember you can sub-slice to affect less that the whole slice.4091 /// // For example, this is similar to `.remove(4)` + `.insert(1, 'Z')`4092 /// let mut a = ['a', 'b', 'c', 'd', 'e', 'f'];4093 /// assert_eq!(a[1..=4].shift_right(['Z']), ['e']);4094 /// assert_eq!(a, ['a', 'Z', 'b', 'c', 'd', 'f']);4095 ///4096 /// // If the size matches it's equivalent to `mem::replace`4097 /// let mut a = [1, 2, 3];4098 /// assert_eq!(a.shift_right([7, 8, 9]), [1, 2, 3]);4099 /// assert_eq!(a, [7, 8, 9]);4100 ///4101 /// // Some of the "inserted" elements end up returned if the slice is too short4102 /// let mut a = [];4103 /// assert_eq!(a.shift_right([1, 2, 3]), [1, 2, 3]);4104 /// let mut a = [9];4105 /// assert_eq!(a.shift_right([1, 2, 3]), [2, 3, 9]);4106 /// assert_eq!(a, [1]);4107 /// ```4108 #[unstable(feature = "slice_shift", issue = "151772")]4109 pub const fn shift_right<const N: usize>(&mut self, inserted: [T; N]) -> [T; N] {4110 if let Some(shift) = self.len().checked_sub(N) {4111 // SAFETY: Having just checked that the inserted/returned arrays are4112 // shorter than (or the same length as) the slice:4113 // 1. The read for the items to return is in-bounds4114 // 2. We can `memmove` the slice over to cover the items we're returning4115 // to ensure those aren't double-dropped4116 // 3. Then we write (in-bounds for the same reason as the read) the4117 // inserted items atop the items of the slice that we just duplicated4118 //4119 // And none of this can panic, so there's no risk of intermediate unwinds.4120 unsafe {4121 let ptr = self.as_mut_ptr();4122 let returned = ptr.add(shift).cast_array::<N>().read();4123 ptr.add(N).copy_from(ptr, shift);4124 ptr.cast_array::<N>().write(inserted);4125 returned4126 }4127 } else {4128 // SAFETY: Having checked that the slice is strictly shorter than the4129 // inserted/returned arrays, it means we'll be copying the whole slice4130 // into the returned array, but that's not enough on its own. We also4131 // need to copy some of the inserted array into the returned array,4132 // with the rest going into the slice. Because `&mut` is exclusive4133 // and we own both `inserted` and `returned`, they're all disjoint4134 // allocations from each other as we can use `nonoverlapping` copies.4135 //4136 // We avoid double-frees by `ManuallyDrop`ing the inserted items,4137 // since we always copy them to other locations that will drop them4138 // instead. Plus nothing in here can panic -- it's just memcpy three4139 // times -- so there's no intermediate unwinds to worry about.4140 unsafe {4141 let len = self.len();4142 let slice = self.as_mut_ptr();4143 let inserted = mem::ManuallyDrop::new(inserted);4144 let inserted = (&raw const inserted).cast::<T>();4145 4146 let mut returned = MaybeUninit::<[T; N]>::uninit();4147 let ptr = returned.as_mut_ptr().cast::<T>();4148 ptr.add(N - len).copy_from_nonoverlapping(slice, len);4149 ptr.copy_from_nonoverlapping(inserted.add(len), N - len);4150 slice.copy_from_nonoverlapping(inserted, len);4151 returned.assume_init()4152 }4153 }4154 }4155 4156 /// Fills `self` with elements by cloning `value`.4157 ///4158 /// # Examples4159 ///4160 /// ```4161 /// let mut buf = vec![0; 10];4162 /// buf.fill(1);4163 /// assert_eq!(buf, vec![1; 10]);4164 /// ```4165 #[doc(alias = "memset")]4166 #[stable(feature = "slice_fill", since = "1.50.0")]4167 pub fn fill(&mut self, value: T)4168 where4169 T: Clone,4170 {4171 specialize::SpecFill::spec_fill(self, value);4172 }4173 4174 /// Fills `self` with elements returned by calling a closure repeatedly.4175 ///4176 /// This method uses a closure to create new values. If you'd rather4177 /// [`Clone`] a given value, use [`fill`]. If you want to use the [`Default`]4178 /// trait to generate values, you can pass [`Default::default`] as the4179 /// argument.4180 ///4181 /// [`fill`]: slice::fill4182 ///4183 /// # Examples4184 ///4185 /// ```4186 /// let mut buf = vec![1; 10];4187 /// buf.fill_with(Default::default);4188 /// assert_eq!(buf, vec![0; 10]);4189 /// ```4190 #[stable(feature = "slice_fill_with", since = "1.51.0")]4191 pub fn fill_with<F>(&mut self, mut f: F)4192 where4193 F: FnMut() -> T,4194 {4195 for el in self {4196 *el = f();4197 }4198 }4199 4200 /// Copies the elements from `src` into `self`.4201 ///4202 /// The length of `src` must be the same as `self`.4203 ///4204 /// # Panics4205 ///4206 /// This function will panic if the two slices have different lengths.4207 ///4208 /// # Examples4209 ///4210 /// Cloning two elements from a slice into another:4211 ///4212 /// ```4213 /// let src = [1, 2, 3, 4];4214 /// let mut dst = [0, 0];4215 ///4216 /// // Because the slices have to be the same length,4217 /// // we slice the source slice from four elements4218 /// // to two. It will panic if we don't do this.4219 /// dst.clone_from_slice(&src[2..]);4220 ///4221 /// assert_eq!(src, [1, 2, 3, 4]);4222 /// assert_eq!(dst, [3, 4]);4223 /// ```4224 ///4225 /// Rust enforces that there can only be one mutable reference with no4226 /// immutable references to a particular piece of data in a particular4227 /// scope. Because of this, attempting to use `clone_from_slice` on a4228 /// single slice will result in a compile failure:4229 ///4230 /// ```compile_fail4231 /// let mut slice = [1, 2, 3, 4, 5];4232 ///4233 /// slice[..2].clone_from_slice(&slice[3..]); // compile fail!4234 /// ```4235 ///4236 /// To work around this, we can use [`split_at_mut`] to create two distinct4237 /// sub-slices from a slice:4238 ///4239 /// ```4240 /// let mut slice = [1, 2, 3, 4, 5];4241 ///4242 /// {4243 /// let (left, right) = slice.split_at_mut(2);4244 /// left.clone_from_slice(&right[1..]);4245 /// }4246 ///4247 /// assert_eq!(slice, [4, 5, 3, 4, 5]);4248 /// ```4249 ///4250 /// [`copy_from_slice`]: slice::copy_from_slice4251 /// [`split_at_mut`]: slice::split_at_mut4252 #[stable(feature = "clone_from_slice", since = "1.7.0")]4253 #[track_caller]4254 #[rustc_const_unstable(feature = "const_clone", issue = "142757")]4255 pub const fn clone_from_slice(&mut self, src: &[T])4256 where4257 T: [const] Clone + [const] Destruct,4258 {4259 self.spec_clone_from(src);4260 }4261 4262 /// Copies all elements from `src` into `self`, using a memcpy.4263 ///4264 /// The length of `src` must be the same as `self`.4265 ///4266 /// If `T` does not implement `Copy`, use [`clone_from_slice`].4267 ///4268 /// # Panics4269 ///4270 /// This function will panic if the two slices have different lengths.4271 ///4272 /// # Examples4273 ///4274 /// Copying two elements from a slice into another:4275 ///4276 /// ```4277 /// let src = [1, 2, 3, 4];4278 /// let mut dst = [0, 0];4279 ///4280 /// // Because the slices have to be the same length,4281 /// // we slice the source slice from four elements4282 /// // to two. It will panic if we don't do this.4283 /// dst.copy_from_slice(&src[2..]);4284 ///4285 /// assert_eq!(src, [1, 2, 3, 4]);4286 /// assert_eq!(dst, [3, 4]);4287 /// ```4288 ///4289 /// Rust enforces that there can only be one mutable reference with no4290 /// immutable references to a particular piece of data in a particular4291 /// scope. Because of this, attempting to use `copy_from_slice` on a4292 /// single slice will result in a compile failure:4293 ///4294 /// ```compile_fail4295 /// let mut slice = [1, 2, 3, 4, 5];4296 ///4297 /// slice[..2].copy_from_slice(&slice[3..]); // compile fail!4298 /// ```4299 ///4300 /// To work around this, we can use [`split_at_mut`] to create two distinct4301 /// sub-slices from a slice:4302 ///4303 /// ```4304 /// let mut slice = [1, 2, 3, 4, 5];4305 ///4306 /// {4307 /// let (left, right) = slice.split_at_mut(2);4308 /// left.copy_from_slice(&right[1..]);4309 /// }4310 ///4311 /// assert_eq!(slice, [4, 5, 3, 4, 5]);4312 /// ```4313 ///4314 /// [`clone_from_slice`]: slice::clone_from_slice4315 /// [`split_at_mut`]: slice::split_at_mut4316 #[doc(alias = "memcpy")]4317 #[inline]4318 #[stable(feature = "copy_from_slice", since = "1.9.0")]4319 #[rustc_const_stable(feature = "const_copy_from_slice", since = "1.87.0")]4320 #[track_caller]4321 pub const fn copy_from_slice(&mut self, src: &[T])4322 where4323 T: Copy,4324 {4325 // SAFETY: `T` implements `Copy`.4326 unsafe { copy_from_slice_impl(self, src) }4327 }4328 4329 /// Copies elements from one part of the slice to another part of itself,4330 /// using a memmove.4331 ///4332 /// `src` is the range within `self` to copy from. `dest` is the starting4333 /// index of the range within `self` to copy to, which will have the same4334 /// length as `src`. The two ranges may overlap. The ends of the two ranges4335 /// must be less than or equal to `self.len()`.4336 ///4337 /// # Panics4338 ///4339 /// This function will panic if either range exceeds the end of the slice,4340 /// or if the end of `src` is before the start.4341 ///4342 /// # Examples4343 ///4344 /// Copying four bytes within a slice:4345 ///4346 /// ```4347 /// let mut bytes = *b"Hello, World!";4348 ///4349 /// bytes.copy_within(1..5, 8);4350 ///4351 /// assert_eq!(&bytes, b"Hello, Wello!");4352 /// ```4353 #[inline]4354 #[stable(feature = "copy_within", since = "1.37.0")]4355 #[track_caller]4356 pub fn copy_within<R: RangeBounds<usize>>(&mut self, src: R, dest: usize)4357 where4358 T: Copy,4359 {4360 let Range { start: src_start, end: src_end } = slice::range(src, ..self.len());4361 let count = src_end - src_start;4362 assert!(dest <= self.len() - count, "dest is out of bounds");4363 // SAFETY: the conditions for `ptr::copy` have all been checked above,4364 // as have those for `ptr::add`.4365 unsafe {4366 // Derive both `src_ptr` and `dest_ptr` from the same loan4367 let ptr = self.as_mut_ptr();4368 let src_ptr = ptr.add(src_start);4369 let dest_ptr = ptr.add(dest);4370 ptr::copy(src_ptr, dest_ptr, count);4371 }4372 }4373 4374 /// Swaps all elements in `self` with those in `other`.4375 ///4376 /// The length of `other` must be the same as `self`.4377 ///4378 /// # Panics4379 ///4380 /// This function will panic if the two slices have different lengths.4381 ///4382 /// # Example4383 ///4384 /// Swapping two elements across slices:4385 ///4386 /// ```4387 /// let mut slice1 = [0, 0];4388 /// let mut slice2 = [1, 2, 3, 4];4389 ///4390 /// slice1.swap_with_slice(&mut slice2[2..]);4391 ///4392 /// assert_eq!(slice1, [3, 4]);4393 /// assert_eq!(slice2, [1, 2, 0, 0]);4394 /// ```4395 ///4396 /// Rust enforces that there can only be one mutable reference to a4397 /// particular piece of data in a particular scope. Because of this,4398 /// attempting to use `swap_with_slice` on a single slice will result in4399 /// a compile failure:4400 ///4401 /// ```compile_fail4402 /// let mut slice = [1, 2, 3, 4, 5];4403 /// slice[..2].swap_with_slice(&mut slice[3..]); // compile fail!4404 /// ```4405 ///4406 /// To work around this, we can use [`split_at_mut`] to create two distinct4407 /// mutable sub-slices from a slice:4408 ///4409 /// ```4410 /// let mut slice = [1, 2, 3, 4, 5];4411 ///4412 /// {4413 /// let (left, right) = slice.split_at_mut(2);4414 /// left.swap_with_slice(&mut right[1..]);4415 /// }4416 ///4417 /// assert_eq!(slice, [4, 5, 3, 1, 2]);4418 /// ```4419 ///4420 /// [`split_at_mut`]: slice::split_at_mut4421 #[stable(feature = "swap_with_slice", since = "1.27.0")]4422 #[rustc_const_unstable(feature = "const_swap_with_slice", issue = "142204")]4423 #[track_caller]4424 pub const fn swap_with_slice(&mut self, other: &mut [T]) {4425 assert!(self.len() == other.len(), "destination and source slices have different lengths");4426 // SAFETY: `self` is valid for `self.len()` elements by definition, and `src` was4427 // checked to have the same length. The slices cannot overlap because4428 // mutable references are exclusive.4429 unsafe {4430 ptr::swap_nonoverlapping(self.as_mut_ptr(), other.as_mut_ptr(), self.len());4431 }4432 }4433 4434 /// Function to calculate lengths of the middle and trailing slice for `align_to{,_mut}`.4435 fn align_to_offsets<U>(&self) -> (usize, usize) {4436 // What we gonna do about `rest` is figure out what multiple of `U`s we can put in a4437 // lowest number of `T`s. And how many `T`s we need for each such "multiple".4438 //4439 // Consider for example T=u8 U=u16. Then we can put 1 U in 2 Ts. Simple. Now, consider4440 // for example a case where size_of::<T> = 16, size_of::<U> = 24. We can put 2 Us in4441 // place of every 3 Ts in the `rest` slice. A bit more complicated.4442 //4443 // Formula to calculate this is:4444 //4445 // Us = lcm(size_of::<T>, size_of::<U>) / size_of::<U>4446 // Ts = lcm(size_of::<T>, size_of::<U>) / size_of::<T>4447 //4448 // Expanded and simplified:4449 //4450 // Us = size_of::<T> / gcd(size_of::<T>, size_of::<U>)4451 // Ts = size_of::<U> / gcd(size_of::<T>, size_of::<U>)4452 //4453 // Luckily since all this is constant-evaluated... performance here matters not!4454 const fn gcd(a: usize, b: usize) -> usize {4455 if b == 0 { a } else { gcd(b, a % b) }4456 }4457 4458 // Explicitly wrap the function call in a const block so it gets4459 // constant-evaluated even in debug mode.4460 let gcd: usize = const { gcd(size_of::<T>(), size_of::<U>()) };4461 let ts: usize = size_of::<U>() / gcd;4462 let us: usize = size_of::<T>() / gcd;4463 4464 // Armed with this knowledge, we can find how many `U`s we can fit!4465 let us_len = self.len() / ts * us;4466 // And how many `T`s will be in the trailing slice!4467 let ts_len = self.len() % ts;4468 (us_len, ts_len)4469 }4470 4471 /// Transmutes the slice to a slice of another type, ensuring alignment of the types is4472 /// maintained.4473 ///4474 /// This method splits the slice into three distinct slices: prefix, correctly aligned middle4475 /// slice of a new type, and the suffix slice. The middle part will be as big as possible under4476 /// the given alignment constraint and element size.4477 ///4478 /// This method has no purpose when either input element `T` or output element `U` are4479 /// zero-sized and will return the original slice without splitting anything.4480 ///4481 /// # Safety4482 ///4483 /// This method is essentially a `transmute` with respect to the elements in the returned4484 /// middle slice, so all the usual caveats pertaining to `transmute::<T, U>` also apply here.4485 ///4486 /// # Examples4487 ///4488 /// Basic usage:4489 ///4490 /// ```4491 /// unsafe {4492 /// let bytes: [u8; 7] = [1, 2, 3, 4, 5, 6, 7];4493 /// let (prefix, shorts, suffix) = bytes.align_to::<u16>();4494 /// // less_efficient_algorithm_for_bytes(prefix);4495 /// // more_efficient_algorithm_for_aligned_shorts(shorts);4496 /// // less_efficient_algorithm_for_bytes(suffix);4497 /// }4498 /// ```4499 #[stable(feature = "slice_align_to", since = "1.30.0")]4500 #[must_use]4501 pub unsafe fn align_to<U>(&self) -> (&[T], &[U], &[T]) {4502 // Note that most of this function will be constant-evaluated,4503 if U::IS_ZST || T::IS_ZST {4504 // handle ZSTs specially, which is โ don't handle them at all.4505 return (self, &[], &[]);4506 }4507 4508 // First, find at what point do we split between the first and 2nd slice. Easy with4509 // ptr.align_offset.4510 let ptr = self.as_ptr();4511 // SAFETY: See the `align_to_mut` method for the detailed safety comment.4512 let offset = unsafe { crate::ptr::align_offset(ptr, align_of::<U>()) };4513 if offset > self.len() {4514 (self, &[], &[])4515 } else {4516 let (left, rest) = self.split_at(offset);4517 let (us_len, ts_len) = rest.align_to_offsets::<U>();4518 // Inform Miri that we want to consider the "middle" pointer to be suitably aligned.4519 #[cfg(miri)]4520 crate::intrinsics::miri_promise_symbolic_alignment(4521 rest.as_ptr().cast(),4522 align_of::<U>(),4523 );4524 // SAFETY: now `rest` is definitely aligned, so `from_raw_parts` below is okay,4525 // since the caller guarantees that we can transmute `T` to `U` safely.4526 unsafe {4527 (4528 left,4529 from_raw_parts(rest.as_ptr() as *const U, us_len),4530 from_raw_parts(rest.as_ptr().add(rest.len() - ts_len), ts_len),4531 )4532 }4533 }4534 }4535 4536 /// Transmutes the mutable slice to a mutable slice of another type, ensuring alignment of the4537 /// types is maintained.4538 ///4539 /// This method splits the slice into three distinct slices: prefix, correctly aligned middle4540 /// slice of a new type, and the suffix slice. The middle part will be as big as possible under4541 /// the given alignment constraint and element size.4542 ///4543 /// This method has no purpose when either input element `T` or output element `U` are4544 /// zero-sized and will return the original slice without splitting anything.4545 ///4546 /// # Safety4547 ///4548 /// This method is essentially a `transmute` with respect to the elements in the returned4549 /// middle slice, so all the usual caveats pertaining to `transmute::<T, U>` also apply here.4550 ///4551 /// # Examples4552 ///4553 /// Basic usage:4554 ///4555 /// ```4556 /// unsafe {4557 /// let mut bytes: [u8; 7] = [1, 2, 3, 4, 5, 6, 7];4558 /// let (prefix, shorts, suffix) = bytes.align_to_mut::<u16>();4559 /// // less_efficient_algorithm_for_bytes(prefix);4560 /// // more_efficient_algorithm_for_aligned_shorts(shorts);4561 /// // less_efficient_algorithm_for_bytes(suffix);4562 /// }4563 /// ```4564 #[stable(feature = "slice_align_to", since = "1.30.0")]4565 #[must_use]4566 pub unsafe fn align_to_mut<U>(&mut self) -> (&mut [T], &mut [U], &mut [T]) {4567 // Note that most of this function will be constant-evaluated,4568 if U::IS_ZST || T::IS_ZST {4569 // handle ZSTs specially, which is โ don't handle them at all.4570 return (self, &mut [], &mut []);4571 }4572 4573 // First, find at what point do we split between the first and 2nd slice. Easy with4574 // ptr.align_offset.4575 let ptr = self.as_ptr();4576 // SAFETY: Here we are ensuring we will use aligned pointers for U for the4577 // rest of the method. This is done by passing a pointer to &[T] with an4578 // alignment targeted for U.4579 // `crate::ptr::align_offset` is called with a correctly aligned and4580 // valid pointer `ptr` (it comes from a reference to `self`) and with4581 // a size that is a power of two (since it comes from the alignment for U),4582 // satisfying its safety constraints.4583 let offset = unsafe { crate::ptr::align_offset(ptr, align_of::<U>()) };4584 if offset > self.len() {4585 (self, &mut [], &mut [])4586 } else {4587 let (left, rest) = self.split_at_mut(offset);4588 let (us_len, ts_len) = rest.align_to_offsets::<U>();4589 let rest_len = rest.len();4590 let mut_ptr = rest.as_mut_ptr();4591 // Inform Miri that we want to consider the "middle" pointer to be suitably aligned.4592 #[cfg(miri)]4593 crate::intrinsics::miri_promise_symbolic_alignment(4594 mut_ptr.cast() as *const (),4595 align_of::<U>(),4596 );4597 // We can't use `rest` again after this, that would invalidate its alias `mut_ptr`!4598 // SAFETY: see comments for `align_to`.4599 unsafe {4600 (4601 left,4602 from_raw_parts_mut(mut_ptr as *mut U, us_len),4603 from_raw_parts_mut(mut_ptr.add(rest_len - ts_len), ts_len),4604 )4605 }4606 }4607 }4608 4609 /// Splits a slice into a prefix, a middle of aligned SIMD types, and a suffix.4610 ///4611 /// This is a safe wrapper around [`slice::align_to`], so inherits the same4612 /// guarantees as that method.4613 ///4614 /// # Panics4615 ///4616 /// This will panic if the size of the SIMD type is different from4617 /// `LANES` times that of the scalar.4618 ///4619 /// At the time of writing, the trait restrictions on `Simd<T, LANES>` keeps4620 /// that from ever happening, as only power-of-two numbers of lanes are4621 /// supported. It's possible that, in the future, those restrictions might4622 /// be lifted in a way that would make it possible to see panics from this4623 /// method for something like `LANES == 3`.4624 ///4625 /// # Examples4626 ///4627 /// ```4628 /// #![feature(portable_simd)]4629 /// use core::simd::prelude::*;4630 ///4631 /// let short = &[1, 2, 3];4632 /// let (prefix, middle, suffix) = short.as_simd::<4>();4633 /// assert_eq!(middle, []); // Not enough elements for anything in the middle4634 ///4635 /// // They might be split in any possible way between prefix and suffix4636 /// let it = prefix.iter().chain(suffix).copied();4637 /// assert_eq!(it.collect::<Vec<_>>(), vec![1, 2, 3]);4638 ///4639 /// fn basic_simd_sum(x: &[f32]) -> f32 {4640 /// use std::ops::Add;4641 /// let (prefix, middle, suffix) = x.as_simd();4642 /// let sums = f32x4::from_array([4643 /// prefix.iter().copied().sum(),4644 /// 0.0,4645 /// 0.0,4646 /// suffix.iter().copied().sum(),4647 /// ]);4648 /// let sums = middle.iter().copied().fold(sums, f32x4::add);4649 /// sums.reduce_sum()4650 /// }4651 ///4652 /// let numbers: Vec<f32> = (1..101).map(|x| x as _).collect();4653 /// assert_eq!(basic_simd_sum(&numbers[1..99]), 4949.0);4654 /// ```4655 #[unstable(feature = "portable_simd", issue = "86656")]4656 #[must_use]4657 pub fn as_simd<const LANES: usize>(&self) -> (&[T], &[Simd<T, LANES>], &[T])4658 where4659 Simd<T, LANES>: AsRef<[T; LANES]>,4660 T: simd::SimdElement,4661 {4662 // These are expected to always match, as vector types are laid out like4663 // arrays per <https://llvm.org/docs/LangRef.html#vector-type>, but we4664 // might as well double-check since it'll optimize away anyhow.4665 assert_eq!(size_of::<Simd<T, LANES>>(), size_of::<[T; LANES]>());4666 4667 // SAFETY: The simd types have the same layout as arrays, just with4668 // potentially-higher alignment, so the de-facto transmutes are sound.4669 unsafe { self.align_to() }4670 }4671 4672 /// Splits a mutable slice into a mutable prefix, a middle of aligned SIMD types,4673 /// and a mutable suffix.4674 ///4675 /// This is a safe wrapper around [`slice::align_to_mut`], so inherits the same4676 /// guarantees as that method.4677 ///4678 /// This is the mutable version of [`slice::as_simd`]; see that for examples.4679 ///4680 /// # Panics4681 ///4682 /// This will panic if the size of the SIMD type is different from4683 /// `LANES` times that of the scalar.4684 ///4685 /// At the time of writing, the trait restrictions on `Simd<T, LANES>` keeps4686 /// that from ever happening, as only power-of-two numbers of lanes are4687 /// supported. It's possible that, in the future, those restrictions might4688 /// be lifted in a way that would make it possible to see panics from this4689 /// method for something like `LANES == 3`.4690 #[unstable(feature = "portable_simd", issue = "86656")]4691 #[must_use]4692 pub fn as_simd_mut<const LANES: usize>(&mut self) -> (&mut [T], &mut [Simd<T, LANES>], &mut [T])4693 where4694 Simd<T, LANES>: AsMut<[T; LANES]>,4695 T: simd::SimdElement,4696 {4697 // These are expected to always match, as vector types are laid out like4698 // arrays per <https://llvm.org/docs/LangRef.html#vector-type>, but we4699 // might as well double-check since it'll optimize away anyhow.4700 assert_eq!(size_of::<Simd<T, LANES>>(), size_of::<[T; LANES]>());4701 4702 // SAFETY: The simd types have the same layout as arrays, just with4703 // potentially-higher alignment, so the de-facto transmutes are sound.4704 unsafe { self.align_to_mut() }4705 }4706 4707 /// Checks if the elements of this slice are sorted.4708 ///4709 /// That is, for each element `a` and its following element `b`, `a <= b` must hold. If the4710 /// slice yields exactly zero or one element, `true` is returned.4711 ///4712 /// Note that if `Self::Item` is only `PartialOrd`, but not `Ord`, the above definition4713 /// implies that this function returns `false` if any two consecutive items are not4714 /// comparable.4715 ///4716 /// # Examples4717 ///4718 /// ```4719 /// let empty: [i32; 0] = [];4720 ///4721 /// assert!([1, 2, 2, 9].is_sorted());4722 /// assert!(![1, 3, 2, 4].is_sorted());4723 /// assert!([0].is_sorted());4724 /// assert!(empty.is_sorted());4725 /// assert!(![0.0, 1.0, f32::NAN].is_sorted());4726 /// ```4727 #[inline]4728 #[stable(feature = "is_sorted", since = "1.82.0")]4729 #[must_use]4730 pub fn is_sorted(&self) -> bool4731 where4732 T: PartialOrd,4733 {4734 // This odd number works the best. 32 + 1 extra due to overlapping chunk boundaries.4735 const CHUNK_SIZE: usize = 33;4736 if self.len() < CHUNK_SIZE {4737 return self.windows(2).all(|w| w[0] <= w[1]);4738 }4739 let mut i = 0;4740 // Check in chunks for autovectorization.4741 while i < self.len() - CHUNK_SIZE {4742 let chunk = &self[i..i + CHUNK_SIZE];4743 if !chunk.windows(2).fold(true, |acc, w| acc & (w[0] <= w[1])) {4744 return false;4745 }4746 // We need to ensure that chunk boundaries are also sorted.4747 // Overlap the next chunk with the last element of our last chunk.4748 i += CHUNK_SIZE - 1;4749 }4750 self[i..].windows(2).all(|w| w[0] <= w[1])4751 }4752 4753 /// Checks if the elements of this slice are sorted using the given comparator function.4754 ///4755 /// Instead of using `PartialOrd::partial_cmp`, this function uses the given `compare`4756 /// function to determine whether two elements are to be considered in sorted order.4757 ///4758 /// # Examples4759 ///4760 /// ```4761 /// assert!([1, 2, 2, 9].is_sorted_by(|a, b| a <= b));4762 /// assert!(![1, 2, 2, 9].is_sorted_by(|a, b| a < b));4763 ///4764 /// assert!([0].is_sorted_by(|a, b| true));4765 /// assert!([0].is_sorted_by(|a, b| false));4766 ///4767 /// let empty: [i32; 0] = [];4768 /// assert!(empty.is_sorted_by(|a, b| false));4769 /// assert!(empty.is_sorted_by(|a, b| true));4770 /// ```4771 #[stable(feature = "is_sorted", since = "1.82.0")]4772 #[must_use]4773 pub fn is_sorted_by<'a, F>(&'a self, mut compare: F) -> bool4774 where4775 F: FnMut(&'a T, &'a T) -> bool,4776 {4777 self.array_windows().all(|[a, b]| compare(a, b))4778 }4779 4780 /// Checks if the elements of this slice are sorted using the given key extraction function.4781 ///4782 /// Instead of comparing the slice's elements directly, this function compares the keys of the4783 /// elements, as determined by `f`. Apart from that, it's equivalent to [`is_sorted`]; see its4784 /// documentation for more information.4785 ///4786 /// [`is_sorted`]: slice::is_sorted4787 ///4788 /// # Examples4789 ///4790 /// ```4791 /// assert!(["c", "bb", "aaa"].is_sorted_by_key(|s| s.len()));4792 /// assert!(![-2i32, -1, 0, 3].is_sorted_by_key(|n| n.abs()));4793 /// ```4794 #[inline]4795 #[stable(feature = "is_sorted", since = "1.82.0")]4796 #[must_use]4797 pub fn is_sorted_by_key<'a, F, K>(&'a self, f: F) -> bool4798 where4799 F: FnMut(&'a T) -> K,4800 K: PartialOrd,4801 {4802 self.iter().is_sorted_by_key(f)4803 }4804 4805 /// Returns the index of the partition point according to the given predicate4806 /// (the index of the first element of the second partition).4807 ///4808 /// The slice is assumed to be partitioned according to the given predicate.4809 /// This means that all elements for which the predicate returns true are at the start of the slice4810 /// and all elements for which the predicate returns false are at the end.4811 /// For example, `[7, 15, 3, 5, 4, 12, 6]` is partitioned under the predicate `x % 2 != 0`4812 /// (all odd numbers are at the start, all even at the end).4813 ///4814 /// If this slice is not partitioned, the returned result is unspecified and meaningless,4815 /// as this method performs a kind of binary search.4816 ///4817 /// See also [`binary_search`], [`binary_search_by`], and [`binary_search_by_key`].4818 ///4819 /// [`binary_search`]: slice::binary_search4820 /// [`binary_search_by`]: slice::binary_search_by4821 /// [`binary_search_by_key`]: slice::binary_search_by_key4822 ///4823 /// # Examples4824 ///4825 /// ```4826 /// let v = [1, 2, 3, 3, 5, 6, 7];4827 /// let i = v.partition_point(|&x| x < 5);4828 ///4829 /// assert_eq!(i, 4);4830 /// assert!(v[..i].iter().all(|&x| x < 5));4831 /// assert!(v[i..].iter().all(|&x| !(x < 5)));4832 /// ```4833 ///4834 /// If all elements of the slice match the predicate, including if the slice4835 /// is empty, then the length of the slice will be returned:4836 ///4837 /// ```4838 /// let a = [2, 4, 8];4839 /// assert_eq!(a.partition_point(|x| x < &100), a.len());4840 /// let a: [i32; 0] = [];4841 /// assert_eq!(a.partition_point(|x| x < &100), 0);4842 /// ```4843 ///4844 /// If you want to insert an item to a sorted vector, while maintaining4845 /// sort order:4846 ///4847 /// ```4848 /// let mut s = vec![0, 1, 1, 1, 1, 2, 3, 5, 8, 13, 21, 34, 55];4849 /// let num = 42;4850 /// let idx = s.partition_point(|&x| x <= num);4851 /// s.insert(idx, num);4852 /// assert_eq!(s, [0, 1, 1, 1, 1, 2, 3, 5, 8, 13, 21, 34, 42, 55]);4853 /// ```4854 #[stable(feature = "partition_point", since = "1.52.0")]4855 #[must_use]4856 pub fn partition_point<P>(&self, mut pred: P) -> usize4857 where4858 P: FnMut(&T) -> bool,4859 {4860 self.binary_search_by(|x| if pred(x) { Less } else { Greater }).unwrap_or_else(|i| i)4861 }4862 4863 /// Removes the subslice corresponding to the given range4864 /// and returns a reference to it.4865 ///4866 /// Returns `None` and does not modify the slice if the given4867 /// range is out of bounds.4868 ///4869 /// Note that this method only accepts one-sided ranges such as4870 /// `2..` or `..6`, but not `2..6`.4871 ///4872 /// # Examples4873 ///4874 /// Splitting off the first three elements of a slice:4875 ///4876 /// ```4877 /// let mut slice: &[_] = &['a', 'b', 'c', 'd'];4878 /// let mut first_three = slice.split_off(..3).unwrap();4879 ///4880 /// assert_eq!(slice, &['d']);4881 /// assert_eq!(first_three, &['a', 'b', 'c']);4882 /// ```4883 ///4884 /// Splitting off a slice starting with the third element:4885 ///4886 /// ```4887 /// let mut slice: &[_] = &['a', 'b', 'c', 'd'];4888 /// let mut tail = slice.split_off(2..).unwrap();4889 ///4890 /// assert_eq!(slice, &['a', 'b']);4891 /// assert_eq!(tail, &['c', 'd']);4892 /// ```4893 ///4894 /// Getting `None` when `range` is out of bounds:4895 ///4896 /// ```4897 /// let mut slice: &[_] = &['a', 'b', 'c', 'd'];4898 ///4899 /// assert_eq!(None, slice.split_off(5..));4900 /// assert_eq!(None, slice.split_off(..5));4901 /// assert_eq!(None, slice.split_off(..=4));4902 /// let expected: &[char] = &['a', 'b', 'c', 'd'];4903 /// assert_eq!(Some(expected), slice.split_off(..4));4904 /// ```4905 #[inline]4906 #[must_use = "method does not modify the slice if the range is out of bounds"]4907 #[stable(feature = "slice_take", since = "1.87.0")]4908 pub fn split_off<'a, R: OneSidedRange<usize>>(4909 self: &mut &'a Self,4910 range: R,4911 ) -> Option<&'a Self> {4912 let (direction, split_index) = split_point_of(range)?;4913 if split_index > self.len() {4914 return None;4915 }4916 let (front, back) = self.split_at(split_index);4917 match direction {4918 Direction::Front => {4919 *self = back;4920 Some(front)4921 }4922 Direction::Back => {4923 *self = front;4924 Some(back)4925 }4926 }4927 }4928 4929 /// Removes the subslice corresponding to the given range4930 /// and returns a mutable reference to it.4931 ///4932 /// Returns `None` and does not modify the slice if the given4933 /// range is out of bounds.4934 ///4935 /// Note that this method only accepts one-sided ranges such as4936 /// `2..` or `..6`, but not `2..6`.4937 ///4938 /// # Examples4939 ///4940 /// Splitting off the first three elements of a slice:4941 ///4942 /// ```4943 /// let mut slice: &mut [_] = &mut ['a', 'b', 'c', 'd'];4944 /// let mut first_three = slice.split_off_mut(..3).unwrap();4945 ///4946 /// assert_eq!(slice, &mut ['d']);4947 /// assert_eq!(first_three, &mut ['a', 'b', 'c']);4948 /// ```4949 ///4950 /// Splitting off a slice starting with the third element:4951 ///4952 /// ```4953 /// let mut slice: &mut [_] = &mut ['a', 'b', 'c', 'd'];4954 /// let mut tail = slice.split_off_mut(2..).unwrap();4955 ///4956 /// assert_eq!(slice, &mut ['a', 'b']);4957 /// assert_eq!(tail, &mut ['c', 'd']);4958 /// ```4959 ///4960 /// Getting `None` when `range` is out of bounds:4961 ///4962 /// ```4963 /// let mut slice: &mut [_] = &mut ['a', 'b', 'c', 'd'];4964 ///4965 /// assert_eq!(None, slice.split_off_mut(5..));4966 /// assert_eq!(None, slice.split_off_mut(..5));4967 /// assert_eq!(None, slice.split_off_mut(..=4));4968 /// let expected: &mut [_] = &mut ['a', 'b', 'c', 'd'];4969 /// assert_eq!(Some(expected), slice.split_off_mut(..4));4970 /// ```4971 #[inline]4972 #[must_use = "method does not modify the slice if the range is out of bounds"]4973 #[stable(feature = "slice_take", since = "1.87.0")]4974 pub fn split_off_mut<'a, R: OneSidedRange<usize>>(4975 self: &mut &'a mut Self,4976 range: R,4977 ) -> Option<&'a mut Self> {4978 let (direction, split_index) = split_point_of(range)?;4979 if split_index > self.len() {4980 return None;4981 }4982 let (front, back) = mem::take(self).split_at_mut(split_index);4983 match direction {4984 Direction::Front => {4985 *self = back;4986 Some(front)4987 }4988 Direction::Back => {4989 *self = front;4990 Some(back)4991 }4992 }4993 }4994 4995 /// Removes the first element of the slice and returns a reference4996 /// to it.4997 ///4998 /// Returns `None` if the slice is empty.4999 ///5000 /// # Examples5001 ///5002 /// ```5003 /// let mut slice: &[_] = &['a', 'b', 'c'];5004 /// let first = slice.split_off_first().unwrap();5005 ///5006 /// assert_eq!(slice, &['b', 'c']);5007 /// assert_eq!(first, &'a');5008 /// ```5009 #[inline]5010 #[stable(feature = "slice_take", since = "1.87.0")]5011 #[rustc_const_unstable(feature = "const_split_off_first_last", issue = "138539")]5012 pub const fn split_off_first<'a>(self: &mut &'a Self) -> Option<&'a T> {5013 // FIXME(const-hack): Use `?` when available in const instead of `let-else`.5014 let Some((first, rem)) = self.split_first() else { return None };5015 *self = rem;5016 Some(first)5017 }5018 5019 /// Removes the first element of the slice and returns a mutable5020 /// reference to it.5021 ///5022 /// Returns `None` if the slice is empty.5023 ///5024 /// # Examples5025 ///5026 /// ```5027 /// let mut slice: &mut [_] = &mut ['a', 'b', 'c'];5028 /// let first = slice.split_off_first_mut().unwrap();5029 /// *first = 'd';5030 ///5031 /// assert_eq!(slice, &['b', 'c']);5032 /// assert_eq!(first, &'d');5033 /// ```5034 #[inline]5035 #[stable(feature = "slice_take", since = "1.87.0")]5036 #[rustc_const_unstable(feature = "const_split_off_first_last", issue = "138539")]5037 pub const fn split_off_first_mut<'a>(self: &mut &'a mut Self) -> Option<&'a mut T> {5038 // FIXME(const-hack): Use `mem::take` and `?` when available in const.5039 // Original: `mem::take(self).split_first_mut()?`5040 let Some((first, rem)) = mem::replace(self, &mut []).split_first_mut() else { return None };5041 *self = rem;5042 Some(first)5043 }5044 5045 /// Removes the last element of the slice and returns a reference5046 /// to it.5047 ///5048 /// Returns `None` if the slice is empty.5049 ///5050 /// # Examples5051 ///5052 /// ```5053 /// let mut slice: &[_] = &['a', 'b', 'c'];5054 /// let last = slice.split_off_last().unwrap();5055 ///5056 /// assert_eq!(slice, &['a', 'b']);5057 /// assert_eq!(last, &'c');5058 /// ```5059 #[inline]5060 #[stable(feature = "slice_take", since = "1.87.0")]5061 #[rustc_const_unstable(feature = "const_split_off_first_last", issue = "138539")]5062 pub const fn split_off_last<'a>(self: &mut &'a Self) -> Option<&'a T> {5063 // FIXME(const-hack): Use `?` when available in const instead of `let-else`.5064 let Some((last, rem)) = self.split_last() else { return None };5065 *self = rem;5066 Some(last)5067 }5068 5069 /// Removes the last element of the slice and returns a mutable5070 /// reference to it.5071 ///5072 /// Returns `None` if the slice is empty.5073 ///5074 /// # Examples5075 ///5076 /// ```5077 /// let mut slice: &mut [_] = &mut ['a', 'b', 'c'];5078 /// let last = slice.split_off_last_mut().unwrap();5079 /// *last = 'd';5080 ///5081 /// assert_eq!(slice, &['a', 'b']);5082 /// assert_eq!(last, &'d');5083 /// ```5084 #[inline]5085 #[stable(feature = "slice_take", since = "1.87.0")]5086 #[rustc_const_unstable(feature = "const_split_off_first_last", issue = "138539")]5087 pub const fn split_off_last_mut<'a>(self: &mut &'a mut Self) -> Option<&'a mut T> {5088 // FIXME(const-hack): Use `mem::take` and `?` when available in const.5089 // Original: `mem::take(self).split_last_mut()?`5090 let Some((last, rem)) = mem::replace(self, &mut []).split_last_mut() else { return None };5091 *self = rem;5092 Some(last)5093 }5094 5095 /// Returns mutable references to many indices at once, without doing any checks.5096 ///5097 /// An index can be either a `usize`, a [`Range`] or a [`RangeInclusive`]. Note5098 /// that this method takes an array, so all indices must be of the same type.5099 /// If passed an array of `usize`s this method gives back an array of mutable references5100 /// to single elements, while if passed an array of ranges it gives back an array of5101 /// mutable references to slices.5102 ///5103 /// For a safe alternative see [`get_disjoint_mut`].5104 ///5105 /// # Safety5106 ///5107 /// Calling this method with overlapping or out-of-bounds indices is *[undefined behavior]*5108 /// even if the resulting references are not used.5109 ///5110 /// # Examples5111 ///5112 /// ```5113 /// let x = &mut [1, 2, 4];5114 ///5115 /// unsafe {5116 /// let [a, b] = x.get_disjoint_unchecked_mut([0, 2]);5117 /// *a *= 10;5118 /// *b *= 100;5119 /// }5120 /// assert_eq!(x, &[10, 2, 400]);5121 ///5122 /// unsafe {5123 /// let [a, b] = x.get_disjoint_unchecked_mut([0..1, 1..3]);5124 /// a[0] = 8;5125 /// b[0] = 88;5126 /// b[1] = 888;5127 /// }5128 /// assert_eq!(x, &[8, 88, 888]);5129 ///5130 /// unsafe {5131 /// let [a, b] = x.get_disjoint_unchecked_mut([1..=2, 0..=0]);5132 /// a[0] = 11;5133 /// a[1] = 111;5134 /// b[0] = 1;5135 /// }5136 /// assert_eq!(x, &[1, 11, 111]);5137 /// ```5138 ///5139 /// [`get_disjoint_mut`]: slice::get_disjoint_mut5140 /// [undefined behavior]: https://doc.rust-lang.org/reference/behavior-considered-undefined.html5141 #[stable(feature = "get_many_mut", since = "1.86.0")]5142 #[inline]5143 #[track_caller]5144 pub unsafe fn get_disjoint_unchecked_mut<I, const N: usize>(5145 &mut self,5146 indices: [I; N],5147 ) -> [&mut I::Output; N]5148 where5149 I: GetDisjointMutIndex + SliceIndex<Self>,5150 {5151 // NB: This implementation is written as it is because any variation of5152 // `indices.map(|i| self.get_unchecked_mut(i))` would make miri unhappy,5153 // or generate worse code otherwise. This is also why we need to go5154 // through a raw pointer here.5155 let slice: *mut [T] = self;5156 let mut arr: MaybeUninit<[&mut I::Output; N]> = MaybeUninit::uninit();5157 let arr_ptr = arr.as_mut_ptr();5158 5159 // SAFETY: We expect `indices` to contain disjunct values that are5160 // in bounds of `self`.5161 unsafe {5162 for i in 0..N {5163 let idx = indices.get_unchecked(i).clone();5164 arr_ptr.cast::<&mut I::Output>().add(i).write(&mut *slice.get_unchecked_mut(idx));5165 }5166 arr.assume_init()5167 }5168 }5169 5170 /// Returns mutable references to many indices at once.5171 ///5172 /// An index can be either a `usize`, a [`Range`] or a [`RangeInclusive`]. Note5173 /// that this method takes an array, so all indices must be of the same type.5174 /// If passed an array of `usize`s this method gives back an array of mutable references5175 /// to single elements, while if passed an array of ranges it gives back an array of5176 /// mutable references to slices.5177 ///5178 /// Returns an error if any index is out-of-bounds, or if there are overlapping indices.5179 /// An empty range is not considered to overlap if it is located at the beginning or at5180 /// the end of another range, but is considered to overlap if it is located in the middle.5181 ///5182 /// This method does a O(n^2) check to check that there are no overlapping indices, so be careful5183 /// when passing many indices.5184 ///5185 /// # Examples5186 ///5187 /// ```5188 /// let v = &mut [1, 2, 3];5189 /// if let Ok([a, b]) = v.get_disjoint_mut([0, 2]) {5190 /// *a = 413;5191 /// *b = 612;5192 /// }5193 /// assert_eq!(v, &[413, 2, 612]);5194 ///5195 /// if let Ok([a, b]) = v.get_disjoint_mut([0..1, 1..3]) {5196 /// a[0] = 8;5197 /// b[0] = 88;5198 /// b[1] = 888;5199 /// }5200 /// assert_eq!(v, &[8, 88, 888]);5201 ///5202 /// if let Ok([a, b]) = v.get_disjoint_mut([1..=2, 0..=0]) {5203 /// a[0] = 11;5204 /// a[1] = 111;5205 /// b[0] = 1;5206 /// }5207 /// assert_eq!(v, &[1, 11, 111]);5208 /// ```5209 #[stable(feature = "get_many_mut", since = "1.86.0")]5210 #[inline]5211 pub fn get_disjoint_mut<I, const N: usize>(5212 &mut self,5213 indices: [I; N],5214 ) -> Result<[&mut I::Output; N], GetDisjointMutError>5215 where5216 I: GetDisjointMutIndex + SliceIndex<Self>,5217 {5218 get_disjoint_check_valid(&indices, self.len())?;5219 // SAFETY: The `get_disjoint_check_valid()` call checked that all indices5220 // are disjunct and in bounds.5221 unsafe { Ok(self.get_disjoint_unchecked_mut(indices)) }5222 }5223 5224 /// Returns the index that an element reference points to.5225 ///5226 /// Returns `None` if `element` does not point to the start of an element within the slice.5227 ///5228 /// This method is useful for extending slice iterators like [`slice::split`].5229 ///5230 /// Note that this uses pointer arithmetic and **does not compare elements**.5231 /// To find the index of an element via comparison, use5232 /// [`.iter().position()`](crate::iter::Iterator::position) instead.5233 ///5234 /// # Panics5235 /// Panics if `T` is zero-sized.5236 ///5237 /// # Examples5238 /// Basic usage:5239 /// ```5240 /// let nums: &[u32] = &[1, 7, 1, 1];5241 /// let num = &nums[2];5242 ///5243 /// assert_eq!(num, &1);5244 /// assert_eq!(nums.element_offset(num), Some(2));5245 /// ```5246 /// Returning `None` with an unaligned element:5247 /// ```5248 /// let arr: &[[u32; 2]] = &[[0, 1], [2, 3]];5249 /// let flat_arr: &[u32] = arr.as_flattened();5250 ///5251 /// let ok_elm: &[u32; 2] = flat_arr[0..2].try_into().unwrap();5252 /// let weird_elm: &[u32; 2] = flat_arr[1..3].try_into().unwrap();5253 ///5254 /// assert_eq!(ok_elm, &[0, 1]);5255 /// assert_eq!(weird_elm, &[1, 2]);5256 ///5257 /// assert_eq!(arr.element_offset(ok_elm), Some(0)); // Points to element 05258 /// assert_eq!(arr.element_offset(weird_elm), None); // Points between element 0 and 15259 /// ```5260 #[must_use]5261 #[stable(feature = "element_offset", since = "1.94.0")]5262 pub fn element_offset(&self, element: &T) -> Option<usize> {5263 if T::IS_ZST {5264 panic!("elements are zero-sized");5265 }5266 5267 let self_start = self.as_ptr().addr();5268 let elem_start = ptr::from_ref(element).addr();5269 5270 let byte_offset = elem_start.wrapping_sub(self_start);5271 5272 if !byte_offset.is_multiple_of(size_of::<T>()) {5273 return None;5274 }5275 5276 let offset = byte_offset / size_of::<T>();5277 5278 if offset < self.len() { Some(offset) } else { None }5279 }5280 5281 /// Returns the range of indices that a subslice points to.5282 ///5283 /// Returns `None` if `subslice` does not point within the slice or if it is not aligned with the5284 /// elements in the slice.5285 ///5286 /// This method **does not compare elements**. Instead, this method finds the location in the slice that5287 /// `subslice` was obtained from. To find the index of a subslice via comparison, instead use5288 /// [`.windows()`](slice::windows)[`.position()`](crate::iter::Iterator::position).5289 ///5290 /// This method is useful for extending slice iterators like [`slice::split`].5291 ///5292 /// Note that this may return a false positive (either `Some(0..0)` or `Some(self.len()..self.len())`)5293 /// if `subslice` has a length of zero and points to the beginning or end of another, separate, slice.5294 ///5295 /// # Panics5296 /// Panics if `T` is zero-sized.5297 ///5298 /// # Examples5299 /// Basic usage:5300 /// ```5301 /// #![feature(substr_range)]5302 /// use core::range::Range;5303 ///5304 /// let nums = &[0, 5, 10, 0, 0, 5];5305 ///5306 /// let mut iter = nums5307 /// .split(|t| *t == 0)5308 /// .map(|n| nums.subslice_range(n).unwrap());5309 ///5310 /// assert_eq!(iter.next(), Some(Range { start: 0, end: 0 }));5311 /// assert_eq!(iter.next(), Some(Range { start: 1, end: 3 }));5312 /// assert_eq!(iter.next(), Some(Range { start: 4, end: 4 }));5313 /// assert_eq!(iter.next(), Some(Range { start: 5, end: 6 }));5314 /// ```5315 #[must_use]5316 #[unstable(feature = "substr_range", issue = "126769")]5317 pub fn subslice_range(&self, subslice: &[T]) -> Option<core::range::Range<usize>> {5318 if T::IS_ZST {5319 panic!("elements are zero-sized");5320 }5321 5322 let self_start = self.as_ptr().addr();5323 let subslice_start = subslice.as_ptr().addr();5324 5325 let byte_start = subslice_start.wrapping_sub(self_start);5326 5327 if !byte_start.is_multiple_of(size_of::<T>()) {5328 return None;5329 }5330 5331 let start = byte_start / size_of::<T>();5332 let end = start.wrapping_add(subslice.len());5333 5334 if start <= self.len() && end <= self.len() {5335 Some(core::range::Range { start, end })5336 } else {5337 None5338 }5339 }5340 5341 /// Returns the same slice `&[T]`.5342 ///5343 /// This method is redundant when used directly on `&[T]`, but5344 /// it helps dereferencing other "container" types to slices,5345 /// for example `Box<[T]>` or `Arc<[T]>`.5346 #[inline]5347 #[unstable(feature = "str_as_str", issue = "130366")]5348 pub const fn as_slice(&self) -> &[T] {5349 self5350 }5351 5352 /// Returns the same slice `&mut [T]`.5353 ///5354 /// This method is redundant when used directly on `&mut [T]`, but5355 /// it helps dereferencing other "container" types to slices,5356 /// for example `Box<[T]>` or `MutexGuard<[T]>`.5357 #[inline]5358 #[unstable(feature = "str_as_str", issue = "130366")]5359 pub const fn as_mut_slice(&mut self) -> &mut [T] {5360 self5361 }5362 }5363 5364 impl<T> [MaybeUninit<T>] {5365 /// Transmutes the mutable uninitialized slice to a mutable uninitialized slice of5366 /// another type, ensuring alignment of the types is maintained.5367 ///5368 /// This is a safe wrapper around [`slice::align_to_mut`], so inherits the same5369 /// guarantees as that method.5370 ///5371 /// # Examples5372 ///5373 /// ```5374 /// #![feature(align_to_uninit_mut)]5375 /// use std::mem::MaybeUninit;5376 ///5377 /// pub struct BumpAllocator<'scope> {5378 /// memory: &'scope mut [MaybeUninit<u8>],5379 /// }5380 ///5381 /// impl<'scope> BumpAllocator<'scope> {5382 /// pub fn new(memory: &'scope mut [MaybeUninit<u8>]) -> Self {5383 /// Self { memory }5384 /// }5385 /// pub fn try_alloc_uninit<T>(&mut self) -> Option<&'scope mut MaybeUninit<T>> {5386 /// let first_end = self.memory.as_ptr().align_offset(align_of::<T>()) + size_of::<T>();5387 /// let prefix = self.memory.split_off_mut(..first_end)?;5388 /// Some(&mut prefix.align_to_uninit_mut::<T>().1[0])5389 /// }5390 /// pub fn try_alloc_u32(&mut self, value: u32) -> Option<&'scope mut u32> {5391 /// let uninit = self.try_alloc_uninit()?;5392 /// Some(uninit.write(value))5393 /// }5394 /// }5395 ///5396 /// let mut memory = [MaybeUninit::<u8>::uninit(); 10];5397 /// let mut allocator = BumpAllocator::new(&mut memory);5398 /// let v = allocator.try_alloc_u32(42);5399 /// assert_eq!(v, Some(&mut 42));5400 /// ```5401 #[unstable(feature = "align_to_uninit_mut", issue = "139062")]5402 #[inline]5403 #[must_use]5404 pub fn align_to_uninit_mut<U>(&mut self) -> (&mut Self, &mut [MaybeUninit<U>], &mut Self) {5405 // SAFETY: `MaybeUninit` is transparent. Correct size and alignment are guaranteed by5406 // `align_to_mut` itself. Therefore the only thing that we have to ensure for a safe5407 // `transmute` is that the values are valid for the types involved. But for `MaybeUninit`5408 // any values are valid, so this operation is safe.5409 unsafe { self.align_to_mut() }5410 }5411 }5412 5413 impl<T, const N: usize> [[T; N]] {5414 /// Takes a `&[[T; N]]`, and flattens it to a `&[T]`.5415 ///5416 /// For the opposite operation, see [`as_chunks`] and [`as_rchunks`].5417 ///5418 /// [`as_chunks`]: slice::as_chunks5419 /// [`as_rchunks`]: slice::as_rchunks5420 ///5421 /// # Panics5422 ///5423 /// This panics if the length of the resulting slice would overflow a `usize`.5424 ///5425 /// This is only possible when flattening a slice of arrays of zero-sized5426 /// types, and thus tends to be irrelevant in practice. If5427 /// `size_of::<T>() > 0`, this will never panic.5428 ///5429 /// # Examples5430 ///5431 /// ```5432 /// assert_eq!([[1, 2, 3], [4, 5, 6]].as_flattened(), &[1, 2, 3, 4, 5, 6]);5433 ///5434 /// assert_eq!(5435 /// [[1, 2, 3], [4, 5, 6]].as_flattened(),5436 /// [[1, 2], [3, 4], [5, 6]].as_flattened(),5437 /// );5438 ///5439 /// let slice_of_empty_arrays: &[[i32; 0]] = &[[], [], [], [], []];5440 /// assert!(slice_of_empty_arrays.as_flattened().is_empty());5441 ///5442 /// let empty_slice_of_arrays: &[[u32; 10]] = &[];5443 /// assert!(empty_slice_of_arrays.as_flattened().is_empty());5444 /// ```5445 #[stable(feature = "slice_flatten", since = "1.80.0")]5446 #[rustc_const_stable(feature = "const_slice_flatten", since = "1.87.0")]5447 pub const fn as_flattened(&self) -> &[T] {5448 let len = if T::IS_ZST {5449 self.len().checked_mul(N).expect("slice len overflow")5450 } else {5451 // SAFETY: `self.len() * N` cannot overflow because `self` is5452 // already in the address space.5453 unsafe { self.len().unchecked_mul(N) }5454 };5455 // SAFETY: `[T]` is layout-identical to `[T; N]`5456 unsafe { from_raw_parts(self.as_ptr().cast(), len) }5457 }5458 5459 /// Takes a `&mut [[T; N]]`, and flattens it to a `&mut [T]`.5460 ///5461 /// For the opposite operation, see [`as_chunks_mut`] and [`as_rchunks_mut`].5462 ///5463 /// [`as_chunks_mut`]: slice::as_chunks_mut5464 /// [`as_rchunks_mut`]: slice::as_rchunks_mut5465 ///5466 /// # Panics5467 ///5468 /// This panics if the length of the resulting slice would overflow a `usize`.5469 ///5470 /// This is only possible when flattening a slice of arrays of zero-sized5471 /// types, and thus tends to be irrelevant in practice. If5472 /// `size_of::<T>() > 0`, this will never panic.5473 ///5474 /// # Examples5475 ///5476 /// ```5477 /// fn add_5_to_all(slice: &mut [i32]) {5478 /// for i in slice {5479 /// *i += 5;5480 /// }5481 /// }5482 ///5483 /// let mut array = [[1, 2, 3], [4, 5, 6], [7, 8, 9]];5484 /// add_5_to_all(array.as_flattened_mut());5485 /// assert_eq!(array, [[6, 7, 8], [9, 10, 11], [12, 13, 14]]);5486 /// ```5487 #[stable(feature = "slice_flatten", since = "1.80.0")]5488 #[rustc_const_stable(feature = "const_slice_flatten", since = "1.87.0")]5489 pub const fn as_flattened_mut(&mut self) -> &mut [T] {5490 let len = if T::IS_ZST {5491 self.len().checked_mul(N).expect("slice len overflow")5492 } else {5493 // SAFETY: `self.len() * N` cannot overflow because `self` is5494 // already in the address space.5495 unsafe { self.len().unchecked_mul(N) }5496 };5497 // SAFETY: `[T]` is layout-identical to `[T; N]`5498 unsafe { from_raw_parts_mut(self.as_mut_ptr().cast(), len) }5499 }5500 }5501 5502 impl [f32] {5503 /// Sorts the slice of floats.5504 ///5505 /// This sort is in-place (i.e. does not allocate), *O*(*n* \* log(*n*)) worst-case, and uses5506 /// the ordering defined by [`f32::total_cmp`].5507 ///5508 /// # Current implementation5509 ///5510 /// This uses the same sorting algorithm as [`sort_unstable_by`](slice::sort_unstable_by).5511 ///5512 /// # Examples5513 ///5514 /// ```5515 /// #![feature(sort_floats)]5516 /// let mut v = [2.6, -5e-8, f32::NAN, 8.29, f32::INFINITY, -1.0, 0.0, -f32::INFINITY, -0.0];5517 ///5518 /// v.sort_floats();5519 /// let sorted = [-f32::INFINITY, -1.0, -5e-8, -0.0, 0.0, 2.6, 8.29, f32::INFINITY, f32::NAN];5520 /// assert_eq!(&v[..8], &sorted[..8]);5521 /// assert!(v[8].is_nan());5522 /// ```5523 #[unstable(feature = "sort_floats", issue = "93396")]5524 #[inline]5525 pub fn sort_floats(&mut self) {5526 self.sort_unstable_by(f32::total_cmp);5527 }5528 }5529 5530 impl [f64] {5531 /// Sorts the slice of floats.5532 ///5533 /// This sort is in-place (i.e. does not allocate), *O*(*n* \* log(*n*)) worst-case, and uses5534 /// the ordering defined by [`f64::total_cmp`].5535 ///5536 /// # Current implementation5537 ///5538 /// This uses the same sorting algorithm as [`sort_unstable_by`](slice::sort_unstable_by).5539 ///5540 /// # Examples5541 ///5542 /// ```5543 /// #![feature(sort_floats)]5544 /// let mut v = [2.6, -5e-8, f64::NAN, 8.29, f64::INFINITY, -1.0, 0.0, -f64::INFINITY, -0.0];5545 ///5546 /// v.sort_floats();5547 /// let sorted = [-f64::INFINITY, -1.0, -5e-8, -0.0, 0.0, 2.6, 8.29, f64::INFINITY, f64::NAN];5548 /// assert_eq!(&v[..8], &sorted[..8]);5549 /// assert!(v[8].is_nan());5550 /// ```5551 #[unstable(feature = "sort_floats", issue = "93396")]5552 #[inline]5553 pub fn sort_floats(&mut self) {5554 self.sort_unstable_by(f64::total_cmp);5555 }5556 }5557 5558 /// Copies `src` to `dest`.5559 ///5560 /// # Safety5561 /// `T` must implement one of `Copy` or `TrivialClone`.5562 #[track_caller]5563 const unsafe fn copy_from_slice_impl<T: Clone>(dest: &mut [T], src: &[T]) {5564 // The panic code path was put into a cold function to not bloat the5565 // call site.5566 #[cfg_attr(not(panic = "immediate-abort"), inline(never), cold)]5567 #[cfg_attr(panic = "immediate-abort", inline)]5568 #[track_caller]5569 const fn len_mismatch_fail(dst_len: usize, src_len: usize) -> ! {5570 const_panic!(5571 "copy_from_slice: source slice length does not match destination slice length",5572 "copy_from_slice: source slice length ({src_len}) does not match destination slice length ({dst_len})",5573 src_len: usize,5574 dst_len: usize,5575 )5576 }5577 5578 if dest.len() != src.len() {5579 len_mismatch_fail(dest.len(), src.len());5580 }5581 5582 // SAFETY: `self` is valid for `self.len()` elements by definition, and `src` was5583 // checked to have the same length. The slices cannot overlap because5584 // mutable references are exclusive.5585 unsafe {5586 ptr::copy_nonoverlapping(src.as_ptr(), dest.as_mut_ptr(), dest.len());5587 }5588 }5589 5590 #[rustc_const_unstable(feature = "const_clone", issue = "142757")]5591 const trait CloneFromSpec<T> {5592 fn spec_clone_from(&mut self, src: &[T])5593 where5594 T: [const] Destruct;5595 }5596 5597 #[rustc_const_unstable(feature = "const_clone", issue = "142757")]5598 const impl<T> CloneFromSpec<T> for [T]5599 where5600 T: [const] Clone + [const] Destruct,5601 {5602 #[track_caller]5603 default fn spec_clone_from(&mut self, src: &[T]) {5604 assert!(self.len() == src.len(), "destination and source slices have different lengths");5605 // NOTE: We need to explicitly slice them to the same length5606 // to make it easier for the optimizer to elide bounds checking.5607 // But since it can't be relied on we also have an explicit specialization for T: Copy.5608 let len = self.len();5609 let src = &src[..len];5610 // FIXME(const_hack): make this a `for idx in 0..self.len()` loop.5611 let mut idx = 0;5612 while idx < self.len() {5613 self[idx].clone_from(&src[idx]);5614 idx += 1;5615 }5616 }5617 }5618 5619 #[rustc_const_unstable(feature = "const_clone", issue = "142757")]5620 const impl<T> CloneFromSpec<T> for [T]5621 where5622 T: [const] TrivialClone + [const] Destruct,5623 {5624 #[track_caller]5625 fn spec_clone_from(&mut self, src: &[T]) {5626 // SAFETY: `T` implements `TrivialClone`.5627 unsafe {5628 copy_from_slice_impl(self, src);5629 }5630 }5631 }5632 5633 #[stable(feature = "rust1", since = "1.0.0")]5634 #[rustc_const_unstable(feature = "const_default", issue = "143894")]5635 const impl<T> Default for &[T] {5636 /// Creates an empty slice.5637 fn default() -> Self {5638 &[]5639 }5640 }5641 5642 #[stable(feature = "mut_slice_default", since = "1.5.0")]5643 #[rustc_const_unstable(feature = "const_default", issue = "143894")]5644 const impl<T> Default for &mut [T] {5645 /// Creates a mutable empty slice.5646 fn default() -> Self {5647 &mut []5648 }5649 }5650 5651 #[unstable(feature = "slice_pattern", reason = "stopgap trait for slice patterns", issue = "56345")]5652 /// Patterns in slices - currently, only used by `strip_prefix` and `strip_suffix`. At a future5653 /// point, we hope to generalise `core::str::Pattern` (which at the time of writing is limited to5654 /// `str`) to slices, and then this trait will be replaced or abolished.5655 pub trait SlicePattern {5656 /// The element type of the slice being matched on.5657 type Item;5658 5659 /// Currently, the consumers of `SlicePattern` need a slice.5660 fn as_slice(&self) -> &[Self::Item];5661 }5662 5663 #[stable(feature = "slice_strip", since = "1.51.0")]5664 impl<T> SlicePattern for [T] {5665 type Item = T;5666 5667 #[inline]5668 fn as_slice(&self) -> &[Self::Item] {5669 self5670 }5671 }5672 5673 #[stable(feature = "slice_strip", since = "1.51.0")]5674 impl<T, const N: usize> SlicePattern for [T; N] {5675 type Item = T;5676 5677 #[inline]5678 fn as_slice(&self) -> &[Self::Item] {5679 self5680 }5681 }5682 5683 /// This checks every index against each other, and against `len`.5684 ///5685 /// This will do `binomial(N + 1, 2) = N * (N + 1) / 2 = 0, 1, 3, 6, 10, ..`5686 /// comparison operations.5687 #[inline]5688 fn get_disjoint_check_valid<I: GetDisjointMutIndex, const N: usize>(5689 indices: &[I; N],5690 len: usize,5691 ) -> Result<(), GetDisjointMutError> {5692 // NB: The optimizer should inline the loops into a sequence5693 // of instructions without additional branching.5694 for (i, idx) in indices.iter().enumerate() {5695 if !idx.is_in_bounds(len) {5696 return Err(GetDisjointMutError::IndexOutOfBounds);5697 }5698 for idx2 in &indices[..i] {5699 if idx.is_overlapping(idx2) {5700 return Err(GetDisjointMutError::OverlappingIndices);5701 }5702 }5703 }5704 Ok(())5705 }5706 5707 /// The error type returned by [`get_disjoint_mut`][`slice::get_disjoint_mut`].5708 ///5709 /// It indicates one of two possible errors:5710 /// - An index is out-of-bounds.5711 /// - The same index appeared multiple times in the array5712 /// (or different but overlapping indices when ranges are provided).5713 ///5714 /// # Examples5715 ///5716 /// ```5717 /// use std::slice::GetDisjointMutError;5718 ///5719 /// let v = &mut [1, 2, 3];5720 /// assert_eq!(v.get_disjoint_mut([0, 999]), Err(GetDisjointMutError::IndexOutOfBounds));5721 /// assert_eq!(v.get_disjoint_mut([1, 1]), Err(GetDisjointMutError::OverlappingIndices));5722 /// ```5723 #[stable(feature = "get_many_mut", since = "1.86.0")]5724 #[derive(Debug, Clone, PartialEq, Eq)]5725 pub enum GetDisjointMutError {5726 /// An index provided was out-of-bounds for the slice.5727 IndexOutOfBounds,5728 /// Two indices provided were overlapping.5729 OverlappingIndices,5730 }5731 5732 #[stable(feature = "get_many_mut", since = "1.86.0")]5733 impl fmt::Display for GetDisjointMutError {5734 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {5735 let msg = match self {5736 GetDisjointMutError::IndexOutOfBounds => "an index is out of bounds",5737 GetDisjointMutError::OverlappingIndices => "there were overlapping indices",5738 };5739 fmt::Display::fmt(msg, f)5740 }5741 }5742 5743 mod private_get_disjoint_mut_index {5744 use super::{Range, RangeInclusive, range};5745 5746 #[unstable(feature = "get_disjoint_mut_helpers", issue = "none")]5747 pub trait Sealed {}5748 5749 #[unstable(feature = "get_disjoint_mut_helpers", issue = "none")]5750 impl Sealed for usize {}5751 #[unstable(feature = "get_disjoint_mut_helpers", issue = "none")]5752 impl Sealed for Range<usize> {}5753 #[unstable(feature = "get_disjoint_mut_helpers", issue = "none")]5754 impl Sealed for RangeInclusive<usize> {}5755 #[unstable(feature = "get_disjoint_mut_helpers", issue = "none")]5756 impl Sealed for range::Range<usize> {}5757 #[unstable(feature = "get_disjoint_mut_helpers", issue = "none")]5758 impl Sealed for range::RangeInclusive<usize> {}5759 }5760 5761 /// A helper trait for `<[T]>::get_disjoint_mut()`.5762 ///5763 /// # Safety5764 ///5765 /// If `is_in_bounds()` returns `true` and `is_overlapping()` returns `false`,5766 /// it must be safe to index the slice with the indices.5767 #[unstable(feature = "get_disjoint_mut_helpers", issue = "none")]5768 pub unsafe trait GetDisjointMutIndex:5769 Clone + private_get_disjoint_mut_index::Sealed5770 {5771 /// Returns `true` if `self` is in bounds for `len` slice elements.5772 #[unstable(feature = "get_disjoint_mut_helpers", issue = "none")]5773 fn is_in_bounds(&self, len: usize) -> bool;5774 5775 /// Returns `true` if `self` overlaps with `other`.5776 ///5777 /// Note that we don't consider zero-length ranges to overlap at the beginning or the end,5778 /// but do consider them to overlap in the middle.5779 #[unstable(feature = "get_disjoint_mut_helpers", issue = "none")]5780 fn is_overlapping(&self, other: &Self) -> bool;5781 }5782 5783 #[unstable(feature = "get_disjoint_mut_helpers", issue = "none")]5784 // SAFETY: We implement `is_in_bounds()` and `is_overlapping()` correctly.5785 unsafe impl GetDisjointMutIndex for usize {5786 #[inline]5787 fn is_in_bounds(&self, len: usize) -> bool {5788 *self < len5789 }5790 5791 #[inline]5792 fn is_overlapping(&self, other: &Self) -> bool {5793 *self == *other5794 }5795 }5796 5797 #[unstable(feature = "get_disjoint_mut_helpers", issue = "none")]5798 // SAFETY: We implement `is_in_bounds()` and `is_overlapping()` correctly.5799 unsafe impl GetDisjointMutIndex for Range<usize> {5800 #[inline]5801 fn is_in_bounds(&self, len: usize) -> bool {5802 (self.start <= self.end) & (self.end <= len)5803 }5804 5805 #[inline]5806 fn is_overlapping(&self, other: &Self) -> bool {5807 (self.start < other.end) & (other.start < self.end)5808 }5809 }5810 5811 #[unstable(feature = "get_disjoint_mut_helpers", issue = "none")]5812 // SAFETY: We implement `is_in_bounds()` and `is_overlapping()` correctly.5813 unsafe impl GetDisjointMutIndex for RangeInclusive<usize> {5814 #[inline]5815 fn is_in_bounds(&self, len: usize) -> bool {5816 (self.start <= self.end) & (self.end < len)5817 }5818 5819 #[inline]5820 fn is_overlapping(&self, other: &Self) -> bool {5821 (self.start <= other.end) & (other.start <= self.end)5822 }5823 }5824 5825 #[unstable(feature = "get_disjoint_mut_helpers", issue = "none")]5826 // SAFETY: We implement `is_in_bounds()` and `is_overlapping()` correctly.5827 unsafe impl GetDisjointMutIndex for range::Range<usize> {5828 #[inline]5829 fn is_in_bounds(&self, len: usize) -> bool {5830 Range::from(*self).is_in_bounds(len)5831 }5832 5833 #[inline]5834 fn is_overlapping(&self, other: &Self) -> bool {5835 Range::from(*self).is_overlapping(&Range::from(*other))5836 }5837 }5838 5839 #[unstable(feature = "get_disjoint_mut_helpers", issue = "none")]5840 // SAFETY: We implement `is_in_bounds()` and `is_overlapping()` correctly.5841 unsafe impl GetDisjointMutIndex for range::RangeInclusive<usize> {5842 #[inline]5843 fn is_in_bounds(&self, len: usize) -> bool {5844 RangeInclusive::from(*self).is_in_bounds(len)5845 }5846 5847 #[inline]5848 fn is_overlapping(&self, other: &Self) -> bool {5849 RangeInclusive::from(*self).is_overlapping(&RangeInclusive::from(*other))5850 }5851 }Reference details
| commit | 14210df0e27ccd7d9e6a05b8085cbd438e4bbc65 |
|---|---|
| sha256 | 354992a6a3d69a0185eef9044a07ea5180e767bdb467aef55e69ee3d44317840 |
| url | https://raw.githubusercontent.com/rust-lang/rust/14210df0e27ccd7d9e6a05b8085cbd438e4bbc65/library/core/src/slice/mod.rs |