]> git.lizzy.rs Git - rust.git/blob - library/core/src/slice/mod.rs
Unify Opaque/Projection handling in region outlives code
[rust.git] / library / core / src / slice / mod.rs
1 //! Slice management and manipulation.
2 //!
3 //! For more details see [`std::slice`].
4 //!
5 //! [`std::slice`]: ../../std/slice/index.html
6
7 #![stable(feature = "rust1", since = "1.0.0")]
8
9 use crate::cmp::Ordering::{self, Greater, Less};
10 use crate::fmt;
11 use crate::intrinsics::{assert_unsafe_precondition, exact_div};
12 use crate::marker::Copy;
13 use crate::mem::{self, SizedTypeProperties};
14 use crate::num::NonZeroUsize;
15 use crate::ops::{Bound, FnMut, OneSidedRange, Range, RangeBounds};
16 use crate::option::Option;
17 use crate::option::Option::{None, Some};
18 use crate::ptr;
19 use crate::result::Result;
20 use crate::result::Result::{Err, Ok};
21 use crate::simd::{self, Simd};
22 use crate::slice;
23
24 #[unstable(
25     feature = "slice_internals",
26     issue = "none",
27     reason = "exposed from core to be reused in std; use the memchr crate"
28 )]
29 /// Pure rust memchr implementation, taken from rust-memchr
30 pub mod memchr;
31
32 mod ascii;
33 mod cmp;
34 mod index;
35 mod iter;
36 mod raw;
37 mod rotate;
38 mod sort;
39 mod specialize;
40
41 #[stable(feature = "rust1", since = "1.0.0")]
42 pub use iter::{Chunks, ChunksMut, Windows};
43 #[stable(feature = "rust1", since = "1.0.0")]
44 pub use iter::{Iter, IterMut};
45 #[stable(feature = "rust1", since = "1.0.0")]
46 pub use iter::{RSplitN, RSplitNMut, Split, SplitMut, SplitN, SplitNMut};
47
48 #[stable(feature = "slice_rsplit", since = "1.27.0")]
49 pub use iter::{RSplit, RSplitMut};
50
51 #[stable(feature = "chunks_exact", since = "1.31.0")]
52 pub use iter::{ChunksExact, ChunksExactMut};
53
54 #[stable(feature = "rchunks", since = "1.31.0")]
55 pub use iter::{RChunks, RChunksExact, RChunksExactMut, RChunksMut};
56
57 #[unstable(feature = "array_chunks", issue = "74985")]
58 pub use iter::{ArrayChunks, ArrayChunksMut};
59
60 #[unstable(feature = "array_windows", issue = "75027")]
61 pub use iter::ArrayWindows;
62
63 #[unstable(feature = "slice_group_by", issue = "80552")]
64 pub use iter::{GroupBy, GroupByMut};
65
66 #[stable(feature = "split_inclusive", since = "1.51.0")]
67 pub use iter::{SplitInclusive, SplitInclusiveMut};
68
69 #[stable(feature = "rust1", since = "1.0.0")]
70 pub use raw::{from_raw_parts, from_raw_parts_mut};
71
72 #[stable(feature = "from_ref", since = "1.28.0")]
73 pub use raw::{from_mut, from_ref};
74
75 #[unstable(feature = "slice_from_ptr_range", issue = "89792")]
76 pub use raw::{from_mut_ptr_range, from_ptr_range};
77
78 // This function is public only because there is no other way to unit test heapsort.
79 #[unstable(feature = "sort_internals", reason = "internal to sort module", issue = "none")]
80 pub use sort::heapsort;
81
82 #[stable(feature = "slice_get_slice", since = "1.28.0")]
83 pub use index::SliceIndex;
84
85 #[unstable(feature = "slice_range", issue = "76393")]
86 pub use index::range;
87
88 #[stable(feature = "inherent_ascii_escape", since = "1.60.0")]
89 pub use ascii::EscapeAscii;
90
91 /// Calculates the direction and split point of a one-sided range.
92 ///
93 /// This is a helper function for `take` and `take_mut` that returns
94 /// the direction of the split (front or back) as well as the index at
95 /// which to split. Returns `None` if the split index would overflow.
96 #[inline]
97 fn split_point_of(range: impl OneSidedRange<usize>) -> Option<(Direction, usize)> {
98     use Bound::*;
99
100     Some(match (range.start_bound(), range.end_bound()) {
101         (Unbounded, Excluded(i)) => (Direction::Front, *i),
102         (Unbounded, Included(i)) => (Direction::Front, i.checked_add(1)?),
103         (Excluded(i), Unbounded) => (Direction::Back, i.checked_add(1)?),
104         (Included(i), Unbounded) => (Direction::Back, *i),
105         _ => unreachable!(),
106     })
107 }
108
109 enum Direction {
110     Front,
111     Back,
112 }
113
114 #[cfg(not(test))]
115 impl<T> [T] {
116     /// Returns the number of elements in the slice.
117     ///
118     /// # Examples
119     ///
120     /// ```
121     /// let a = [1, 2, 3];
122     /// assert_eq!(a.len(), 3);
123     /// ```
124     #[lang = "slice_len_fn"]
125     #[stable(feature = "rust1", since = "1.0.0")]
126     #[rustc_const_stable(feature = "const_slice_len", since = "1.39.0")]
127     #[rustc_allow_const_fn_unstable(ptr_metadata)]
128     #[inline]
129     #[must_use]
130     pub const fn len(&self) -> usize {
131         ptr::metadata(self)
132     }
133
134     /// Returns `true` if the slice has a length of 0.
135     ///
136     /// # Examples
137     ///
138     /// ```
139     /// let a = [1, 2, 3];
140     /// assert!(!a.is_empty());
141     /// ```
142     #[stable(feature = "rust1", since = "1.0.0")]
143     #[rustc_const_stable(feature = "const_slice_is_empty", since = "1.39.0")]
144     #[inline]
145     #[must_use]
146     pub const fn is_empty(&self) -> bool {
147         self.len() == 0
148     }
149
150     /// Returns the first element of the slice, or `None` if it is empty.
151     ///
152     /// # Examples
153     ///
154     /// ```
155     /// let v = [10, 40, 30];
156     /// assert_eq!(Some(&10), v.first());
157     ///
158     /// let w: &[i32] = &[];
159     /// assert_eq!(None, w.first());
160     /// ```
161     #[stable(feature = "rust1", since = "1.0.0")]
162     #[rustc_const_stable(feature = "const_slice_first_last_not_mut", since = "1.56.0")]
163     #[inline]
164     #[must_use]
165     pub const fn first(&self) -> Option<&T> {
166         if let [first, ..] = self { Some(first) } else { None }
167     }
168
169     /// Returns a mutable pointer to the first element of the slice, or `None` if it is empty.
170     ///
171     /// # Examples
172     ///
173     /// ```
174     /// let x = &mut [0, 1, 2];
175     ///
176     /// if let Some(first) = x.first_mut() {
177     ///     *first = 5;
178     /// }
179     /// assert_eq!(x, &[5, 1, 2]);
180     /// ```
181     #[stable(feature = "rust1", since = "1.0.0")]
182     #[rustc_const_unstable(feature = "const_slice_first_last", issue = "83570")]
183     #[inline]
184     #[must_use]
185     pub const fn first_mut(&mut self) -> Option<&mut T> {
186         if let [first, ..] = self { Some(first) } else { None }
187     }
188
189     /// Returns the first and all the rest of the elements of the slice, or `None` if it is empty.
190     ///
191     /// # Examples
192     ///
193     /// ```
194     /// let x = &[0, 1, 2];
195     ///
196     /// if let Some((first, elements)) = x.split_first() {
197     ///     assert_eq!(first, &0);
198     ///     assert_eq!(elements, &[1, 2]);
199     /// }
200     /// ```
201     #[stable(feature = "slice_splits", since = "1.5.0")]
202     #[rustc_const_stable(feature = "const_slice_first_last_not_mut", since = "1.56.0")]
203     #[inline]
204     #[must_use]
205     pub const fn split_first(&self) -> Option<(&T, &[T])> {
206         if let [first, tail @ ..] = self { Some((first, tail)) } else { None }
207     }
208
209     /// Returns the first and all the rest of the elements of the slice, or `None` if it is empty.
210     ///
211     /// # Examples
212     ///
213     /// ```
214     /// let x = &mut [0, 1, 2];
215     ///
216     /// if let Some((first, elements)) = x.split_first_mut() {
217     ///     *first = 3;
218     ///     elements[0] = 4;
219     ///     elements[1] = 5;
220     /// }
221     /// assert_eq!(x, &[3, 4, 5]);
222     /// ```
223     #[stable(feature = "slice_splits", since = "1.5.0")]
224     #[rustc_const_unstable(feature = "const_slice_first_last", issue = "83570")]
225     #[inline]
226     #[must_use]
227     pub const fn split_first_mut(&mut self) -> Option<(&mut T, &mut [T])> {
228         if let [first, tail @ ..] = self { Some((first, tail)) } else { None }
229     }
230
231     /// Returns the last and all the rest of the elements of the slice, or `None` if it is empty.
232     ///
233     /// # Examples
234     ///
235     /// ```
236     /// let x = &[0, 1, 2];
237     ///
238     /// if let Some((last, elements)) = x.split_last() {
239     ///     assert_eq!(last, &2);
240     ///     assert_eq!(elements, &[0, 1]);
241     /// }
242     /// ```
243     #[stable(feature = "slice_splits", since = "1.5.0")]
244     #[rustc_const_stable(feature = "const_slice_first_last_not_mut", since = "1.56.0")]
245     #[inline]
246     #[must_use]
247     pub const fn split_last(&self) -> Option<(&T, &[T])> {
248         if let [init @ .., last] = self { Some((last, init)) } else { None }
249     }
250
251     /// Returns the last and all the rest of the elements of the slice, or `None` if it is empty.
252     ///
253     /// # Examples
254     ///
255     /// ```
256     /// let x = &mut [0, 1, 2];
257     ///
258     /// if let Some((last, elements)) = x.split_last_mut() {
259     ///     *last = 3;
260     ///     elements[0] = 4;
261     ///     elements[1] = 5;
262     /// }
263     /// assert_eq!(x, &[4, 5, 3]);
264     /// ```
265     #[stable(feature = "slice_splits", since = "1.5.0")]
266     #[rustc_const_unstable(feature = "const_slice_first_last", issue = "83570")]
267     #[inline]
268     #[must_use]
269     pub const fn split_last_mut(&mut self) -> Option<(&mut T, &mut [T])> {
270         if let [init @ .., last] = self { Some((last, init)) } else { None }
271     }
272
273     /// Returns the last element of the slice, or `None` if it is empty.
274     ///
275     /// # Examples
276     ///
277     /// ```
278     /// let v = [10, 40, 30];
279     /// assert_eq!(Some(&30), v.last());
280     ///
281     /// let w: &[i32] = &[];
282     /// assert_eq!(None, w.last());
283     /// ```
284     #[stable(feature = "rust1", since = "1.0.0")]
285     #[rustc_const_stable(feature = "const_slice_first_last_not_mut", since = "1.56.0")]
286     #[inline]
287     #[must_use]
288     pub const fn last(&self) -> Option<&T> {
289         if let [.., last] = self { Some(last) } else { None }
290     }
291
292     /// Returns a mutable pointer to the last item in the slice.
293     ///
294     /// # Examples
295     ///
296     /// ```
297     /// let x = &mut [0, 1, 2];
298     ///
299     /// if let Some(last) = x.last_mut() {
300     ///     *last = 10;
301     /// }
302     /// assert_eq!(x, &[0, 1, 10]);
303     /// ```
304     #[stable(feature = "rust1", since = "1.0.0")]
305     #[rustc_const_unstable(feature = "const_slice_first_last", issue = "83570")]
306     #[inline]
307     #[must_use]
308     pub const fn last_mut(&mut self) -> Option<&mut T> {
309         if let [.., last] = self { Some(last) } else { None }
310     }
311
312     /// Returns a reference to an element or subslice depending on the type of
313     /// index.
314     ///
315     /// - If given a position, returns a reference to the element at that
316     ///   position or `None` if out of bounds.
317     /// - If given a range, returns the subslice corresponding to that range,
318     ///   or `None` if out of bounds.
319     ///
320     /// # Examples
321     ///
322     /// ```
323     /// let v = [10, 40, 30];
324     /// assert_eq!(Some(&40), v.get(1));
325     /// assert_eq!(Some(&[10, 40][..]), v.get(0..2));
326     /// assert_eq!(None, v.get(3));
327     /// assert_eq!(None, v.get(0..4));
328     /// ```
329     #[stable(feature = "rust1", since = "1.0.0")]
330     #[rustc_const_unstable(feature = "const_slice_index", issue = "none")]
331     #[inline]
332     #[must_use]
333     pub const fn get<I>(&self, index: I) -> Option<&I::Output>
334     where
335         I: ~const SliceIndex<Self>,
336     {
337         index.get(self)
338     }
339
340     /// Returns a mutable reference to an element or subslice depending on the
341     /// type of index (see [`get`]) or `None` if the index is out of bounds.
342     ///
343     /// [`get`]: slice::get
344     ///
345     /// # Examples
346     ///
347     /// ```
348     /// let x = &mut [0, 1, 2];
349     ///
350     /// if let Some(elem) = x.get_mut(1) {
351     ///     *elem = 42;
352     /// }
353     /// assert_eq!(x, &[0, 42, 2]);
354     /// ```
355     #[stable(feature = "rust1", since = "1.0.0")]
356     #[rustc_const_unstable(feature = "const_slice_index", issue = "none")]
357     #[inline]
358     #[must_use]
359     pub const fn get_mut<I>(&mut self, index: I) -> Option<&mut I::Output>
360     where
361         I: ~const SliceIndex<Self>,
362     {
363         index.get_mut(self)
364     }
365
366     /// Returns a reference to an element or subslice, without doing bounds
367     /// checking.
368     ///
369     /// For a safe alternative see [`get`].
370     ///
371     /// # Safety
372     ///
373     /// Calling this method with an out-of-bounds index is *[undefined behavior]*
374     /// even if the resulting reference is not used.
375     ///
376     /// [`get`]: slice::get
377     /// [undefined behavior]: https://doc.rust-lang.org/reference/behavior-considered-undefined.html
378     ///
379     /// # Examples
380     ///
381     /// ```
382     /// let x = &[1, 2, 4];
383     ///
384     /// unsafe {
385     ///     assert_eq!(x.get_unchecked(1), &2);
386     /// }
387     /// ```
388     #[stable(feature = "rust1", since = "1.0.0")]
389     #[rustc_const_unstable(feature = "const_slice_index", issue = "none")]
390     #[inline]
391     #[must_use]
392     pub const unsafe fn get_unchecked<I>(&self, index: I) -> &I::Output
393     where
394         I: ~const SliceIndex<Self>,
395     {
396         // SAFETY: the caller must uphold most of the safety requirements for `get_unchecked`;
397         // the slice is dereferenceable because `self` is a safe reference.
398         // The returned pointer is safe because impls of `SliceIndex` have to guarantee that it is.
399         unsafe { &*index.get_unchecked(self) }
400     }
401
402     /// Returns a mutable reference to an element or subslice, without doing
403     /// bounds checking.
404     ///
405     /// For a safe alternative see [`get_mut`].
406     ///
407     /// # Safety
408     ///
409     /// Calling this method with an out-of-bounds index is *[undefined behavior]*
410     /// even if the resulting reference is not used.
411     ///
412     /// [`get_mut`]: slice::get_mut
413     /// [undefined behavior]: https://doc.rust-lang.org/reference/behavior-considered-undefined.html
414     ///
415     /// # Examples
416     ///
417     /// ```
418     /// let x = &mut [1, 2, 4];
419     ///
420     /// unsafe {
421     ///     let elem = x.get_unchecked_mut(1);
422     ///     *elem = 13;
423     /// }
424     /// assert_eq!(x, &[1, 13, 4]);
425     /// ```
426     #[stable(feature = "rust1", since = "1.0.0")]
427     #[rustc_const_unstable(feature = "const_slice_index", issue = "none")]
428     #[inline]
429     #[must_use]
430     pub const unsafe fn get_unchecked_mut<I>(&mut self, index: I) -> &mut I::Output
431     where
432         I: ~const SliceIndex<Self>,
433     {
434         // SAFETY: the caller must uphold the safety requirements for `get_unchecked_mut`;
435         // the slice is dereferenceable because `self` is a safe reference.
436         // The returned pointer is safe because impls of `SliceIndex` have to guarantee that it is.
437         unsafe { &mut *index.get_unchecked_mut(self) }
438     }
439
440     /// Returns a raw pointer to the slice's buffer.
441     ///
442     /// The caller must ensure that the slice outlives the pointer this
443     /// function returns, or else it will end up pointing to garbage.
444     ///
445     /// The caller must also ensure that the memory the pointer (non-transitively) points to
446     /// is never written to (except inside an `UnsafeCell`) using this pointer or any pointer
447     /// derived from it. If you need to mutate the contents of the slice, use [`as_mut_ptr`].
448     ///
449     /// Modifying the container referenced by this slice may cause its buffer
450     /// to be reallocated, which would also make any pointers to it invalid.
451     ///
452     /// # Examples
453     ///
454     /// ```
455     /// let x = &[1, 2, 4];
456     /// let x_ptr = x.as_ptr();
457     ///
458     /// unsafe {
459     ///     for i in 0..x.len() {
460     ///         assert_eq!(x.get_unchecked(i), &*x_ptr.add(i));
461     ///     }
462     /// }
463     /// ```
464     ///
465     /// [`as_mut_ptr`]: slice::as_mut_ptr
466     #[stable(feature = "rust1", since = "1.0.0")]
467     #[rustc_const_stable(feature = "const_slice_as_ptr", since = "1.32.0")]
468     #[inline(always)]
469     #[must_use]
470     pub const fn as_ptr(&self) -> *const T {
471         self as *const [T] as *const T
472     }
473
474     /// Returns an unsafe mutable pointer to the slice's buffer.
475     ///
476     /// The caller must ensure that the slice outlives the pointer this
477     /// function returns, or else it will end up pointing to garbage.
478     ///
479     /// Modifying the container referenced by this slice may cause its buffer
480     /// to be reallocated, which would also make any pointers to it invalid.
481     ///
482     /// # Examples
483     ///
484     /// ```
485     /// let x = &mut [1, 2, 4];
486     /// let x_ptr = x.as_mut_ptr();
487     ///
488     /// unsafe {
489     ///     for i in 0..x.len() {
490     ///         *x_ptr.add(i) += 2;
491     ///     }
492     /// }
493     /// assert_eq!(x, &[3, 4, 6]);
494     /// ```
495     #[stable(feature = "rust1", since = "1.0.0")]
496     #[rustc_const_stable(feature = "const_ptr_offset", since = "1.61.0")]
497     #[rustc_allow_const_fn_unstable(const_mut_refs)]
498     #[inline(always)]
499     #[must_use]
500     pub const fn as_mut_ptr(&mut self) -> *mut T {
501         self as *mut [T] as *mut T
502     }
503
504     /// Returns the two raw pointers spanning the slice.
505     ///
506     /// The returned range is half-open, which means that the end pointer
507     /// points *one past* the last element of the slice. This way, an empty
508     /// slice is represented by two equal pointers, and the difference between
509     /// the two pointers represents the size of the slice.
510     ///
511     /// See [`as_ptr`] for warnings on using these pointers. The end pointer
512     /// requires extra caution, as it does not point to a valid element in the
513     /// slice.
514     ///
515     /// This function is useful for interacting with foreign interfaces which
516     /// use two pointers to refer to a range of elements in memory, as is
517     /// common in C++.
518     ///
519     /// It can also be useful to check if a pointer to an element refers to an
520     /// element of this slice:
521     ///
522     /// ```
523     /// let a = [1, 2, 3];
524     /// let x = &a[1] as *const _;
525     /// let y = &5 as *const _;
526     ///
527     /// assert!(a.as_ptr_range().contains(&x));
528     /// assert!(!a.as_ptr_range().contains(&y));
529     /// ```
530     ///
531     /// [`as_ptr`]: slice::as_ptr
532     #[stable(feature = "slice_ptr_range", since = "1.48.0")]
533     #[rustc_const_stable(feature = "const_ptr_offset", since = "1.61.0")]
534     #[inline]
535     #[must_use]
536     pub const fn as_ptr_range(&self) -> Range<*const T> {
537         let start = self.as_ptr();
538         // SAFETY: The `add` here is safe, because:
539         //
540         //   - Both pointers are part of the same object, as pointing directly
541         //     past the object also counts.
542         //
543         //   - The size of the slice is never larger than isize::MAX bytes, as
544         //     noted here:
545         //       - https://github.com/rust-lang/unsafe-code-guidelines/issues/102#issuecomment-473340447
546         //       - https://doc.rust-lang.org/reference/behavior-considered-undefined.html
547         //       - https://doc.rust-lang.org/core/slice/fn.from_raw_parts.html#safety
548         //     (This doesn't seem normative yet, but the very same assumption is
549         //     made in many places, including the Index implementation of slices.)
550         //
551         //   - There is no wrapping around involved, as slices do not wrap past
552         //     the end of the address space.
553         //
554         // See the documentation of pointer::add.
555         let end = unsafe { start.add(self.len()) };
556         start..end
557     }
558
559     /// Returns the two unsafe mutable pointers spanning the slice.
560     ///
561     /// The returned range is half-open, which means that the end pointer
562     /// points *one past* the last element of the slice. This way, an empty
563     /// slice is represented by two equal pointers, and the difference between
564     /// the two pointers represents the size of the slice.
565     ///
566     /// See [`as_mut_ptr`] for warnings on using these pointers. The end
567     /// pointer requires extra caution, as it does not point to a valid element
568     /// in the slice.
569     ///
570     /// This function is useful for interacting with foreign interfaces which
571     /// use two pointers to refer to a range of elements in memory, as is
572     /// common in C++.
573     ///
574     /// [`as_mut_ptr`]: slice::as_mut_ptr
575     #[stable(feature = "slice_ptr_range", since = "1.48.0")]
576     #[rustc_const_stable(feature = "const_ptr_offset", since = "1.61.0")]
577     #[rustc_allow_const_fn_unstable(const_mut_refs)]
578     #[inline]
579     #[must_use]
580     pub const fn as_mut_ptr_range(&mut self) -> Range<*mut T> {
581         let start = self.as_mut_ptr();
582         // SAFETY: See as_ptr_range() above for why `add` here is safe.
583         let end = unsafe { start.add(self.len()) };
584         start..end
585     }
586
587     /// Swaps two elements in the slice.
588     ///
589     /// # Arguments
590     ///
591     /// * a - The index of the first element
592     /// * b - The index of the second element
593     ///
594     /// # Panics
595     ///
596     /// Panics if `a` or `b` are out of bounds.
597     ///
598     /// # Examples
599     ///
600     /// ```
601     /// let mut v = ["a", "b", "c", "d", "e"];
602     /// v.swap(2, 4);
603     /// assert!(v == ["a", "b", "e", "d", "c"]);
604     /// ```
605     #[stable(feature = "rust1", since = "1.0.0")]
606     #[rustc_const_unstable(feature = "const_swap", issue = "83163")]
607     #[inline]
608     #[track_caller]
609     pub const fn swap(&mut self, a: usize, b: usize) {
610         // FIXME: use swap_unchecked here (https://github.com/rust-lang/rust/pull/88540#issuecomment-944344343)
611         // Can't take two mutable loans from one vector, so instead use raw pointers.
612         let pa = ptr::addr_of_mut!(self[a]);
613         let pb = ptr::addr_of_mut!(self[b]);
614         // SAFETY: `pa` and `pb` have been created from safe mutable references and refer
615         // to elements in the slice and therefore are guaranteed to be valid and aligned.
616         // Note that accessing the elements behind `a` and `b` is checked and will
617         // panic when out of bounds.
618         unsafe {
619             ptr::swap(pa, pb);
620         }
621     }
622
623     /// Swaps two elements in the slice, without doing bounds checking.
624     ///
625     /// For a safe alternative see [`swap`].
626     ///
627     /// # Arguments
628     ///
629     /// * a - The index of the first element
630     /// * b - The index of the second element
631     ///
632     /// # Safety
633     ///
634     /// Calling this method with an out-of-bounds index is *[undefined behavior]*.
635     /// The caller has to ensure that `a < self.len()` and `b < self.len()`.
636     ///
637     /// # Examples
638     ///
639     /// ```
640     /// #![feature(slice_swap_unchecked)]
641     ///
642     /// let mut v = ["a", "b", "c", "d"];
643     /// // SAFETY: we know that 1 and 3 are both indices of the slice
644     /// unsafe { v.swap_unchecked(1, 3) };
645     /// assert!(v == ["a", "d", "c", "b"]);
646     /// ```
647     ///
648     /// [`swap`]: slice::swap
649     /// [undefined behavior]: https://doc.rust-lang.org/reference/behavior-considered-undefined.html
650     #[unstable(feature = "slice_swap_unchecked", issue = "88539")]
651     #[rustc_const_unstable(feature = "const_swap", issue = "83163")]
652     pub const unsafe fn swap_unchecked(&mut self, a: usize, b: usize) {
653         let this = self;
654         let ptr = this.as_mut_ptr();
655         // SAFETY: caller has to guarantee that `a < self.len()` and `b < self.len()`
656         unsafe {
657             assert_unsafe_precondition!(
658                 "slice::swap_unchecked requires that the indices are within the slice",
659                 [T](a: usize, b: usize, this: &mut [T]) => a < this.len() && b < this.len()
660             );
661             ptr::swap(ptr.add(a), ptr.add(b));
662         }
663     }
664
665     /// Reverses the order of elements in the slice, in place.
666     ///
667     /// # Examples
668     ///
669     /// ```
670     /// let mut v = [1, 2, 3];
671     /// v.reverse();
672     /// assert!(v == [3, 2, 1]);
673     /// ```
674     #[stable(feature = "rust1", since = "1.0.0")]
675     #[rustc_const_unstable(feature = "const_reverse", issue = "100784")]
676     #[inline]
677     pub const fn reverse(&mut self) {
678         let half_len = self.len() / 2;
679         let Range { start, end } = self.as_mut_ptr_range();
680
681         // These slices will skip the middle item for an odd length,
682         // since that one doesn't need to move.
683         let (front_half, back_half) =
684             // SAFETY: Both are subparts of the original slice, so the memory
685             // range is valid, and they don't overlap because they're each only
686             // half (or less) of the original slice.
687             unsafe {
688                 (
689                     slice::from_raw_parts_mut(start, half_len),
690                     slice::from_raw_parts_mut(end.sub(half_len), half_len),
691                 )
692             };
693
694         // Introducing a function boundary here means that the two halves
695         // get `noalias` markers, allowing better optimization as LLVM
696         // knows that they're disjoint, unlike in the original slice.
697         revswap(front_half, back_half, half_len);
698
699         #[inline]
700         const fn revswap<T>(a: &mut [T], b: &mut [T], n: usize) {
701             debug_assert!(a.len() == n);
702             debug_assert!(b.len() == n);
703
704             // Because this function is first compiled in isolation,
705             // this check tells LLVM that the indexing below is
706             // in-bounds.  Then after inlining -- once the actual
707             // lengths of the slices are known -- it's removed.
708             let (a, b) = (&mut a[..n], &mut b[..n]);
709
710             let mut i = 0;
711             while i < n {
712                 mem::swap(&mut a[i], &mut b[n - 1 - i]);
713                 i += 1;
714             }
715         }
716     }
717
718     /// Returns an iterator over the slice.
719     ///
720     /// The iterator yields all items from start to end.
721     ///
722     /// # Examples
723     ///
724     /// ```
725     /// let x = &[1, 2, 4];
726     /// let mut iterator = x.iter();
727     ///
728     /// assert_eq!(iterator.next(), Some(&1));
729     /// assert_eq!(iterator.next(), Some(&2));
730     /// assert_eq!(iterator.next(), Some(&4));
731     /// assert_eq!(iterator.next(), None);
732     /// ```
733     #[stable(feature = "rust1", since = "1.0.0")]
734     #[inline]
735     pub fn iter(&self) -> Iter<'_, T> {
736         Iter::new(self)
737     }
738
739     /// Returns an iterator that allows modifying each value.
740     ///
741     /// The iterator yields all items from start to end.
742     ///
743     /// # Examples
744     ///
745     /// ```
746     /// let x = &mut [1, 2, 4];
747     /// for elem in x.iter_mut() {
748     ///     *elem += 2;
749     /// }
750     /// assert_eq!(x, &[3, 4, 6]);
751     /// ```
752     #[stable(feature = "rust1", since = "1.0.0")]
753     #[inline]
754     pub fn iter_mut(&mut self) -> IterMut<'_, T> {
755         IterMut::new(self)
756     }
757
758     /// Returns an iterator over all contiguous windows of length
759     /// `size`. The windows overlap. If the slice is shorter than
760     /// `size`, the iterator returns no values.
761     ///
762     /// # Panics
763     ///
764     /// Panics if `size` is 0.
765     ///
766     /// # Examples
767     ///
768     /// ```
769     /// let slice = ['r', 'u', 's', 't'];
770     /// let mut iter = slice.windows(2);
771     /// assert_eq!(iter.next().unwrap(), &['r', 'u']);
772     /// assert_eq!(iter.next().unwrap(), &['u', 's']);
773     /// assert_eq!(iter.next().unwrap(), &['s', 't']);
774     /// assert!(iter.next().is_none());
775     /// ```
776     ///
777     /// If the slice is shorter than `size`:
778     ///
779     /// ```
780     /// let slice = ['f', 'o', 'o'];
781     /// let mut iter = slice.windows(4);
782     /// assert!(iter.next().is_none());
783     /// ```
784     #[stable(feature = "rust1", since = "1.0.0")]
785     #[inline]
786     pub fn windows(&self, size: usize) -> Windows<'_, T> {
787         let size = NonZeroUsize::new(size).expect("size is zero");
788         Windows::new(self, size)
789     }
790
791     /// Returns an iterator over `chunk_size` elements of the slice at a time, starting at the
792     /// beginning of the slice.
793     ///
794     /// The chunks are slices and do not overlap. If `chunk_size` does not divide the length of the
795     /// slice, then the last chunk will not have length `chunk_size`.
796     ///
797     /// See [`chunks_exact`] for a variant of this iterator that returns chunks of always exactly
798     /// `chunk_size` elements, and [`rchunks`] for the same iterator but starting at the end of the
799     /// slice.
800     ///
801     /// # Panics
802     ///
803     /// Panics if `chunk_size` is 0.
804     ///
805     /// # Examples
806     ///
807     /// ```
808     /// let slice = ['l', 'o', 'r', 'e', 'm'];
809     /// let mut iter = slice.chunks(2);
810     /// assert_eq!(iter.next().unwrap(), &['l', 'o']);
811     /// assert_eq!(iter.next().unwrap(), &['r', 'e']);
812     /// assert_eq!(iter.next().unwrap(), &['m']);
813     /// assert!(iter.next().is_none());
814     /// ```
815     ///
816     /// [`chunks_exact`]: slice::chunks_exact
817     /// [`rchunks`]: slice::rchunks
818     #[stable(feature = "rust1", since = "1.0.0")]
819     #[inline]
820     pub fn chunks(&self, chunk_size: usize) -> Chunks<'_, T> {
821         assert_ne!(chunk_size, 0, "chunks cannot have a size of zero");
822         Chunks::new(self, chunk_size)
823     }
824
825     /// Returns an iterator over `chunk_size` elements of the slice at a time, starting at the
826     /// beginning of the slice.
827     ///
828     /// The chunks are mutable slices, and do not overlap. If `chunk_size` does not divide the
829     /// length of the slice, then the last chunk will not have length `chunk_size`.
830     ///
831     /// See [`chunks_exact_mut`] for a variant of this iterator that returns chunks of always
832     /// exactly `chunk_size` elements, and [`rchunks_mut`] for the same iterator but starting at
833     /// the end of the slice.
834     ///
835     /// # Panics
836     ///
837     /// Panics if `chunk_size` is 0.
838     ///
839     /// # Examples
840     ///
841     /// ```
842     /// let v = &mut [0, 0, 0, 0, 0];
843     /// let mut count = 1;
844     ///
845     /// for chunk in v.chunks_mut(2) {
846     ///     for elem in chunk.iter_mut() {
847     ///         *elem += count;
848     ///     }
849     ///     count += 1;
850     /// }
851     /// assert_eq!(v, &[1, 1, 2, 2, 3]);
852     /// ```
853     ///
854     /// [`chunks_exact_mut`]: slice::chunks_exact_mut
855     /// [`rchunks_mut`]: slice::rchunks_mut
856     #[stable(feature = "rust1", since = "1.0.0")]
857     #[inline]
858     pub fn chunks_mut(&mut self, chunk_size: usize) -> ChunksMut<'_, T> {
859         assert_ne!(chunk_size, 0, "chunks cannot have a size of zero");
860         ChunksMut::new(self, chunk_size)
861     }
862
863     /// Returns an iterator over `chunk_size` elements of the slice at a time, starting at the
864     /// beginning of the slice.
865     ///
866     /// The chunks are slices and do not overlap. If `chunk_size` does not divide the length of the
867     /// slice, then the last up to `chunk_size-1` elements will be omitted and can be retrieved
868     /// from the `remainder` function of the iterator.
869     ///
870     /// Due to each chunk having exactly `chunk_size` elements, the compiler can often optimize the
871     /// resulting code better than in the case of [`chunks`].
872     ///
873     /// See [`chunks`] for a variant of this iterator that also returns the remainder as a smaller
874     /// chunk, and [`rchunks_exact`] for the same iterator but starting at the end of the slice.
875     ///
876     /// # Panics
877     ///
878     /// Panics if `chunk_size` is 0.
879     ///
880     /// # Examples
881     ///
882     /// ```
883     /// let slice = ['l', 'o', 'r', 'e', 'm'];
884     /// let mut iter = slice.chunks_exact(2);
885     /// assert_eq!(iter.next().unwrap(), &['l', 'o']);
886     /// assert_eq!(iter.next().unwrap(), &['r', 'e']);
887     /// assert!(iter.next().is_none());
888     /// assert_eq!(iter.remainder(), &['m']);
889     /// ```
890     ///
891     /// [`chunks`]: slice::chunks
892     /// [`rchunks_exact`]: slice::rchunks_exact
893     #[stable(feature = "chunks_exact", since = "1.31.0")]
894     #[inline]
895     pub fn chunks_exact(&self, chunk_size: usize) -> ChunksExact<'_, T> {
896         assert_ne!(chunk_size, 0, "chunks cannot have a size of zero");
897         ChunksExact::new(self, chunk_size)
898     }
899
900     /// Returns an iterator over `chunk_size` elements of the slice at a time, starting at the
901     /// beginning of the slice.
902     ///
903     /// The chunks are mutable slices, and do not overlap. If `chunk_size` does not divide the
904     /// length of the slice, then the last up to `chunk_size-1` elements will be omitted and can be
905     /// retrieved from the `into_remainder` function of the iterator.
906     ///
907     /// Due to each chunk having exactly `chunk_size` elements, the compiler can often optimize the
908     /// resulting code better than in the case of [`chunks_mut`].
909     ///
910     /// See [`chunks_mut`] for a variant of this iterator that also returns the remainder as a
911     /// smaller chunk, and [`rchunks_exact_mut`] for the same iterator but starting at the end of
912     /// the slice.
913     ///
914     /// # Panics
915     ///
916     /// Panics if `chunk_size` is 0.
917     ///
918     /// # Examples
919     ///
920     /// ```
921     /// let v = &mut [0, 0, 0, 0, 0];
922     /// let mut count = 1;
923     ///
924     /// for chunk in v.chunks_exact_mut(2) {
925     ///     for elem in chunk.iter_mut() {
926     ///         *elem += count;
927     ///     }
928     ///     count += 1;
929     /// }
930     /// assert_eq!(v, &[1, 1, 2, 2, 0]);
931     /// ```
932     ///
933     /// [`chunks_mut`]: slice::chunks_mut
934     /// [`rchunks_exact_mut`]: slice::rchunks_exact_mut
935     #[stable(feature = "chunks_exact", since = "1.31.0")]
936     #[inline]
937     pub fn chunks_exact_mut(&mut self, chunk_size: usize) -> ChunksExactMut<'_, T> {
938         assert_ne!(chunk_size, 0, "chunks cannot have a size of zero");
939         ChunksExactMut::new(self, chunk_size)
940     }
941
942     /// Splits the slice into a slice of `N`-element arrays,
943     /// assuming that there's no remainder.
944     ///
945     /// # Safety
946     ///
947     /// This may only be called when
948     /// - The slice splits exactly into `N`-element chunks (aka `self.len() % N == 0`).
949     /// - `N != 0`.
950     ///
951     /// # Examples
952     ///
953     /// ```
954     /// #![feature(slice_as_chunks)]
955     /// let slice: &[char] = &['l', 'o', 'r', 'e', 'm', '!'];
956     /// let chunks: &[[char; 1]] =
957     ///     // SAFETY: 1-element chunks never have remainder
958     ///     unsafe { slice.as_chunks_unchecked() };
959     /// assert_eq!(chunks, &[['l'], ['o'], ['r'], ['e'], ['m'], ['!']]);
960     /// let chunks: &[[char; 3]] =
961     ///     // SAFETY: The slice length (6) is a multiple of 3
962     ///     unsafe { slice.as_chunks_unchecked() };
963     /// assert_eq!(chunks, &[['l', 'o', 'r'], ['e', 'm', '!']]);
964     ///
965     /// // These would be unsound:
966     /// // let chunks: &[[_; 5]] = slice.as_chunks_unchecked() // The slice length is not a multiple of 5
967     /// // let chunks: &[[_; 0]] = slice.as_chunks_unchecked() // Zero-length chunks are never allowed
968     /// ```
969     #[unstable(feature = "slice_as_chunks", issue = "74985")]
970     #[inline]
971     #[must_use]
972     pub unsafe fn as_chunks_unchecked<const N: usize>(&self) -> &[[T; N]] {
973         let this = self;
974         // SAFETY: Caller must guarantee that `N` is nonzero and exactly divides the slice length
975         let new_len = unsafe {
976             assert_unsafe_precondition!(
977                 "slice::as_chunks_unchecked requires `N != 0` and the slice to split exactly into `N`-element chunks",
978                 [T](this: &[T], N: usize) => N != 0 && this.len() % N == 0
979             );
980             exact_div(self.len(), N)
981         };
982         // SAFETY: We cast a slice of `new_len * N` elements into
983         // a slice of `new_len` many `N` elements chunks.
984         unsafe { from_raw_parts(self.as_ptr().cast(), new_len) }
985     }
986
987     /// Splits the slice into a slice of `N`-element arrays,
988     /// starting at the beginning of the slice,
989     /// and a remainder slice with length strictly less than `N`.
990     ///
991     /// # Panics
992     ///
993     /// Panics if `N` is 0. This check will most probably get changed to a compile time
994     /// error before this method gets stabilized.
995     ///
996     /// # Examples
997     ///
998     /// ```
999     /// #![feature(slice_as_chunks)]
1000     /// let slice = ['l', 'o', 'r', 'e', 'm'];
1001     /// let (chunks, remainder) = slice.as_chunks();
1002     /// assert_eq!(chunks, &[['l', 'o'], ['r', 'e']]);
1003     /// assert_eq!(remainder, &['m']);
1004     /// ```
1005     ///
1006     /// If you expect the slice to be an exact multiple, you can combine
1007     /// `let`-`else` with an empty slice pattern:
1008     /// ```
1009     /// #![feature(slice_as_chunks)]
1010     /// let slice = ['R', 'u', 's', 't'];
1011     /// let (chunks, []) = slice.as_chunks::<2>() else {
1012     ///     panic!("slice didn't have even length")
1013     /// };
1014     /// assert_eq!(chunks, &[['R', 'u'], ['s', 't']]);
1015     /// ```
1016     #[unstable(feature = "slice_as_chunks", issue = "74985")]
1017     #[inline]
1018     #[must_use]
1019     pub fn as_chunks<const N: usize>(&self) -> (&[[T; N]], &[T]) {
1020         assert_ne!(N, 0, "chunks cannot have a size of zero");
1021         let len = self.len() / N;
1022         let (multiple_of_n, remainder) = self.split_at(len * N);
1023         // SAFETY: We already panicked for zero, and ensured by construction
1024         // that the length of the subslice is a multiple of N.
1025         let array_slice = unsafe { multiple_of_n.as_chunks_unchecked() };
1026         (array_slice, remainder)
1027     }
1028
1029     /// Splits the slice into a slice of `N`-element arrays,
1030     /// starting at the end of the slice,
1031     /// and a remainder slice with length strictly less than `N`.
1032     ///
1033     /// # Panics
1034     ///
1035     /// Panics if `N` is 0. This check will most probably get changed to a compile time
1036     /// error before this method gets stabilized.
1037     ///
1038     /// # Examples
1039     ///
1040     /// ```
1041     /// #![feature(slice_as_chunks)]
1042     /// let slice = ['l', 'o', 'r', 'e', 'm'];
1043     /// let (remainder, chunks) = slice.as_rchunks();
1044     /// assert_eq!(remainder, &['l']);
1045     /// assert_eq!(chunks, &[['o', 'r'], ['e', 'm']]);
1046     /// ```
1047     #[unstable(feature = "slice_as_chunks", issue = "74985")]
1048     #[inline]
1049     #[must_use]
1050     pub fn as_rchunks<const N: usize>(&self) -> (&[T], &[[T; N]]) {
1051         assert_ne!(N, 0, "chunks cannot have a size of zero");
1052         let len = self.len() / N;
1053         let (remainder, multiple_of_n) = self.split_at(self.len() - len * N);
1054         // SAFETY: We already panicked for zero, and ensured by construction
1055         // that the length of the subslice is a multiple of N.
1056         let array_slice = unsafe { multiple_of_n.as_chunks_unchecked() };
1057         (remainder, array_slice)
1058     }
1059
1060     /// Returns an iterator over `N` elements of the slice at a time, starting at the
1061     /// beginning of the slice.
1062     ///
1063     /// The chunks are array references and do not overlap. If `N` does not divide the
1064     /// length of the slice, then the last up to `N-1` elements will be omitted and can be
1065     /// retrieved from the `remainder` function of the iterator.
1066     ///
1067     /// This method is the const generic equivalent of [`chunks_exact`].
1068     ///
1069     /// # Panics
1070     ///
1071     /// Panics if `N` is 0. This check will most probably get changed to a compile time
1072     /// error before this method gets stabilized.
1073     ///
1074     /// # Examples
1075     ///
1076     /// ```
1077     /// #![feature(array_chunks)]
1078     /// let slice = ['l', 'o', 'r', 'e', 'm'];
1079     /// let mut iter = slice.array_chunks();
1080     /// assert_eq!(iter.next().unwrap(), &['l', 'o']);
1081     /// assert_eq!(iter.next().unwrap(), &['r', 'e']);
1082     /// assert!(iter.next().is_none());
1083     /// assert_eq!(iter.remainder(), &['m']);
1084     /// ```
1085     ///
1086     /// [`chunks_exact`]: slice::chunks_exact
1087     #[unstable(feature = "array_chunks", issue = "74985")]
1088     #[inline]
1089     pub fn array_chunks<const N: usize>(&self) -> ArrayChunks<'_, T, N> {
1090         assert_ne!(N, 0, "chunks cannot have a size of zero");
1091         ArrayChunks::new(self)
1092     }
1093
1094     /// Splits the slice into a slice of `N`-element arrays,
1095     /// assuming that there's no remainder.
1096     ///
1097     /// # Safety
1098     ///
1099     /// This may only be called when
1100     /// - The slice splits exactly into `N`-element chunks (aka `self.len() % N == 0`).
1101     /// - `N != 0`.
1102     ///
1103     /// # Examples
1104     ///
1105     /// ```
1106     /// #![feature(slice_as_chunks)]
1107     /// let slice: &mut [char] = &mut ['l', 'o', 'r', 'e', 'm', '!'];
1108     /// let chunks: &mut [[char; 1]] =
1109     ///     // SAFETY: 1-element chunks never have remainder
1110     ///     unsafe { slice.as_chunks_unchecked_mut() };
1111     /// chunks[0] = ['L'];
1112     /// assert_eq!(chunks, &[['L'], ['o'], ['r'], ['e'], ['m'], ['!']]);
1113     /// let chunks: &mut [[char; 3]] =
1114     ///     // SAFETY: The slice length (6) is a multiple of 3
1115     ///     unsafe { slice.as_chunks_unchecked_mut() };
1116     /// chunks[1] = ['a', 'x', '?'];
1117     /// assert_eq!(slice, &['L', 'o', 'r', 'a', 'x', '?']);
1118     ///
1119     /// // These would be unsound:
1120     /// // let chunks: &[[_; 5]] = slice.as_chunks_unchecked_mut() // The slice length is not a multiple of 5
1121     /// // let chunks: &[[_; 0]] = slice.as_chunks_unchecked_mut() // Zero-length chunks are never allowed
1122     /// ```
1123     #[unstable(feature = "slice_as_chunks", issue = "74985")]
1124     #[inline]
1125     #[must_use]
1126     pub unsafe fn as_chunks_unchecked_mut<const N: usize>(&mut self) -> &mut [[T; N]] {
1127         let this = &*self;
1128         // SAFETY: Caller must guarantee that `N` is nonzero and exactly divides the slice length
1129         let new_len = unsafe {
1130             assert_unsafe_precondition!(
1131                 "slice::as_chunks_unchecked_mut requires `N != 0` and the slice to split exactly into `N`-element chunks",
1132                 [T](this: &[T], N: usize) => N != 0 && this.len() % N == 0
1133             );
1134             exact_div(this.len(), N)
1135         };
1136         // SAFETY: We cast a slice of `new_len * N` elements into
1137         // a slice of `new_len` many `N` elements chunks.
1138         unsafe { from_raw_parts_mut(self.as_mut_ptr().cast(), new_len) }
1139     }
1140
1141     /// Splits the slice into a slice of `N`-element arrays,
1142     /// starting at the beginning of the slice,
1143     /// and a remainder slice with length strictly less than `N`.
1144     ///
1145     /// # Panics
1146     ///
1147     /// Panics if `N` is 0. This check will most probably get changed to a compile time
1148     /// error before this method gets stabilized.
1149     ///
1150     /// # Examples
1151     ///
1152     /// ```
1153     /// #![feature(slice_as_chunks)]
1154     /// let v = &mut [0, 0, 0, 0, 0];
1155     /// let mut count = 1;
1156     ///
1157     /// let (chunks, remainder) = v.as_chunks_mut();
1158     /// remainder[0] = 9;
1159     /// for chunk in chunks {
1160     ///     *chunk = [count; 2];
1161     ///     count += 1;
1162     /// }
1163     /// assert_eq!(v, &[1, 1, 2, 2, 9]);
1164     /// ```
1165     #[unstable(feature = "slice_as_chunks", issue = "74985")]
1166     #[inline]
1167     #[must_use]
1168     pub fn as_chunks_mut<const N: usize>(&mut self) -> (&mut [[T; N]], &mut [T]) {
1169         assert_ne!(N, 0, "chunks cannot have a size of zero");
1170         let len = self.len() / N;
1171         let (multiple_of_n, remainder) = self.split_at_mut(len * N);
1172         // SAFETY: We already panicked for zero, and ensured by construction
1173         // that the length of the subslice is a multiple of N.
1174         let array_slice = unsafe { multiple_of_n.as_chunks_unchecked_mut() };
1175         (array_slice, remainder)
1176     }
1177
1178     /// Splits the slice into a slice of `N`-element arrays,
1179     /// starting at the end of the slice,
1180     /// and a remainder slice with length strictly less than `N`.
1181     ///
1182     /// # Panics
1183     ///
1184     /// Panics if `N` is 0. This check will most probably get changed to a compile time
1185     /// error before this method gets stabilized.
1186     ///
1187     /// # Examples
1188     ///
1189     /// ```
1190     /// #![feature(slice_as_chunks)]
1191     /// let v = &mut [0, 0, 0, 0, 0];
1192     /// let mut count = 1;
1193     ///
1194     /// let (remainder, chunks) = v.as_rchunks_mut();
1195     /// remainder[0] = 9;
1196     /// for chunk in chunks {
1197     ///     *chunk = [count; 2];
1198     ///     count += 1;
1199     /// }
1200     /// assert_eq!(v, &[9, 1, 1, 2, 2]);
1201     /// ```
1202     #[unstable(feature = "slice_as_chunks", issue = "74985")]
1203     #[inline]
1204     #[must_use]
1205     pub fn as_rchunks_mut<const N: usize>(&mut self) -> (&mut [T], &mut [[T; N]]) {
1206         assert_ne!(N, 0, "chunks cannot have a size of zero");
1207         let len = self.len() / N;
1208         let (remainder, multiple_of_n) = self.split_at_mut(self.len() - len * N);
1209         // SAFETY: We already panicked for zero, and ensured by construction
1210         // that the length of the subslice is a multiple of N.
1211         let array_slice = unsafe { multiple_of_n.as_chunks_unchecked_mut() };
1212         (remainder, array_slice)
1213     }
1214
1215     /// Returns an iterator over `N` elements of the slice at a time, starting at the
1216     /// beginning of the slice.
1217     ///
1218     /// The chunks are mutable array references and do not overlap. If `N` does not divide
1219     /// the length of the slice, then the last up to `N-1` elements will be omitted and
1220     /// can be retrieved from the `into_remainder` function of the iterator.
1221     ///
1222     /// This method is the const generic equivalent of [`chunks_exact_mut`].
1223     ///
1224     /// # Panics
1225     ///
1226     /// Panics if `N` is 0. This check will most probably get changed to a compile time
1227     /// error before this method gets stabilized.
1228     ///
1229     /// # Examples
1230     ///
1231     /// ```
1232     /// #![feature(array_chunks)]
1233     /// let v = &mut [0, 0, 0, 0, 0];
1234     /// let mut count = 1;
1235     ///
1236     /// for chunk in v.array_chunks_mut() {
1237     ///     *chunk = [count; 2];
1238     ///     count += 1;
1239     /// }
1240     /// assert_eq!(v, &[1, 1, 2, 2, 0]);
1241     /// ```
1242     ///
1243     /// [`chunks_exact_mut`]: slice::chunks_exact_mut
1244     #[unstable(feature = "array_chunks", issue = "74985")]
1245     #[inline]
1246     pub fn array_chunks_mut<const N: usize>(&mut self) -> ArrayChunksMut<'_, T, N> {
1247         assert_ne!(N, 0, "chunks cannot have a size of zero");
1248         ArrayChunksMut::new(self)
1249     }
1250
1251     /// Returns an iterator over overlapping windows of `N` elements of  a slice,
1252     /// starting at the beginning of the slice.
1253     ///
1254     /// This is the const generic equivalent of [`windows`].
1255     ///
1256     /// If `N` is greater than the size of the slice, it will return no windows.
1257     ///
1258     /// # Panics
1259     ///
1260     /// Panics if `N` is 0. This check will most probably get changed to a compile time
1261     /// error before this method gets stabilized.
1262     ///
1263     /// # Examples
1264     ///
1265     /// ```
1266     /// #![feature(array_windows)]
1267     /// let slice = [0, 1, 2, 3];
1268     /// let mut iter = slice.array_windows();
1269     /// assert_eq!(iter.next().unwrap(), &[0, 1]);
1270     /// assert_eq!(iter.next().unwrap(), &[1, 2]);
1271     /// assert_eq!(iter.next().unwrap(), &[2, 3]);
1272     /// assert!(iter.next().is_none());
1273     /// ```
1274     ///
1275     /// [`windows`]: slice::windows
1276     #[unstable(feature = "array_windows", issue = "75027")]
1277     #[inline]
1278     pub fn array_windows<const N: usize>(&self) -> ArrayWindows<'_, T, N> {
1279         assert_ne!(N, 0, "windows cannot have a size of zero");
1280         ArrayWindows::new(self)
1281     }
1282
1283     /// Returns an iterator over `chunk_size` elements of the slice at a time, starting at the end
1284     /// of the slice.
1285     ///
1286     /// The chunks are slices and do not overlap. If `chunk_size` does not divide the length of the
1287     /// slice, then the last chunk will not have length `chunk_size`.
1288     ///
1289     /// See [`rchunks_exact`] for a variant of this iterator that returns chunks of always exactly
1290     /// `chunk_size` elements, and [`chunks`] for the same iterator but starting at the beginning
1291     /// of the slice.
1292     ///
1293     /// # Panics
1294     ///
1295     /// Panics if `chunk_size` is 0.
1296     ///
1297     /// # Examples
1298     ///
1299     /// ```
1300     /// let slice = ['l', 'o', 'r', 'e', 'm'];
1301     /// let mut iter = slice.rchunks(2);
1302     /// assert_eq!(iter.next().unwrap(), &['e', 'm']);
1303     /// assert_eq!(iter.next().unwrap(), &['o', 'r']);
1304     /// assert_eq!(iter.next().unwrap(), &['l']);
1305     /// assert!(iter.next().is_none());
1306     /// ```
1307     ///
1308     /// [`rchunks_exact`]: slice::rchunks_exact
1309     /// [`chunks`]: slice::chunks
1310     #[stable(feature = "rchunks", since = "1.31.0")]
1311     #[inline]
1312     pub fn rchunks(&self, chunk_size: usize) -> RChunks<'_, T> {
1313         assert!(chunk_size != 0);
1314         RChunks::new(self, chunk_size)
1315     }
1316
1317     /// Returns an iterator over `chunk_size` elements of the slice at a time, starting at the end
1318     /// of the slice.
1319     ///
1320     /// The chunks are mutable slices, and do not overlap. If `chunk_size` does not divide the
1321     /// length of the slice, then the last chunk will not have length `chunk_size`.
1322     ///
1323     /// See [`rchunks_exact_mut`] for a variant of this iterator that returns chunks of always
1324     /// exactly `chunk_size` elements, and [`chunks_mut`] for the same iterator but starting at the
1325     /// beginning of the slice.
1326     ///
1327     /// # Panics
1328     ///
1329     /// Panics if `chunk_size` is 0.
1330     ///
1331     /// # Examples
1332     ///
1333     /// ```
1334     /// let v = &mut [0, 0, 0, 0, 0];
1335     /// let mut count = 1;
1336     ///
1337     /// for chunk in v.rchunks_mut(2) {
1338     ///     for elem in chunk.iter_mut() {
1339     ///         *elem += count;
1340     ///     }
1341     ///     count += 1;
1342     /// }
1343     /// assert_eq!(v, &[3, 2, 2, 1, 1]);
1344     /// ```
1345     ///
1346     /// [`rchunks_exact_mut`]: slice::rchunks_exact_mut
1347     /// [`chunks_mut`]: slice::chunks_mut
1348     #[stable(feature = "rchunks", since = "1.31.0")]
1349     #[inline]
1350     pub fn rchunks_mut(&mut self, chunk_size: usize) -> RChunksMut<'_, T> {
1351         assert!(chunk_size != 0);
1352         RChunksMut::new(self, chunk_size)
1353     }
1354
1355     /// Returns an iterator over `chunk_size` elements of the slice at a time, starting at the
1356     /// end of the slice.
1357     ///
1358     /// The chunks are slices and do not overlap. If `chunk_size` does not divide the length of the
1359     /// slice, then the last up to `chunk_size-1` elements will be omitted and can be retrieved
1360     /// from the `remainder` function of the iterator.
1361     ///
1362     /// Due to each chunk having exactly `chunk_size` elements, the compiler can often optimize the
1363     /// resulting code better than in the case of [`rchunks`].
1364     ///
1365     /// See [`rchunks`] for a variant of this iterator that also returns the remainder as a smaller
1366     /// chunk, and [`chunks_exact`] for the same iterator but starting at the beginning of the
1367     /// slice.
1368     ///
1369     /// # Panics
1370     ///
1371     /// Panics if `chunk_size` is 0.
1372     ///
1373     /// # Examples
1374     ///
1375     /// ```
1376     /// let slice = ['l', 'o', 'r', 'e', 'm'];
1377     /// let mut iter = slice.rchunks_exact(2);
1378     /// assert_eq!(iter.next().unwrap(), &['e', 'm']);
1379     /// assert_eq!(iter.next().unwrap(), &['o', 'r']);
1380     /// assert!(iter.next().is_none());
1381     /// assert_eq!(iter.remainder(), &['l']);
1382     /// ```
1383     ///
1384     /// [`chunks`]: slice::chunks
1385     /// [`rchunks`]: slice::rchunks
1386     /// [`chunks_exact`]: slice::chunks_exact
1387     #[stable(feature = "rchunks", since = "1.31.0")]
1388     #[inline]
1389     pub fn rchunks_exact(&self, chunk_size: usize) -> RChunksExact<'_, T> {
1390         assert!(chunk_size != 0);
1391         RChunksExact::new(self, chunk_size)
1392     }
1393
1394     /// Returns an iterator over `chunk_size` elements of the slice at a time, starting at the end
1395     /// of the slice.
1396     ///
1397     /// The chunks are mutable slices, and do not overlap. If `chunk_size` does not divide the
1398     /// length of the slice, then the last up to `chunk_size-1` elements will be omitted and can be
1399     /// retrieved from the `into_remainder` function of the iterator.
1400     ///
1401     /// Due to each chunk having exactly `chunk_size` elements, the compiler can often optimize the
1402     /// resulting code better than in the case of [`chunks_mut`].
1403     ///
1404     /// See [`rchunks_mut`] for a variant of this iterator that also returns the remainder as a
1405     /// smaller chunk, and [`chunks_exact_mut`] for the same iterator but starting at the beginning
1406     /// of the slice.
1407     ///
1408     /// # Panics
1409     ///
1410     /// Panics if `chunk_size` is 0.
1411     ///
1412     /// # Examples
1413     ///
1414     /// ```
1415     /// let v = &mut [0, 0, 0, 0, 0];
1416     /// let mut count = 1;
1417     ///
1418     /// for chunk in v.rchunks_exact_mut(2) {
1419     ///     for elem in chunk.iter_mut() {
1420     ///         *elem += count;
1421     ///     }
1422     ///     count += 1;
1423     /// }
1424     /// assert_eq!(v, &[0, 2, 2, 1, 1]);
1425     /// ```
1426     ///
1427     /// [`chunks_mut`]: slice::chunks_mut
1428     /// [`rchunks_mut`]: slice::rchunks_mut
1429     /// [`chunks_exact_mut`]: slice::chunks_exact_mut
1430     #[stable(feature = "rchunks", since = "1.31.0")]
1431     #[inline]
1432     pub fn rchunks_exact_mut(&mut self, chunk_size: usize) -> RChunksExactMut<'_, T> {
1433         assert!(chunk_size != 0);
1434         RChunksExactMut::new(self, chunk_size)
1435     }
1436
1437     /// Returns an iterator over the slice producing non-overlapping runs
1438     /// of elements using the predicate to separate them.
1439     ///
1440     /// The predicate is called on two elements following themselves,
1441     /// it means the predicate is called on `slice[0]` and `slice[1]`
1442     /// then on `slice[1]` and `slice[2]` and so on.
1443     ///
1444     /// # Examples
1445     ///
1446     /// ```
1447     /// #![feature(slice_group_by)]
1448     ///
1449     /// let slice = &[1, 1, 1, 3, 3, 2, 2, 2];
1450     ///
1451     /// let mut iter = slice.group_by(|a, b| a == b);
1452     ///
1453     /// assert_eq!(iter.next(), Some(&[1, 1, 1][..]));
1454     /// assert_eq!(iter.next(), Some(&[3, 3][..]));
1455     /// assert_eq!(iter.next(), Some(&[2, 2, 2][..]));
1456     /// assert_eq!(iter.next(), None);
1457     /// ```
1458     ///
1459     /// This method can be used to extract the sorted subslices:
1460     ///
1461     /// ```
1462     /// #![feature(slice_group_by)]
1463     ///
1464     /// let slice = &[1, 1, 2, 3, 2, 3, 2, 3, 4];
1465     ///
1466     /// let mut iter = slice.group_by(|a, b| a <= b);
1467     ///
1468     /// assert_eq!(iter.next(), Some(&[1, 1, 2, 3][..]));
1469     /// assert_eq!(iter.next(), Some(&[2, 3][..]));
1470     /// assert_eq!(iter.next(), Some(&[2, 3, 4][..]));
1471     /// assert_eq!(iter.next(), None);
1472     /// ```
1473     #[unstable(feature = "slice_group_by", issue = "80552")]
1474     #[inline]
1475     pub fn group_by<F>(&self, pred: F) -> GroupBy<'_, T, F>
1476     where
1477         F: FnMut(&T, &T) -> bool,
1478     {
1479         GroupBy::new(self, pred)
1480     }
1481
1482     /// Returns an iterator over the slice producing non-overlapping mutable
1483     /// runs of elements using the predicate to separate them.
1484     ///
1485     /// The predicate is called on two elements following themselves,
1486     /// it means the predicate is called on `slice[0]` and `slice[1]`
1487     /// then on `slice[1]` and `slice[2]` and so on.
1488     ///
1489     /// # Examples
1490     ///
1491     /// ```
1492     /// #![feature(slice_group_by)]
1493     ///
1494     /// let slice = &mut [1, 1, 1, 3, 3, 2, 2, 2];
1495     ///
1496     /// let mut iter = slice.group_by_mut(|a, b| a == b);
1497     ///
1498     /// assert_eq!(iter.next(), Some(&mut [1, 1, 1][..]));
1499     /// assert_eq!(iter.next(), Some(&mut [3, 3][..]));
1500     /// assert_eq!(iter.next(), Some(&mut [2, 2, 2][..]));
1501     /// assert_eq!(iter.next(), None);
1502     /// ```
1503     ///
1504     /// This method can be used to extract the sorted subslices:
1505     ///
1506     /// ```
1507     /// #![feature(slice_group_by)]
1508     ///
1509     /// let slice = &mut [1, 1, 2, 3, 2, 3, 2, 3, 4];
1510     ///
1511     /// let mut iter = slice.group_by_mut(|a, b| a <= b);
1512     ///
1513     /// assert_eq!(iter.next(), Some(&mut [1, 1, 2, 3][..]));
1514     /// assert_eq!(iter.next(), Some(&mut [2, 3][..]));
1515     /// assert_eq!(iter.next(), Some(&mut [2, 3, 4][..]));
1516     /// assert_eq!(iter.next(), None);
1517     /// ```
1518     #[unstable(feature = "slice_group_by", issue = "80552")]
1519     #[inline]
1520     pub fn group_by_mut<F>(&mut self, pred: F) -> GroupByMut<'_, T, F>
1521     where
1522         F: FnMut(&T, &T) -> bool,
1523     {
1524         GroupByMut::new(self, pred)
1525     }
1526
1527     /// Divides one slice into two at an index.
1528     ///
1529     /// The first will contain all indices from `[0, mid)` (excluding
1530     /// the index `mid` itself) and the second will contain all
1531     /// indices from `[mid, len)` (excluding the index `len` itself).
1532     ///
1533     /// # Panics
1534     ///
1535     /// Panics if `mid > len`.
1536     ///
1537     /// # Examples
1538     ///
1539     /// ```
1540     /// let v = [1, 2, 3, 4, 5, 6];
1541     ///
1542     /// {
1543     ///    let (left, right) = v.split_at(0);
1544     ///    assert_eq!(left, []);
1545     ///    assert_eq!(right, [1, 2, 3, 4, 5, 6]);
1546     /// }
1547     ///
1548     /// {
1549     ///     let (left, right) = v.split_at(2);
1550     ///     assert_eq!(left, [1, 2]);
1551     ///     assert_eq!(right, [3, 4, 5, 6]);
1552     /// }
1553     ///
1554     /// {
1555     ///     let (left, right) = v.split_at(6);
1556     ///     assert_eq!(left, [1, 2, 3, 4, 5, 6]);
1557     ///     assert_eq!(right, []);
1558     /// }
1559     /// ```
1560     #[stable(feature = "rust1", since = "1.0.0")]
1561     #[rustc_const_unstable(feature = "const_slice_split_at_not_mut", issue = "101158")]
1562     #[inline]
1563     #[track_caller]
1564     #[must_use]
1565     pub const fn split_at(&self, mid: usize) -> (&[T], &[T]) {
1566         assert!(mid <= self.len());
1567         // SAFETY: `[ptr; mid]` and `[mid; len]` are inside `self`, which
1568         // fulfills the requirements of `split_at_unchecked`.
1569         unsafe { self.split_at_unchecked(mid) }
1570     }
1571
1572     /// Divides one mutable slice into two at an index.
1573     ///
1574     /// The first will contain all indices from `[0, mid)` (excluding
1575     /// the index `mid` itself) and the second will contain all
1576     /// indices from `[mid, len)` (excluding the index `len` itself).
1577     ///
1578     /// # Panics
1579     ///
1580     /// Panics if `mid > len`.
1581     ///
1582     /// # Examples
1583     ///
1584     /// ```
1585     /// let mut v = [1, 0, 3, 0, 5, 6];
1586     /// let (left, right) = v.split_at_mut(2);
1587     /// assert_eq!(left, [1, 0]);
1588     /// assert_eq!(right, [3, 0, 5, 6]);
1589     /// left[1] = 2;
1590     /// right[1] = 4;
1591     /// assert_eq!(v, [1, 2, 3, 4, 5, 6]);
1592     /// ```
1593     #[stable(feature = "rust1", since = "1.0.0")]
1594     #[inline]
1595     #[track_caller]
1596     #[must_use]
1597     #[rustc_const_unstable(feature = "const_slice_split_at_mut", issue = "101804")]
1598     pub const fn split_at_mut(&mut self, mid: usize) -> (&mut [T], &mut [T]) {
1599         assert!(mid <= self.len());
1600         // SAFETY: `[ptr; mid]` and `[mid; len]` are inside `self`, which
1601         // fulfills the requirements of `from_raw_parts_mut`.
1602         unsafe { self.split_at_mut_unchecked(mid) }
1603     }
1604
1605     /// Divides one slice into two at an index, without doing bounds checking.
1606     ///
1607     /// The first will contain all indices from `[0, mid)` (excluding
1608     /// the index `mid` itself) and the second will contain all
1609     /// indices from `[mid, len)` (excluding the index `len` itself).
1610     ///
1611     /// For a safe alternative see [`split_at`].
1612     ///
1613     /// # Safety
1614     ///
1615     /// Calling this method with an out-of-bounds index is *[undefined behavior]*
1616     /// even if the resulting reference is not used. The caller has to ensure that
1617     /// `0 <= mid <= self.len()`.
1618     ///
1619     /// [`split_at`]: slice::split_at
1620     /// [undefined behavior]: https://doc.rust-lang.org/reference/behavior-considered-undefined.html
1621     ///
1622     /// # Examples
1623     ///
1624     /// ```
1625     /// #![feature(slice_split_at_unchecked)]
1626     ///
1627     /// let v = [1, 2, 3, 4, 5, 6];
1628     ///
1629     /// unsafe {
1630     ///    let (left, right) = v.split_at_unchecked(0);
1631     ///    assert_eq!(left, []);
1632     ///    assert_eq!(right, [1, 2, 3, 4, 5, 6]);
1633     /// }
1634     ///
1635     /// unsafe {
1636     ///     let (left, right) = v.split_at_unchecked(2);
1637     ///     assert_eq!(left, [1, 2]);
1638     ///     assert_eq!(right, [3, 4, 5, 6]);
1639     /// }
1640     ///
1641     /// unsafe {
1642     ///     let (left, right) = v.split_at_unchecked(6);
1643     ///     assert_eq!(left, [1, 2, 3, 4, 5, 6]);
1644     ///     assert_eq!(right, []);
1645     /// }
1646     /// ```
1647     #[unstable(feature = "slice_split_at_unchecked", reason = "new API", issue = "76014")]
1648     #[rustc_const_unstable(feature = "slice_split_at_unchecked", issue = "76014")]
1649     #[inline]
1650     #[must_use]
1651     pub const unsafe fn split_at_unchecked(&self, mid: usize) -> (&[T], &[T]) {
1652         // HACK: the const function `from_raw_parts` is used to make this
1653         // function const; previously the implementation used
1654         // `(self.get_unchecked(..mid), self.get_unchecked(mid..))`
1655
1656         let len = self.len();
1657         let ptr = self.as_ptr();
1658
1659         // SAFETY: Caller has to check that `0 <= mid <= self.len()`
1660         unsafe { (from_raw_parts(ptr, mid), from_raw_parts(ptr.add(mid), len - mid)) }
1661     }
1662
1663     /// Divides one mutable slice into two at an index, without doing bounds checking.
1664     ///
1665     /// The first will contain all indices from `[0, mid)` (excluding
1666     /// the index `mid` itself) and the second will contain all
1667     /// indices from `[mid, len)` (excluding the index `len` itself).
1668     ///
1669     /// For a safe alternative see [`split_at_mut`].
1670     ///
1671     /// # Safety
1672     ///
1673     /// Calling this method with an out-of-bounds index is *[undefined behavior]*
1674     /// even if the resulting reference is not used. The caller has to ensure that
1675     /// `0 <= mid <= self.len()`.
1676     ///
1677     /// [`split_at_mut`]: slice::split_at_mut
1678     /// [undefined behavior]: https://doc.rust-lang.org/reference/behavior-considered-undefined.html
1679     ///
1680     /// # Examples
1681     ///
1682     /// ```
1683     /// #![feature(slice_split_at_unchecked)]
1684     ///
1685     /// let mut v = [1, 0, 3, 0, 5, 6];
1686     /// // scoped to restrict the lifetime of the borrows
1687     /// unsafe {
1688     ///     let (left, right) = v.split_at_mut_unchecked(2);
1689     ///     assert_eq!(left, [1, 0]);
1690     ///     assert_eq!(right, [3, 0, 5, 6]);
1691     ///     left[1] = 2;
1692     ///     right[1] = 4;
1693     /// }
1694     /// assert_eq!(v, [1, 2, 3, 4, 5, 6]);
1695     /// ```
1696     #[unstable(feature = "slice_split_at_unchecked", reason = "new API", issue = "76014")]
1697     #[rustc_const_unstable(feature = "const_slice_split_at_mut", issue = "101804")]
1698     #[inline]
1699     #[must_use]
1700     pub const unsafe fn split_at_mut_unchecked(&mut self, mid: usize) -> (&mut [T], &mut [T]) {
1701         let len = self.len();
1702         let ptr = self.as_mut_ptr();
1703
1704         // SAFETY: Caller has to check that `0 <= mid <= self.len()`.
1705         //
1706         // `[ptr; mid]` and `[mid; len]` are not overlapping, so returning a mutable reference
1707         // is fine.
1708         unsafe {
1709             assert_unsafe_precondition!(
1710                 "slice::split_at_mut_unchecked requires the index to be within the slice",
1711                 (mid: usize, len: usize) => mid <= len
1712             );
1713             (from_raw_parts_mut(ptr, mid), from_raw_parts_mut(ptr.add(mid), len - mid))
1714         }
1715     }
1716
1717     /// Divides one slice into an array and a remainder slice at an index.
1718     ///
1719     /// The array will contain all indices from `[0, N)` (excluding
1720     /// the index `N` itself) and the slice will contain all
1721     /// indices from `[N, len)` (excluding the index `len` itself).
1722     ///
1723     /// # Panics
1724     ///
1725     /// Panics if `N > len`.
1726     ///
1727     /// # Examples
1728     ///
1729     /// ```
1730     /// #![feature(split_array)]
1731     ///
1732     /// let v = &[1, 2, 3, 4, 5, 6][..];
1733     ///
1734     /// {
1735     ///    let (left, right) = v.split_array_ref::<0>();
1736     ///    assert_eq!(left, &[]);
1737     ///    assert_eq!(right, [1, 2, 3, 4, 5, 6]);
1738     /// }
1739     ///
1740     /// {
1741     ///     let (left, right) = v.split_array_ref::<2>();
1742     ///     assert_eq!(left, &[1, 2]);
1743     ///     assert_eq!(right, [3, 4, 5, 6]);
1744     /// }
1745     ///
1746     /// {
1747     ///     let (left, right) = v.split_array_ref::<6>();
1748     ///     assert_eq!(left, &[1, 2, 3, 4, 5, 6]);
1749     ///     assert_eq!(right, []);
1750     /// }
1751     /// ```
1752     #[unstable(feature = "split_array", reason = "new API", issue = "90091")]
1753     #[inline]
1754     #[track_caller]
1755     #[must_use]
1756     pub fn split_array_ref<const N: usize>(&self) -> (&[T; N], &[T]) {
1757         let (a, b) = self.split_at(N);
1758         // SAFETY: a points to [T; N]? Yes it's [T] of length N (checked by split_at)
1759         unsafe { (&*(a.as_ptr() as *const [T; N]), b) }
1760     }
1761
1762     /// Divides one mutable slice into an array and a remainder slice at an index.
1763     ///
1764     /// The array will contain all indices from `[0, N)` (excluding
1765     /// the index `N` itself) and the slice will contain all
1766     /// indices from `[N, len)` (excluding the index `len` itself).
1767     ///
1768     /// # Panics
1769     ///
1770     /// Panics if `N > len`.
1771     ///
1772     /// # Examples
1773     ///
1774     /// ```
1775     /// #![feature(split_array)]
1776     ///
1777     /// let mut v = &mut [1, 0, 3, 0, 5, 6][..];
1778     /// let (left, right) = v.split_array_mut::<2>();
1779     /// assert_eq!(left, &mut [1, 0]);
1780     /// assert_eq!(right, [3, 0, 5, 6]);
1781     /// left[1] = 2;
1782     /// right[1] = 4;
1783     /// assert_eq!(v, [1, 2, 3, 4, 5, 6]);
1784     /// ```
1785     #[unstable(feature = "split_array", reason = "new API", issue = "90091")]
1786     #[inline]
1787     #[track_caller]
1788     #[must_use]
1789     pub fn split_array_mut<const N: usize>(&mut self) -> (&mut [T; N], &mut [T]) {
1790         let (a, b) = self.split_at_mut(N);
1791         // SAFETY: a points to [T; N]? Yes it's [T] of length N (checked by split_at_mut)
1792         unsafe { (&mut *(a.as_mut_ptr() as *mut [T; N]), b) }
1793     }
1794
1795     /// Divides one slice into an array and a remainder slice at an index from
1796     /// the end.
1797     ///
1798     /// The slice will contain all indices from `[0, len - N)` (excluding
1799     /// the index `len - N` itself) and the array will contain all
1800     /// indices from `[len - N, len)` (excluding the index `len` itself).
1801     ///
1802     /// # Panics
1803     ///
1804     /// Panics if `N > len`.
1805     ///
1806     /// # Examples
1807     ///
1808     /// ```
1809     /// #![feature(split_array)]
1810     ///
1811     /// let v = &[1, 2, 3, 4, 5, 6][..];
1812     ///
1813     /// {
1814     ///    let (left, right) = v.rsplit_array_ref::<0>();
1815     ///    assert_eq!(left, [1, 2, 3, 4, 5, 6]);
1816     ///    assert_eq!(right, &[]);
1817     /// }
1818     ///
1819     /// {
1820     ///     let (left, right) = v.rsplit_array_ref::<2>();
1821     ///     assert_eq!(left, [1, 2, 3, 4]);
1822     ///     assert_eq!(right, &[5, 6]);
1823     /// }
1824     ///
1825     /// {
1826     ///     let (left, right) = v.rsplit_array_ref::<6>();
1827     ///     assert_eq!(left, []);
1828     ///     assert_eq!(right, &[1, 2, 3, 4, 5, 6]);
1829     /// }
1830     /// ```
1831     #[unstable(feature = "split_array", reason = "new API", issue = "90091")]
1832     #[inline]
1833     #[must_use]
1834     pub fn rsplit_array_ref<const N: usize>(&self) -> (&[T], &[T; N]) {
1835         assert!(N <= self.len());
1836         let (a, b) = self.split_at(self.len() - N);
1837         // SAFETY: b points to [T; N]? Yes it's [T] of length N (checked by split_at)
1838         unsafe { (a, &*(b.as_ptr() as *const [T; N])) }
1839     }
1840
1841     /// Divides one mutable slice into an array and a remainder slice at an
1842     /// index from the end.
1843     ///
1844     /// The slice will contain all indices from `[0, len - N)` (excluding
1845     /// the index `N` itself) and the array will contain all
1846     /// indices from `[len - N, len)` (excluding the index `len` itself).
1847     ///
1848     /// # Panics
1849     ///
1850     /// Panics if `N > len`.
1851     ///
1852     /// # Examples
1853     ///
1854     /// ```
1855     /// #![feature(split_array)]
1856     ///
1857     /// let mut v = &mut [1, 0, 3, 0, 5, 6][..];
1858     /// let (left, right) = v.rsplit_array_mut::<4>();
1859     /// assert_eq!(left, [1, 0]);
1860     /// assert_eq!(right, &mut [3, 0, 5, 6]);
1861     /// left[1] = 2;
1862     /// right[1] = 4;
1863     /// assert_eq!(v, [1, 2, 3, 4, 5, 6]);
1864     /// ```
1865     #[unstable(feature = "split_array", reason = "new API", issue = "90091")]
1866     #[inline]
1867     #[must_use]
1868     pub fn rsplit_array_mut<const N: usize>(&mut self) -> (&mut [T], &mut [T; N]) {
1869         assert!(N <= self.len());
1870         let (a, b) = self.split_at_mut(self.len() - N);
1871         // SAFETY: b points to [T; N]? Yes it's [T] of length N (checked by split_at_mut)
1872         unsafe { (a, &mut *(b.as_mut_ptr() as *mut [T; N])) }
1873     }
1874
1875     /// Returns an iterator over subslices separated by elements that match
1876     /// `pred`. The matched element is not contained in the subslices.
1877     ///
1878     /// # Examples
1879     ///
1880     /// ```
1881     /// let slice = [10, 40, 33, 20];
1882     /// let mut iter = slice.split(|num| num % 3 == 0);
1883     ///
1884     /// assert_eq!(iter.next().unwrap(), &[10, 40]);
1885     /// assert_eq!(iter.next().unwrap(), &[20]);
1886     /// assert!(iter.next().is_none());
1887     /// ```
1888     ///
1889     /// If the first element is matched, an empty slice will be the first item
1890     /// returned by the iterator. Similarly, if the last element in the slice
1891     /// is matched, an empty slice will be the last item returned by the
1892     /// iterator:
1893     ///
1894     /// ```
1895     /// let slice = [10, 40, 33];
1896     /// let mut iter = slice.split(|num| num % 3 == 0);
1897     ///
1898     /// assert_eq!(iter.next().unwrap(), &[10, 40]);
1899     /// assert_eq!(iter.next().unwrap(), &[]);
1900     /// assert!(iter.next().is_none());
1901     /// ```
1902     ///
1903     /// If two matched elements are directly adjacent, an empty slice will be
1904     /// present between them:
1905     ///
1906     /// ```
1907     /// let slice = [10, 6, 33, 20];
1908     /// let mut iter = slice.split(|num| num % 3 == 0);
1909     ///
1910     /// assert_eq!(iter.next().unwrap(), &[10]);
1911     /// assert_eq!(iter.next().unwrap(), &[]);
1912     /// assert_eq!(iter.next().unwrap(), &[20]);
1913     /// assert!(iter.next().is_none());
1914     /// ```
1915     #[stable(feature = "rust1", since = "1.0.0")]
1916     #[inline]
1917     pub fn split<F>(&self, pred: F) -> Split<'_, T, F>
1918     where
1919         F: FnMut(&T) -> bool,
1920     {
1921         Split::new(self, pred)
1922     }
1923
1924     /// Returns an iterator over mutable subslices separated by elements that
1925     /// match `pred`. The matched element is not contained in the subslices.
1926     ///
1927     /// # Examples
1928     ///
1929     /// ```
1930     /// let mut v = [10, 40, 30, 20, 60, 50];
1931     ///
1932     /// for group in v.split_mut(|num| *num % 3 == 0) {
1933     ///     group[0] = 1;
1934     /// }
1935     /// assert_eq!(v, [1, 40, 30, 1, 60, 1]);
1936     /// ```
1937     #[stable(feature = "rust1", since = "1.0.0")]
1938     #[inline]
1939     pub fn split_mut<F>(&mut self, pred: F) -> SplitMut<'_, T, F>
1940     where
1941         F: FnMut(&T) -> bool,
1942     {
1943         SplitMut::new(self, pred)
1944     }
1945
1946     /// Returns an iterator over subslices separated by elements that match
1947     /// `pred`. The matched element is contained in the end of the previous
1948     /// subslice as a terminator.
1949     ///
1950     /// # Examples
1951     ///
1952     /// ```
1953     /// let slice = [10, 40, 33, 20];
1954     /// let mut iter = slice.split_inclusive(|num| num % 3 == 0);
1955     ///
1956     /// assert_eq!(iter.next().unwrap(), &[10, 40, 33]);
1957     /// assert_eq!(iter.next().unwrap(), &[20]);
1958     /// assert!(iter.next().is_none());
1959     /// ```
1960     ///
1961     /// If the last element of the slice is matched,
1962     /// that element will be considered the terminator of the preceding slice.
1963     /// That slice will be the last item returned by the iterator.
1964     ///
1965     /// ```
1966     /// let slice = [3, 10, 40, 33];
1967     /// let mut iter = slice.split_inclusive(|num| num % 3 == 0);
1968     ///
1969     /// assert_eq!(iter.next().unwrap(), &[3]);
1970     /// assert_eq!(iter.next().unwrap(), &[10, 40, 33]);
1971     /// assert!(iter.next().is_none());
1972     /// ```
1973     #[stable(feature = "split_inclusive", since = "1.51.0")]
1974     #[inline]
1975     pub fn split_inclusive<F>(&self, pred: F) -> SplitInclusive<'_, T, F>
1976     where
1977         F: FnMut(&T) -> bool,
1978     {
1979         SplitInclusive::new(self, pred)
1980     }
1981
1982     /// Returns an iterator over mutable subslices separated by elements that
1983     /// match `pred`. The matched element is contained in the previous
1984     /// subslice as a terminator.
1985     ///
1986     /// # Examples
1987     ///
1988     /// ```
1989     /// let mut v = [10, 40, 30, 20, 60, 50];
1990     ///
1991     /// for group in v.split_inclusive_mut(|num| *num % 3 == 0) {
1992     ///     let terminator_idx = group.len()-1;
1993     ///     group[terminator_idx] = 1;
1994     /// }
1995     /// assert_eq!(v, [10, 40, 1, 20, 1, 1]);
1996     /// ```
1997     #[stable(feature = "split_inclusive", since = "1.51.0")]
1998     #[inline]
1999     pub fn split_inclusive_mut<F>(&mut self, pred: F) -> SplitInclusiveMut<'_, T, F>
2000     where
2001         F: FnMut(&T) -> bool,
2002     {
2003         SplitInclusiveMut::new(self, pred)
2004     }
2005
2006     /// Returns an iterator over subslices separated by elements that match
2007     /// `pred`, starting at the end of the slice and working backwards.
2008     /// The matched element is not contained in the subslices.
2009     ///
2010     /// # Examples
2011     ///
2012     /// ```
2013     /// let slice = [11, 22, 33, 0, 44, 55];
2014     /// let mut iter = slice.rsplit(|num| *num == 0);
2015     ///
2016     /// assert_eq!(iter.next().unwrap(), &[44, 55]);
2017     /// assert_eq!(iter.next().unwrap(), &[11, 22, 33]);
2018     /// assert_eq!(iter.next(), None);
2019     /// ```
2020     ///
2021     /// As with `split()`, if the first or last element is matched, an empty
2022     /// slice will be the first (or last) item returned by the iterator.
2023     ///
2024     /// ```
2025     /// let v = &[0, 1, 1, 2, 3, 5, 8];
2026     /// let mut it = v.rsplit(|n| *n % 2 == 0);
2027     /// assert_eq!(it.next().unwrap(), &[]);
2028     /// assert_eq!(it.next().unwrap(), &[3, 5]);
2029     /// assert_eq!(it.next().unwrap(), &[1, 1]);
2030     /// assert_eq!(it.next().unwrap(), &[]);
2031     /// assert_eq!(it.next(), None);
2032     /// ```
2033     #[stable(feature = "slice_rsplit", since = "1.27.0")]
2034     #[inline]
2035     pub fn rsplit<F>(&self, pred: F) -> RSplit<'_, T, F>
2036     where
2037         F: FnMut(&T) -> bool,
2038     {
2039         RSplit::new(self, pred)
2040     }
2041
2042     /// Returns an iterator over mutable subslices separated by elements that
2043     /// match `pred`, starting at the end of the slice and working
2044     /// backwards. The matched element is not contained in the subslices.
2045     ///
2046     /// # Examples
2047     ///
2048     /// ```
2049     /// let mut v = [100, 400, 300, 200, 600, 500];
2050     ///
2051     /// let mut count = 0;
2052     /// for group in v.rsplit_mut(|num| *num % 3 == 0) {
2053     ///     count += 1;
2054     ///     group[0] = count;
2055     /// }
2056     /// assert_eq!(v, [3, 400, 300, 2, 600, 1]);
2057     /// ```
2058     ///
2059     #[stable(feature = "slice_rsplit", since = "1.27.0")]
2060     #[inline]
2061     pub fn rsplit_mut<F>(&mut self, pred: F) -> RSplitMut<'_, T, F>
2062     where
2063         F: FnMut(&T) -> bool,
2064     {
2065         RSplitMut::new(self, pred)
2066     }
2067
2068     /// Returns an iterator over subslices separated by elements that match
2069     /// `pred`, limited to returning at most `n` items. The matched element is
2070     /// not contained in the subslices.
2071     ///
2072     /// The last element returned, if any, will contain the remainder of the
2073     /// slice.
2074     ///
2075     /// # Examples
2076     ///
2077     /// Print the slice split once by numbers divisible by 3 (i.e., `[10, 40]`,
2078     /// `[20, 60, 50]`):
2079     ///
2080     /// ```
2081     /// let v = [10, 40, 30, 20, 60, 50];
2082     ///
2083     /// for group in v.splitn(2, |num| *num % 3 == 0) {
2084     ///     println!("{group:?}");
2085     /// }
2086     /// ```
2087     #[stable(feature = "rust1", since = "1.0.0")]
2088     #[inline]
2089     pub fn splitn<F>(&self, n: usize, pred: F) -> SplitN<'_, T, F>
2090     where
2091         F: FnMut(&T) -> bool,
2092     {
2093         SplitN::new(self.split(pred), n)
2094     }
2095
2096     /// Returns an iterator over mutable subslices separated by elements that match
2097     /// `pred`, limited to returning at most `n` items. The matched element is
2098     /// not contained in the subslices.
2099     ///
2100     /// The last element returned, if any, will contain the remainder of the
2101     /// slice.
2102     ///
2103     /// # Examples
2104     ///
2105     /// ```
2106     /// let mut v = [10, 40, 30, 20, 60, 50];
2107     ///
2108     /// for group in v.splitn_mut(2, |num| *num % 3 == 0) {
2109     ///     group[0] = 1;
2110     /// }
2111     /// assert_eq!(v, [1, 40, 30, 1, 60, 50]);
2112     /// ```
2113     #[stable(feature = "rust1", since = "1.0.0")]
2114     #[inline]
2115     pub fn splitn_mut<F>(&mut self, n: usize, pred: F) -> SplitNMut<'_, T, F>
2116     where
2117         F: FnMut(&T) -> bool,
2118     {
2119         SplitNMut::new(self.split_mut(pred), n)
2120     }
2121
2122     /// Returns an iterator over subslices separated by elements that match
2123     /// `pred` limited to returning at most `n` items. This starts at the end of
2124     /// the slice and works backwards. The matched element is not contained in
2125     /// the subslices.
2126     ///
2127     /// The last element returned, if any, will contain the remainder of the
2128     /// slice.
2129     ///
2130     /// # Examples
2131     ///
2132     /// Print the slice split once, starting from the end, by numbers divisible
2133     /// by 3 (i.e., `[50]`, `[10, 40, 30, 20]`):
2134     ///
2135     /// ```
2136     /// let v = [10, 40, 30, 20, 60, 50];
2137     ///
2138     /// for group in v.rsplitn(2, |num| *num % 3 == 0) {
2139     ///     println!("{group:?}");
2140     /// }
2141     /// ```
2142     #[stable(feature = "rust1", since = "1.0.0")]
2143     #[inline]
2144     pub fn rsplitn<F>(&self, n: usize, pred: F) -> RSplitN<'_, T, F>
2145     where
2146         F: FnMut(&T) -> bool,
2147     {
2148         RSplitN::new(self.rsplit(pred), n)
2149     }
2150
2151     /// Returns an iterator over subslices separated by elements that match
2152     /// `pred` limited to returning at most `n` items. This starts at the end of
2153     /// the slice and works backwards. The matched element is not contained in
2154     /// the subslices.
2155     ///
2156     /// The last element returned, if any, will contain the remainder of the
2157     /// slice.
2158     ///
2159     /// # Examples
2160     ///
2161     /// ```
2162     /// let mut s = [10, 40, 30, 20, 60, 50];
2163     ///
2164     /// for group in s.rsplitn_mut(2, |num| *num % 3 == 0) {
2165     ///     group[0] = 1;
2166     /// }
2167     /// assert_eq!(s, [1, 40, 30, 20, 60, 1]);
2168     /// ```
2169     #[stable(feature = "rust1", since = "1.0.0")]
2170     #[inline]
2171     pub fn rsplitn_mut<F>(&mut self, n: usize, pred: F) -> RSplitNMut<'_, T, F>
2172     where
2173         F: FnMut(&T) -> bool,
2174     {
2175         RSplitNMut::new(self.rsplit_mut(pred), n)
2176     }
2177
2178     /// Returns `true` if the slice contains an element with the given value.
2179     ///
2180     /// This operation is *O*(*n*).
2181     ///
2182     /// Note that if you have a sorted slice, [`binary_search`] may be faster.
2183     ///
2184     /// [`binary_search`]: slice::binary_search
2185     ///
2186     /// # Examples
2187     ///
2188     /// ```
2189     /// let v = [10, 40, 30];
2190     /// assert!(v.contains(&30));
2191     /// assert!(!v.contains(&50));
2192     /// ```
2193     ///
2194     /// If you do not have a `&T`, but some other value that you can compare
2195     /// with one (for example, `String` implements `PartialEq<str>`), you can
2196     /// use `iter().any`:
2197     ///
2198     /// ```
2199     /// let v = [String::from("hello"), String::from("world")]; // slice of `String`
2200     /// assert!(v.iter().any(|e| e == "hello")); // search with `&str`
2201     /// assert!(!v.iter().any(|e| e == "hi"));
2202     /// ```
2203     #[stable(feature = "rust1", since = "1.0.0")]
2204     #[inline]
2205     #[must_use]
2206     pub fn contains(&self, x: &T) -> bool
2207     where
2208         T: PartialEq,
2209     {
2210         cmp::SliceContains::slice_contains(x, self)
2211     }
2212
2213     /// Returns `true` if `needle` is a prefix of the slice.
2214     ///
2215     /// # Examples
2216     ///
2217     /// ```
2218     /// let v = [10, 40, 30];
2219     /// assert!(v.starts_with(&[10]));
2220     /// assert!(v.starts_with(&[10, 40]));
2221     /// assert!(!v.starts_with(&[50]));
2222     /// assert!(!v.starts_with(&[10, 50]));
2223     /// ```
2224     ///
2225     /// Always returns `true` if `needle` is an empty slice:
2226     ///
2227     /// ```
2228     /// let v = &[10, 40, 30];
2229     /// assert!(v.starts_with(&[]));
2230     /// let v: &[u8] = &[];
2231     /// assert!(v.starts_with(&[]));
2232     /// ```
2233     #[stable(feature = "rust1", since = "1.0.0")]
2234     #[must_use]
2235     pub fn starts_with(&self, needle: &[T]) -> bool
2236     where
2237         T: PartialEq,
2238     {
2239         let n = needle.len();
2240         self.len() >= n && needle == &self[..n]
2241     }
2242
2243     /// Returns `true` if `needle` is a suffix of the slice.
2244     ///
2245     /// # Examples
2246     ///
2247     /// ```
2248     /// let v = [10, 40, 30];
2249     /// assert!(v.ends_with(&[30]));
2250     /// assert!(v.ends_with(&[40, 30]));
2251     /// assert!(!v.ends_with(&[50]));
2252     /// assert!(!v.ends_with(&[50, 30]));
2253     /// ```
2254     ///
2255     /// Always returns `true` if `needle` is an empty slice:
2256     ///
2257     /// ```
2258     /// let v = &[10, 40, 30];
2259     /// assert!(v.ends_with(&[]));
2260     /// let v: &[u8] = &[];
2261     /// assert!(v.ends_with(&[]));
2262     /// ```
2263     #[stable(feature = "rust1", since = "1.0.0")]
2264     #[must_use]
2265     pub fn ends_with(&self, needle: &[T]) -> bool
2266     where
2267         T: PartialEq,
2268     {
2269         let (m, n) = (self.len(), needle.len());
2270         m >= n && needle == &self[m - n..]
2271     }
2272
2273     /// Returns a subslice with the prefix removed.
2274     ///
2275     /// If the slice starts with `prefix`, returns the subslice after the prefix, wrapped in `Some`.
2276     /// If `prefix` is empty, simply returns the original slice.
2277     ///
2278     /// If the slice does not start with `prefix`, returns `None`.
2279     ///
2280     /// # Examples
2281     ///
2282     /// ```
2283     /// let v = &[10, 40, 30];
2284     /// assert_eq!(v.strip_prefix(&[10]), Some(&[40, 30][..]));
2285     /// assert_eq!(v.strip_prefix(&[10, 40]), Some(&[30][..]));
2286     /// assert_eq!(v.strip_prefix(&[50]), None);
2287     /// assert_eq!(v.strip_prefix(&[10, 50]), None);
2288     ///
2289     /// let prefix : &str = "he";
2290     /// assert_eq!(b"hello".strip_prefix(prefix.as_bytes()),
2291     ///            Some(b"llo".as_ref()));
2292     /// ```
2293     #[must_use = "returns the subslice without modifying the original"]
2294     #[stable(feature = "slice_strip", since = "1.51.0")]
2295     pub fn strip_prefix<P: SlicePattern<Item = T> + ?Sized>(&self, prefix: &P) -> Option<&[T]>
2296     where
2297         T: PartialEq,
2298     {
2299         // This function will need rewriting if and when SlicePattern becomes more sophisticated.
2300         let prefix = prefix.as_slice();
2301         let n = prefix.len();
2302         if n <= self.len() {
2303             let (head, tail) = self.split_at(n);
2304             if head == prefix {
2305                 return Some(tail);
2306             }
2307         }
2308         None
2309     }
2310
2311     /// Returns a subslice with the suffix removed.
2312     ///
2313     /// If the slice ends with `suffix`, returns the subslice before the suffix, wrapped in `Some`.
2314     /// If `suffix` is empty, simply returns the original slice.
2315     ///
2316     /// If the slice does not end with `suffix`, returns `None`.
2317     ///
2318     /// # Examples
2319     ///
2320     /// ```
2321     /// let v = &[10, 40, 30];
2322     /// assert_eq!(v.strip_suffix(&[30]), Some(&[10, 40][..]));
2323     /// assert_eq!(v.strip_suffix(&[40, 30]), Some(&[10][..]));
2324     /// assert_eq!(v.strip_suffix(&[50]), None);
2325     /// assert_eq!(v.strip_suffix(&[50, 30]), None);
2326     /// ```
2327     #[must_use = "returns the subslice without modifying the original"]
2328     #[stable(feature = "slice_strip", since = "1.51.0")]
2329     pub fn strip_suffix<P: SlicePattern<Item = T> + ?Sized>(&self, suffix: &P) -> Option<&[T]>
2330     where
2331         T: PartialEq,
2332     {
2333         // This function will need rewriting if and when SlicePattern becomes more sophisticated.
2334         let suffix = suffix.as_slice();
2335         let (len, n) = (self.len(), suffix.len());
2336         if n <= len {
2337             let (head, tail) = self.split_at(len - n);
2338             if tail == suffix {
2339                 return Some(head);
2340             }
2341         }
2342         None
2343     }
2344
2345     /// Binary searches this slice for a given element.
2346     /// This behaves similarly to [`contains`] if this slice is sorted.
2347     ///
2348     /// If the value is found then [`Result::Ok`] is returned, containing the
2349     /// index of the matching element. If there are multiple matches, then any
2350     /// one of the matches could be returned. The index is chosen
2351     /// deterministically, but is subject to change in future versions of Rust.
2352     /// If the value is not found then [`Result::Err`] is returned, containing
2353     /// the index where a matching element could be inserted while maintaining
2354     /// sorted order.
2355     ///
2356     /// See also [`binary_search_by`], [`binary_search_by_key`], and [`partition_point`].
2357     ///
2358     /// [`contains`]: slice::contains
2359     /// [`binary_search_by`]: slice::binary_search_by
2360     /// [`binary_search_by_key`]: slice::binary_search_by_key
2361     /// [`partition_point`]: slice::partition_point
2362     ///
2363     /// # Examples
2364     ///
2365     /// Looks up a series of four elements. The first is found, with a
2366     /// uniquely determined position; the second and third are not
2367     /// found; the fourth could match any position in `[1, 4]`.
2368     ///
2369     /// ```
2370     /// let s = [0, 1, 1, 1, 1, 2, 3, 5, 8, 13, 21, 34, 55];
2371     ///
2372     /// assert_eq!(s.binary_search(&13),  Ok(9));
2373     /// assert_eq!(s.binary_search(&4),   Err(7));
2374     /// assert_eq!(s.binary_search(&100), Err(13));
2375     /// let r = s.binary_search(&1);
2376     /// assert!(match r { Ok(1..=4) => true, _ => false, });
2377     /// ```
2378     ///
2379     /// If you want to find that whole *range* of matching items, rather than
2380     /// an arbitrary matching one, that can be done using [`partition_point`]:
2381     /// ```
2382     /// let s = [0, 1, 1, 1, 1, 2, 3, 5, 8, 13, 21, 34, 55];
2383     ///
2384     /// let low = s.partition_point(|x| x < &1);
2385     /// assert_eq!(low, 1);
2386     /// let high = s.partition_point(|x| x <= &1);
2387     /// assert_eq!(high, 5);
2388     /// let r = s.binary_search(&1);
2389     /// assert!((low..high).contains(&r.unwrap()));
2390     ///
2391     /// assert!(s[..low].iter().all(|&x| x < 1));
2392     /// assert!(s[low..high].iter().all(|&x| x == 1));
2393     /// assert!(s[high..].iter().all(|&x| x > 1));
2394     ///
2395     /// // For something not found, the "range" of equal items is empty
2396     /// assert_eq!(s.partition_point(|x| x < &11), 9);
2397     /// assert_eq!(s.partition_point(|x| x <= &11), 9);
2398     /// assert_eq!(s.binary_search(&11), Err(9));
2399     /// ```
2400     ///
2401     /// If you want to insert an item to a sorted vector, while maintaining
2402     /// sort order, consider using [`partition_point`]:
2403     ///
2404     /// ```
2405     /// let mut s = vec![0, 1, 1, 1, 1, 2, 3, 5, 8, 13, 21, 34, 55];
2406     /// let num = 42;
2407     /// let idx = s.partition_point(|&x| x < num);
2408     /// // The above is equivalent to `let idx = s.binary_search(&num).unwrap_or_else(|x| x);`
2409     /// s.insert(idx, num);
2410     /// assert_eq!(s, [0, 1, 1, 1, 1, 2, 3, 5, 8, 13, 21, 34, 42, 55]);
2411     /// ```
2412     #[stable(feature = "rust1", since = "1.0.0")]
2413     pub fn binary_search(&self, x: &T) -> Result<usize, usize>
2414     where
2415         T: Ord,
2416     {
2417         self.binary_search_by(|p| p.cmp(x))
2418     }
2419
2420     /// Binary searches this slice with a comparator function.
2421     /// This behaves similarly to [`contains`] if this slice is sorted.
2422     ///
2423     /// The comparator function should implement an order consistent
2424     /// with the sort order of the underlying slice, returning an
2425     /// order code that indicates whether its argument is `Less`,
2426     /// `Equal` or `Greater` the desired target.
2427     ///
2428     /// If the value is found then [`Result::Ok`] is returned, containing the
2429     /// index of the matching element. If there are multiple matches, then any
2430     /// one of the matches could be returned. The index is chosen
2431     /// deterministically, but is subject to change in future versions of Rust.
2432     /// If the value is not found then [`Result::Err`] is returned, containing
2433     /// the index where a matching element could be inserted while maintaining
2434     /// sorted order.
2435     ///
2436     /// See also [`binary_search`], [`binary_search_by_key`], and [`partition_point`].
2437     ///
2438     /// [`contains`]: slice::contains
2439     /// [`binary_search`]: slice::binary_search
2440     /// [`binary_search_by_key`]: slice::binary_search_by_key
2441     /// [`partition_point`]: slice::partition_point
2442     ///
2443     /// # Examples
2444     ///
2445     /// Looks up a series of four elements. The first is found, with a
2446     /// uniquely determined position; the second and third are not
2447     /// found; the fourth could match any position in `[1, 4]`.
2448     ///
2449     /// ```
2450     /// let s = [0, 1, 1, 1, 1, 2, 3, 5, 8, 13, 21, 34, 55];
2451     ///
2452     /// let seek = 13;
2453     /// assert_eq!(s.binary_search_by(|probe| probe.cmp(&seek)), Ok(9));
2454     /// let seek = 4;
2455     /// assert_eq!(s.binary_search_by(|probe| probe.cmp(&seek)), Err(7));
2456     /// let seek = 100;
2457     /// assert_eq!(s.binary_search_by(|probe| probe.cmp(&seek)), Err(13));
2458     /// let seek = 1;
2459     /// let r = s.binary_search_by(|probe| probe.cmp(&seek));
2460     /// assert!(match r { Ok(1..=4) => true, _ => false, });
2461     /// ```
2462     #[stable(feature = "rust1", since = "1.0.0")]
2463     #[inline]
2464     pub fn binary_search_by<'a, F>(&'a self, mut f: F) -> Result<usize, usize>
2465     where
2466         F: FnMut(&'a T) -> Ordering,
2467     {
2468         // INVARIANTS:
2469         // - 0 <= left <= left + size = right <= self.len()
2470         // - f returns Less for everything in self[..left]
2471         // - f returns Greater for everything in self[right..]
2472         let mut size = self.len();
2473         let mut left = 0;
2474         let mut right = size;
2475         while left < right {
2476             let mid = left + size / 2;
2477
2478             // SAFETY: the while condition means `size` is strictly positive, so
2479             // `size/2 < size`.  Thus `left + size/2 < left + size`, which
2480             // coupled with the `left + size <= self.len()` invariant means
2481             // we have `left + size/2 < self.len()`, and this is in-bounds.
2482             let cmp = f(unsafe { self.get_unchecked(mid) });
2483
2484             // The reason why we use if/else control flow rather than match
2485             // is because match reorders comparison operations, which is perf sensitive.
2486             // This is x86 asm for u8: https://rust.godbolt.org/z/8Y8Pra.
2487             if cmp == Less {
2488                 left = mid + 1;
2489             } else if cmp == Greater {
2490                 right = mid;
2491             } else {
2492                 // SAFETY: same as the `get_unchecked` above
2493                 unsafe { crate::intrinsics::assume(mid < self.len()) };
2494                 return Ok(mid);
2495             }
2496
2497             size = right - left;
2498         }
2499
2500         // SAFETY: directly true from the overall invariant.
2501         // Note that this is `<=`, unlike the assume in the `Ok` path.
2502         unsafe { crate::intrinsics::assume(left <= self.len()) };
2503         Err(left)
2504     }
2505
2506     /// Binary searches this slice with a key extraction function.
2507     /// This behaves similarly to [`contains`] if this slice is sorted.
2508     ///
2509     /// Assumes that the slice is sorted by the key, for instance with
2510     /// [`sort_by_key`] using the same key extraction function.
2511     ///
2512     /// If the value is found then [`Result::Ok`] is returned, containing the
2513     /// index of the matching element. If there are multiple matches, then any
2514     /// one of the matches could be returned. The index is chosen
2515     /// deterministically, but is subject to change in future versions of Rust.
2516     /// If the value is not found then [`Result::Err`] is returned, containing
2517     /// the index where a matching element could be inserted while maintaining
2518     /// sorted order.
2519     ///
2520     /// See also [`binary_search`], [`binary_search_by`], and [`partition_point`].
2521     ///
2522     /// [`contains`]: slice::contains
2523     /// [`sort_by_key`]: slice::sort_by_key
2524     /// [`binary_search`]: slice::binary_search
2525     /// [`binary_search_by`]: slice::binary_search_by
2526     /// [`partition_point`]: slice::partition_point
2527     ///
2528     /// # Examples
2529     ///
2530     /// Looks up a series of four elements in a slice of pairs sorted by
2531     /// their second elements. The first is found, with a uniquely
2532     /// determined position; the second and third are not found; the
2533     /// fourth could match any position in `[1, 4]`.
2534     ///
2535     /// ```
2536     /// let s = [(0, 0), (2, 1), (4, 1), (5, 1), (3, 1),
2537     ///          (1, 2), (2, 3), (4, 5), (5, 8), (3, 13),
2538     ///          (1, 21), (2, 34), (4, 55)];
2539     ///
2540     /// assert_eq!(s.binary_search_by_key(&13, |&(a, b)| b),  Ok(9));
2541     /// assert_eq!(s.binary_search_by_key(&4, |&(a, b)| b),   Err(7));
2542     /// assert_eq!(s.binary_search_by_key(&100, |&(a, b)| b), Err(13));
2543     /// let r = s.binary_search_by_key(&1, |&(a, b)| b);
2544     /// assert!(match r { Ok(1..=4) => true, _ => false, });
2545     /// ```
2546     // Lint rustdoc::broken_intra_doc_links is allowed as `slice::sort_by_key` is
2547     // in crate `alloc`, and as such doesn't exists yet when building `core`: #74481.
2548     // This breaks links when slice is displayed in core, but changing it to use relative links
2549     // would break when the item is re-exported. So allow the core links to be broken for now.
2550     #[allow(rustdoc::broken_intra_doc_links)]
2551     #[stable(feature = "slice_binary_search_by_key", since = "1.10.0")]
2552     #[inline]
2553     pub fn binary_search_by_key<'a, B, F>(&'a self, b: &B, mut f: F) -> Result<usize, usize>
2554     where
2555         F: FnMut(&'a T) -> B,
2556         B: Ord,
2557     {
2558         self.binary_search_by(|k| f(k).cmp(b))
2559     }
2560
2561     /// Sorts the slice, but might not preserve the order of equal elements.
2562     ///
2563     /// This sort is unstable (i.e., may reorder equal elements), in-place
2564     /// (i.e., does not allocate), and *O*(*n* \* log(*n*)) worst-case.
2565     ///
2566     /// # Current implementation
2567     ///
2568     /// The current algorithm is based on [pattern-defeating quicksort][pdqsort] by Orson Peters,
2569     /// which combines the fast average case of randomized quicksort with the fast worst case of
2570     /// heapsort, while achieving linear time on slices with certain patterns. It uses some
2571     /// randomization to avoid degenerate cases, but with a fixed seed to always provide
2572     /// deterministic behavior.
2573     ///
2574     /// It is typically faster than stable sorting, except in a few special cases, e.g., when the
2575     /// slice consists of several concatenated sorted sequences.
2576     ///
2577     /// # Examples
2578     ///
2579     /// ```
2580     /// let mut v = [-5, 4, 1, -3, 2];
2581     ///
2582     /// v.sort_unstable();
2583     /// assert!(v == [-5, -3, 1, 2, 4]);
2584     /// ```
2585     ///
2586     /// [pdqsort]: https://github.com/orlp/pdqsort
2587     #[stable(feature = "sort_unstable", since = "1.20.0")]
2588     #[inline]
2589     pub fn sort_unstable(&mut self)
2590     where
2591         T: Ord,
2592     {
2593         sort::quicksort(self, T::lt);
2594     }
2595
2596     /// Sorts the slice with a comparator function, but might not preserve the order of equal
2597     /// elements.
2598     ///
2599     /// This sort is unstable (i.e., may reorder equal elements), in-place
2600     /// (i.e., does not allocate), and *O*(*n* \* log(*n*)) worst-case.
2601     ///
2602     /// The comparator function must define a total ordering for the elements in the slice. If
2603     /// the ordering is not total, the order of the elements is unspecified. An order is a
2604     /// total order if it is (for all `a`, `b` and `c`):
2605     ///
2606     /// * total and antisymmetric: exactly one of `a < b`, `a == b` or `a > b` is true, and
2607     /// * transitive, `a < b` and `b < c` implies `a < c`. The same must hold for both `==` and `>`.
2608     ///
2609     /// For example, while [`f64`] doesn't implement [`Ord`] because `NaN != NaN`, we can use
2610     /// `partial_cmp` as our sort function when we know the slice doesn't contain a `NaN`.
2611     ///
2612     /// ```
2613     /// let mut floats = [5f64, 4.0, 1.0, 3.0, 2.0];
2614     /// floats.sort_unstable_by(|a, b| a.partial_cmp(b).unwrap());
2615     /// assert_eq!(floats, [1.0, 2.0, 3.0, 4.0, 5.0]);
2616     /// ```
2617     ///
2618     /// # Current implementation
2619     ///
2620     /// The current algorithm is based on [pattern-defeating quicksort][pdqsort] by Orson Peters,
2621     /// which combines the fast average case of randomized quicksort with the fast worst case of
2622     /// heapsort, while achieving linear time on slices with certain patterns. It uses some
2623     /// randomization to avoid degenerate cases, but with a fixed seed to always provide
2624     /// deterministic behavior.
2625     ///
2626     /// It is typically faster than stable sorting, except in a few special cases, e.g., when the
2627     /// slice consists of several concatenated sorted sequences.
2628     ///
2629     /// # Examples
2630     ///
2631     /// ```
2632     /// let mut v = [5, 4, 1, 3, 2];
2633     /// v.sort_unstable_by(|a, b| a.cmp(b));
2634     /// assert!(v == [1, 2, 3, 4, 5]);
2635     ///
2636     /// // reverse sorting
2637     /// v.sort_unstable_by(|a, b| b.cmp(a));
2638     /// assert!(v == [5, 4, 3, 2, 1]);
2639     /// ```
2640     ///
2641     /// [pdqsort]: https://github.com/orlp/pdqsort
2642     #[stable(feature = "sort_unstable", since = "1.20.0")]
2643     #[inline]
2644     pub fn sort_unstable_by<F>(&mut self, mut compare: F)
2645     where
2646         F: FnMut(&T, &T) -> Ordering,
2647     {
2648         sort::quicksort(self, |a, b| compare(a, b) == Ordering::Less);
2649     }
2650
2651     /// Sorts the slice with a key extraction function, but might not preserve the order of equal
2652     /// elements.
2653     ///
2654     /// This sort is unstable (i.e., may reorder equal elements), in-place
2655     /// (i.e., does not allocate), and *O*(m \* *n* \* log(*n*)) worst-case, where the key function is
2656     /// *O*(*m*).
2657     ///
2658     /// # Current implementation
2659     ///
2660     /// The current algorithm is based on [pattern-defeating quicksort][pdqsort] by Orson Peters,
2661     /// which combines the fast average case of randomized quicksort with the fast worst case of
2662     /// heapsort, while achieving linear time on slices with certain patterns. It uses some
2663     /// randomization to avoid degenerate cases, but with a fixed seed to always provide
2664     /// deterministic behavior.
2665     ///
2666     /// Due to its key calling strategy, [`sort_unstable_by_key`](#method.sort_unstable_by_key)
2667     /// is likely to be slower than [`sort_by_cached_key`](#method.sort_by_cached_key) in
2668     /// cases where the key function is expensive.
2669     ///
2670     /// # Examples
2671     ///
2672     /// ```
2673     /// let mut v = [-5i32, 4, 1, -3, 2];
2674     ///
2675     /// v.sort_unstable_by_key(|k| k.abs());
2676     /// assert!(v == [1, 2, -3, 4, -5]);
2677     /// ```
2678     ///
2679     /// [pdqsort]: https://github.com/orlp/pdqsort
2680     #[stable(feature = "sort_unstable", since = "1.20.0")]
2681     #[inline]
2682     pub fn sort_unstable_by_key<K, F>(&mut self, mut f: F)
2683     where
2684         F: FnMut(&T) -> K,
2685         K: Ord,
2686     {
2687         sort::quicksort(self, |a, b| f(a).lt(&f(b)));
2688     }
2689
2690     /// Reorder the slice such that the element at `index` is at its final sorted position.
2691     ///
2692     /// This reordering has the additional property that any value at position `i < index` will be
2693     /// less than or equal to any value at a position `j > index`. Additionally, this reordering is
2694     /// unstable (i.e. any number of equal elements may end up at position `index`), in-place
2695     /// (i.e. does not allocate), and *O*(*n*) worst-case. This function is also/ known as "kth
2696     /// element" in other libraries. It returns a triplet of the following from the reordered slice:
2697     /// the subslice prior to `index`, the element at `index`, and the subslice after `index`;
2698     /// accordingly, the values in those two subslices will respectively all be less-than-or-equal-to
2699     /// and greater-than-or-equal-to the value of the element at `index`.
2700     ///
2701     /// # Current implementation
2702     ///
2703     /// The current algorithm is based on the quickselect portion of the same quicksort algorithm
2704     /// used for [`sort_unstable`].
2705     ///
2706     /// [`sort_unstable`]: slice::sort_unstable
2707     ///
2708     /// # Panics
2709     ///
2710     /// Panics when `index >= len()`, meaning it always panics on empty slices.
2711     ///
2712     /// # Examples
2713     ///
2714     /// ```
2715     /// let mut v = [-5i32, 4, 1, -3, 2];
2716     ///
2717     /// // Find the median
2718     /// v.select_nth_unstable(2);
2719     ///
2720     /// // We are only guaranteed the slice will be one of the following, based on the way we sort
2721     /// // about the specified index.
2722     /// assert!(v == [-3, -5, 1, 2, 4] ||
2723     ///         v == [-5, -3, 1, 2, 4] ||
2724     ///         v == [-3, -5, 1, 4, 2] ||
2725     ///         v == [-5, -3, 1, 4, 2]);
2726     /// ```
2727     #[stable(feature = "slice_select_nth_unstable", since = "1.49.0")]
2728     #[inline]
2729     pub fn select_nth_unstable(&mut self, index: usize) -> (&mut [T], &mut T, &mut [T])
2730     where
2731         T: Ord,
2732     {
2733         sort::partition_at_index(self, index, T::lt)
2734     }
2735
2736     /// Reorder the slice with a comparator function such that the element at `index` is at its
2737     /// final sorted position.
2738     ///
2739     /// This reordering has the additional property that any value at position `i < index` will be
2740     /// less than or equal to any value at a position `j > index` using the comparator function.
2741     /// Additionally, this reordering is unstable (i.e. any number of equal elements may end up at
2742     /// position `index`), in-place (i.e. does not allocate), and *O*(*n*) worst-case. This function
2743     /// is also known as "kth element" in other libraries. It returns a triplet of the following from
2744     /// the slice reordered according to the provided comparator function: the subslice prior to
2745     /// `index`, the element at `index`, and the subslice after `index`; accordingly, the values in
2746     /// those two subslices will respectively all be less-than-or-equal-to and greater-than-or-equal-to
2747     /// the value of the element at `index`.
2748     ///
2749     /// # Current implementation
2750     ///
2751     /// The current algorithm is based on the quickselect portion of the same quicksort algorithm
2752     /// used for [`sort_unstable`].
2753     ///
2754     /// [`sort_unstable`]: slice::sort_unstable
2755     ///
2756     /// # Panics
2757     ///
2758     /// Panics when `index >= len()`, meaning it always panics on empty slices.
2759     ///
2760     /// # Examples
2761     ///
2762     /// ```
2763     /// let mut v = [-5i32, 4, 1, -3, 2];
2764     ///
2765     /// // Find the median as if the slice were sorted in descending order.
2766     /// v.select_nth_unstable_by(2, |a, b| b.cmp(a));
2767     ///
2768     /// // We are only guaranteed the slice will be one of the following, based on the way we sort
2769     /// // about the specified index.
2770     /// assert!(v == [2, 4, 1, -5, -3] ||
2771     ///         v == [2, 4, 1, -3, -5] ||
2772     ///         v == [4, 2, 1, -5, -3] ||
2773     ///         v == [4, 2, 1, -3, -5]);
2774     /// ```
2775     #[stable(feature = "slice_select_nth_unstable", since = "1.49.0")]
2776     #[inline]
2777     pub fn select_nth_unstable_by<F>(
2778         &mut self,
2779         index: usize,
2780         mut compare: F,
2781     ) -> (&mut [T], &mut T, &mut [T])
2782     where
2783         F: FnMut(&T, &T) -> Ordering,
2784     {
2785         sort::partition_at_index(self, index, |a: &T, b: &T| compare(a, b) == Less)
2786     }
2787
2788     /// Reorder the slice with a key extraction function such that the element at `index` is at its
2789     /// final sorted position.
2790     ///
2791     /// This reordering has the additional property that any value at position `i < index` will be
2792     /// less than or equal to any value at a position `j > index` using the key extraction function.
2793     /// Additionally, this reordering is unstable (i.e. any number of equal elements may end up at
2794     /// position `index`), in-place (i.e. does not allocate), and *O*(*n*) worst-case. This function
2795     /// is also known as "kth element" in other libraries. It returns a triplet of the following from
2796     /// the slice reordered according to the provided key extraction function: the subslice prior to
2797     /// `index`, the element at `index`, and the subslice after `index`; accordingly, the values in
2798     /// those two subslices will respectively all be less-than-or-equal-to and greater-than-or-equal-to
2799     /// the value of the element at `index`.
2800     ///
2801     /// # Current implementation
2802     ///
2803     /// The current algorithm is based on the quickselect portion of the same quicksort algorithm
2804     /// used for [`sort_unstable`].
2805     ///
2806     /// [`sort_unstable`]: slice::sort_unstable
2807     ///
2808     /// # Panics
2809     ///
2810     /// Panics when `index >= len()`, meaning it always panics on empty slices.
2811     ///
2812     /// # Examples
2813     ///
2814     /// ```
2815     /// let mut v = [-5i32, 4, 1, -3, 2];
2816     ///
2817     /// // Return the median as if the array were sorted according to absolute value.
2818     /// v.select_nth_unstable_by_key(2, |a| a.abs());
2819     ///
2820     /// // We are only guaranteed the slice will be one of the following, based on the way we sort
2821     /// // about the specified index.
2822     /// assert!(v == [1, 2, -3, 4, -5] ||
2823     ///         v == [1, 2, -3, -5, 4] ||
2824     ///         v == [2, 1, -3, 4, -5] ||
2825     ///         v == [2, 1, -3, -5, 4]);
2826     /// ```
2827     #[stable(feature = "slice_select_nth_unstable", since = "1.49.0")]
2828     #[inline]
2829     pub fn select_nth_unstable_by_key<K, F>(
2830         &mut self,
2831         index: usize,
2832         mut f: F,
2833     ) -> (&mut [T], &mut T, &mut [T])
2834     where
2835         F: FnMut(&T) -> K,
2836         K: Ord,
2837     {
2838         sort::partition_at_index(self, index, |a: &T, b: &T| f(a).lt(&f(b)))
2839     }
2840
2841     /// Moves all consecutive repeated elements to the end of the slice according to the
2842     /// [`PartialEq`] trait implementation.
2843     ///
2844     /// Returns two slices. The first contains no consecutive repeated elements.
2845     /// The second contains all the duplicates in no specified order.
2846     ///
2847     /// If the slice is sorted, the first returned slice contains no duplicates.
2848     ///
2849     /// # Examples
2850     ///
2851     /// ```
2852     /// #![feature(slice_partition_dedup)]
2853     ///
2854     /// let mut slice = [1, 2, 2, 3, 3, 2, 1, 1];
2855     ///
2856     /// let (dedup, duplicates) = slice.partition_dedup();
2857     ///
2858     /// assert_eq!(dedup, [1, 2, 3, 2, 1]);
2859     /// assert_eq!(duplicates, [2, 3, 1]);
2860     /// ```
2861     #[unstable(feature = "slice_partition_dedup", issue = "54279")]
2862     #[inline]
2863     pub fn partition_dedup(&mut self) -> (&mut [T], &mut [T])
2864     where
2865         T: PartialEq,
2866     {
2867         self.partition_dedup_by(|a, b| a == b)
2868     }
2869
2870     /// Moves all but the first of consecutive elements to the end of the slice satisfying
2871     /// a given equality relation.
2872     ///
2873     /// Returns two slices. The first contains no consecutive repeated elements.
2874     /// The second contains all the duplicates in no specified order.
2875     ///
2876     /// The `same_bucket` function is passed references to two elements from the slice and
2877     /// must determine if the elements compare equal. The elements are passed in opposite order
2878     /// from their order in the slice, so if `same_bucket(a, b)` returns `true`, `a` is moved
2879     /// at the end of the slice.
2880     ///
2881     /// If the slice is sorted, the first returned slice contains no duplicates.
2882     ///
2883     /// # Examples
2884     ///
2885     /// ```
2886     /// #![feature(slice_partition_dedup)]
2887     ///
2888     /// let mut slice = ["foo", "Foo", "BAZ", "Bar", "bar", "baz", "BAZ"];
2889     ///
2890     /// let (dedup, duplicates) = slice.partition_dedup_by(|a, b| a.eq_ignore_ascii_case(b));
2891     ///
2892     /// assert_eq!(dedup, ["foo", "BAZ", "Bar", "baz"]);
2893     /// assert_eq!(duplicates, ["bar", "Foo", "BAZ"]);
2894     /// ```
2895     #[unstable(feature = "slice_partition_dedup", issue = "54279")]
2896     #[inline]
2897     pub fn partition_dedup_by<F>(&mut self, mut same_bucket: F) -> (&mut [T], &mut [T])
2898     where
2899         F: FnMut(&mut T, &mut T) -> bool,
2900     {
2901         // Although we have a mutable reference to `self`, we cannot make
2902         // *arbitrary* changes. The `same_bucket` calls could panic, so we
2903         // must ensure that the slice is in a valid state at all times.
2904         //
2905         // The way that we handle this is by using swaps; we iterate
2906         // over all the elements, swapping as we go so that at the end
2907         // the elements we wish to keep are in the front, and those we
2908         // wish to reject are at the back. We can then split the slice.
2909         // This operation is still `O(n)`.
2910         //
2911         // Example: We start in this state, where `r` represents "next
2912         // read" and `w` represents "next_write`.
2913         //
2914         //           r
2915         //     +---+---+---+---+---+---+
2916         //     | 0 | 1 | 1 | 2 | 3 | 3 |
2917         //     +---+---+---+---+---+---+
2918         //           w
2919         //
2920         // Comparing self[r] against self[w-1], this is not a duplicate, so
2921         // we swap self[r] and self[w] (no effect as r==w) and then increment both
2922         // r and w, leaving us with:
2923         //
2924         //               r
2925         //     +---+---+---+---+---+---+
2926         //     | 0 | 1 | 1 | 2 | 3 | 3 |
2927         //     +---+---+---+---+---+---+
2928         //               w
2929         //
2930         // Comparing self[r] against self[w-1], this value is a duplicate,
2931         // so we increment `r` but leave everything else unchanged:
2932         //
2933         //                   r
2934         //     +---+---+---+---+---+---+
2935         //     | 0 | 1 | 1 | 2 | 3 | 3 |
2936         //     +---+---+---+---+---+---+
2937         //               w
2938         //
2939         // Comparing self[r] against self[w-1], this is not a duplicate,
2940         // so swap self[r] and self[w] and advance r and w:
2941         //
2942         //                       r
2943         //     +---+---+---+---+---+---+
2944         //     | 0 | 1 | 2 | 1 | 3 | 3 |
2945         //     +---+---+---+---+---+---+
2946         //                   w
2947         //
2948         // Not a duplicate, repeat:
2949         //
2950         //                           r
2951         //     +---+---+---+---+---+---+
2952         //     | 0 | 1 | 2 | 3 | 1 | 3 |
2953         //     +---+---+---+---+---+---+
2954         //                       w
2955         //
2956         // Duplicate, advance r. End of slice. Split at w.
2957
2958         let len = self.len();
2959         if len <= 1 {
2960             return (self, &mut []);
2961         }
2962
2963         let ptr = self.as_mut_ptr();
2964         let mut next_read: usize = 1;
2965         let mut next_write: usize = 1;
2966
2967         // SAFETY: the `while` condition guarantees `next_read` and `next_write`
2968         // are less than `len`, thus are inside `self`. `prev_ptr_write` points to
2969         // one element before `ptr_write`, but `next_write` starts at 1, so
2970         // `prev_ptr_write` is never less than 0 and is inside the slice.
2971         // This fulfils the requirements for dereferencing `ptr_read`, `prev_ptr_write`
2972         // and `ptr_write`, and for using `ptr.add(next_read)`, `ptr.add(next_write - 1)`
2973         // and `prev_ptr_write.offset(1)`.
2974         //
2975         // `next_write` is also incremented at most once per loop at most meaning
2976         // no element is skipped when it may need to be swapped.
2977         //
2978         // `ptr_read` and `prev_ptr_write` never point to the same element. This
2979         // is required for `&mut *ptr_read`, `&mut *prev_ptr_write` to be safe.
2980         // The explanation is simply that `next_read >= next_write` is always true,
2981         // thus `next_read > next_write - 1` is too.
2982         unsafe {
2983             // Avoid bounds checks by using raw pointers.
2984             while next_read < len {
2985                 let ptr_read = ptr.add(next_read);
2986                 let prev_ptr_write = ptr.add(next_write - 1);
2987                 if !same_bucket(&mut *ptr_read, &mut *prev_ptr_write) {
2988                     if next_read != next_write {
2989                         let ptr_write = prev_ptr_write.add(1);
2990                         mem::swap(&mut *ptr_read, &mut *ptr_write);
2991                     }
2992                     next_write += 1;
2993                 }
2994                 next_read += 1;
2995             }
2996         }
2997
2998         self.split_at_mut(next_write)
2999     }
3000
3001     /// Moves all but the first of consecutive elements to the end of the slice that resolve
3002     /// to the same key.
3003     ///
3004     /// Returns two slices. The first contains no consecutive repeated elements.
3005     /// The second contains all the duplicates in no specified order.
3006     ///
3007     /// If the slice is sorted, the first returned slice contains no duplicates.
3008     ///
3009     /// # Examples
3010     ///
3011     /// ```
3012     /// #![feature(slice_partition_dedup)]
3013     ///
3014     /// let mut slice = [10, 20, 21, 30, 30, 20, 11, 13];
3015     ///
3016     /// let (dedup, duplicates) = slice.partition_dedup_by_key(|i| *i / 10);
3017     ///
3018     /// assert_eq!(dedup, [10, 20, 30, 20, 11]);
3019     /// assert_eq!(duplicates, [21, 30, 13]);
3020     /// ```
3021     #[unstable(feature = "slice_partition_dedup", issue = "54279")]
3022     #[inline]
3023     pub fn partition_dedup_by_key<K, F>(&mut self, mut key: F) -> (&mut [T], &mut [T])
3024     where
3025         F: FnMut(&mut T) -> K,
3026         K: PartialEq,
3027     {
3028         self.partition_dedup_by(|a, b| key(a) == key(b))
3029     }
3030
3031     /// Rotates the slice in-place such that the first `mid` elements of the
3032     /// slice move to the end while the last `self.len() - mid` elements move to
3033     /// the front. After calling `rotate_left`, the element previously at index
3034     /// `mid` will become the first element in the slice.
3035     ///
3036     /// # Panics
3037     ///
3038     /// This function will panic if `mid` is greater than the length of the
3039     /// slice. Note that `mid == self.len()` does _not_ panic and is a no-op
3040     /// rotation.
3041     ///
3042     /// # Complexity
3043     ///
3044     /// Takes linear (in `self.len()`) time.
3045     ///
3046     /// # Examples
3047     ///
3048     /// ```
3049     /// let mut a = ['a', 'b', 'c', 'd', 'e', 'f'];
3050     /// a.rotate_left(2);
3051     /// assert_eq!(a, ['c', 'd', 'e', 'f', 'a', 'b']);
3052     /// ```
3053     ///
3054     /// Rotating a subslice:
3055     ///
3056     /// ```
3057     /// let mut a = ['a', 'b', 'c', 'd', 'e', 'f'];
3058     /// a[1..5].rotate_left(1);
3059     /// assert_eq!(a, ['a', 'c', 'd', 'e', 'b', 'f']);
3060     /// ```
3061     #[stable(feature = "slice_rotate", since = "1.26.0")]
3062     pub fn rotate_left(&mut self, mid: usize) {
3063         assert!(mid <= self.len());
3064         let k = self.len() - mid;
3065         let p = self.as_mut_ptr();
3066
3067         // SAFETY: The range `[p.add(mid) - mid, p.add(mid) + k)` is trivially
3068         // valid for reading and writing, as required by `ptr_rotate`.
3069         unsafe {
3070             rotate::ptr_rotate(mid, p.add(mid), k);
3071         }
3072     }
3073
3074     /// Rotates the slice in-place such that the first `self.len() - k`
3075     /// elements of the slice move to the end while the last `k` elements move
3076     /// to the front. After calling `rotate_right`, the element previously at
3077     /// index `self.len() - k` will become the first element in the slice.
3078     ///
3079     /// # Panics
3080     ///
3081     /// This function will panic if `k` is greater than the length of the
3082     /// slice. Note that `k == self.len()` does _not_ panic and is a no-op
3083     /// rotation.
3084     ///
3085     /// # Complexity
3086     ///
3087     /// Takes linear (in `self.len()`) time.
3088     ///
3089     /// # Examples
3090     ///
3091     /// ```
3092     /// let mut a = ['a', 'b', 'c', 'd', 'e', 'f'];
3093     /// a.rotate_right(2);
3094     /// assert_eq!(a, ['e', 'f', 'a', 'b', 'c', 'd']);
3095     /// ```
3096     ///
3097     /// Rotate a subslice:
3098     ///
3099     /// ```
3100     /// let mut a = ['a', 'b', 'c', 'd', 'e', 'f'];
3101     /// a[1..5].rotate_right(1);
3102     /// assert_eq!(a, ['a', 'e', 'b', 'c', 'd', 'f']);
3103     /// ```
3104     #[stable(feature = "slice_rotate", since = "1.26.0")]
3105     pub fn rotate_right(&mut self, k: usize) {
3106         assert!(k <= self.len());
3107         let mid = self.len() - k;
3108         let p = self.as_mut_ptr();
3109
3110         // SAFETY: The range `[p.add(mid) - mid, p.add(mid) + k)` is trivially
3111         // valid for reading and writing, as required by `ptr_rotate`.
3112         unsafe {
3113             rotate::ptr_rotate(mid, p.add(mid), k);
3114         }
3115     }
3116
3117     /// Fills `self` with elements by cloning `value`.
3118     ///
3119     /// # Examples
3120     ///
3121     /// ```
3122     /// let mut buf = vec![0; 10];
3123     /// buf.fill(1);
3124     /// assert_eq!(buf, vec![1; 10]);
3125     /// ```
3126     #[doc(alias = "memset")]
3127     #[stable(feature = "slice_fill", since = "1.50.0")]
3128     pub fn fill(&mut self, value: T)
3129     where
3130         T: Clone,
3131     {
3132         specialize::SpecFill::spec_fill(self, value);
3133     }
3134
3135     /// Fills `self` with elements returned by calling a closure repeatedly.
3136     ///
3137     /// This method uses a closure to create new values. If you'd rather
3138     /// [`Clone`] a given value, use [`fill`]. If you want to use the [`Default`]
3139     /// trait to generate values, you can pass [`Default::default`] as the
3140     /// argument.
3141     ///
3142     /// [`fill`]: slice::fill
3143     ///
3144     /// # Examples
3145     ///
3146     /// ```
3147     /// let mut buf = vec![1; 10];
3148     /// buf.fill_with(Default::default);
3149     /// assert_eq!(buf, vec![0; 10]);
3150     /// ```
3151     #[stable(feature = "slice_fill_with", since = "1.51.0")]
3152     pub fn fill_with<F>(&mut self, mut f: F)
3153     where
3154         F: FnMut() -> T,
3155     {
3156         for el in self {
3157             *el = f();
3158         }
3159     }
3160
3161     /// Copies the elements from `src` into `self`.
3162     ///
3163     /// The length of `src` must be the same as `self`.
3164     ///
3165     /// # Panics
3166     ///
3167     /// This function will panic if the two slices have different lengths.
3168     ///
3169     /// # Examples
3170     ///
3171     /// Cloning two elements from a slice into another:
3172     ///
3173     /// ```
3174     /// let src = [1, 2, 3, 4];
3175     /// let mut dst = [0, 0];
3176     ///
3177     /// // Because the slices have to be the same length,
3178     /// // we slice the source slice from four elements
3179     /// // to two. It will panic if we don't do this.
3180     /// dst.clone_from_slice(&src[2..]);
3181     ///
3182     /// assert_eq!(src, [1, 2, 3, 4]);
3183     /// assert_eq!(dst, [3, 4]);
3184     /// ```
3185     ///
3186     /// Rust enforces that there can only be one mutable reference with no
3187     /// immutable references to a particular piece of data in a particular
3188     /// scope. Because of this, attempting to use `clone_from_slice` on a
3189     /// single slice will result in a compile failure:
3190     ///
3191     /// ```compile_fail
3192     /// let mut slice = [1, 2, 3, 4, 5];
3193     ///
3194     /// slice[..2].clone_from_slice(&slice[3..]); // compile fail!
3195     /// ```
3196     ///
3197     /// To work around this, we can use [`split_at_mut`] to create two distinct
3198     /// sub-slices from a slice:
3199     ///
3200     /// ```
3201     /// let mut slice = [1, 2, 3, 4, 5];
3202     ///
3203     /// {
3204     ///     let (left, right) = slice.split_at_mut(2);
3205     ///     left.clone_from_slice(&right[1..]);
3206     /// }
3207     ///
3208     /// assert_eq!(slice, [4, 5, 3, 4, 5]);
3209     /// ```
3210     ///
3211     /// [`copy_from_slice`]: slice::copy_from_slice
3212     /// [`split_at_mut`]: slice::split_at_mut
3213     #[stable(feature = "clone_from_slice", since = "1.7.0")]
3214     #[track_caller]
3215     pub fn clone_from_slice(&mut self, src: &[T])
3216     where
3217         T: Clone,
3218     {
3219         self.spec_clone_from(src);
3220     }
3221
3222     /// Copies all elements from `src` into `self`, using a memcpy.
3223     ///
3224     /// The length of `src` must be the same as `self`.
3225     ///
3226     /// If `T` does not implement `Copy`, use [`clone_from_slice`].
3227     ///
3228     /// # Panics
3229     ///
3230     /// This function will panic if the two slices have different lengths.
3231     ///
3232     /// # Examples
3233     ///
3234     /// Copying two elements from a slice into another:
3235     ///
3236     /// ```
3237     /// let src = [1, 2, 3, 4];
3238     /// let mut dst = [0, 0];
3239     ///
3240     /// // Because the slices have to be the same length,
3241     /// // we slice the source slice from four elements
3242     /// // to two. It will panic if we don't do this.
3243     /// dst.copy_from_slice(&src[2..]);
3244     ///
3245     /// assert_eq!(src, [1, 2, 3, 4]);
3246     /// assert_eq!(dst, [3, 4]);
3247     /// ```
3248     ///
3249     /// Rust enforces that there can only be one mutable reference with no
3250     /// immutable references to a particular piece of data in a particular
3251     /// scope. Because of this, attempting to use `copy_from_slice` on a
3252     /// single slice will result in a compile failure:
3253     ///
3254     /// ```compile_fail
3255     /// let mut slice = [1, 2, 3, 4, 5];
3256     ///
3257     /// slice[..2].copy_from_slice(&slice[3..]); // compile fail!
3258     /// ```
3259     ///
3260     /// To work around this, we can use [`split_at_mut`] to create two distinct
3261     /// sub-slices from a slice:
3262     ///
3263     /// ```
3264     /// let mut slice = [1, 2, 3, 4, 5];
3265     ///
3266     /// {
3267     ///     let (left, right) = slice.split_at_mut(2);
3268     ///     left.copy_from_slice(&right[1..]);
3269     /// }
3270     ///
3271     /// assert_eq!(slice, [4, 5, 3, 4, 5]);
3272     /// ```
3273     ///
3274     /// [`clone_from_slice`]: slice::clone_from_slice
3275     /// [`split_at_mut`]: slice::split_at_mut
3276     #[doc(alias = "memcpy")]
3277     #[stable(feature = "copy_from_slice", since = "1.9.0")]
3278     #[track_caller]
3279     pub fn copy_from_slice(&mut self, src: &[T])
3280     where
3281         T: Copy,
3282     {
3283         // The panic code path was put into a cold function to not bloat the
3284         // call site.
3285         #[inline(never)]
3286         #[cold]
3287         #[track_caller]
3288         fn len_mismatch_fail(dst_len: usize, src_len: usize) -> ! {
3289             panic!(
3290                 "source slice length ({}) does not match destination slice length ({})",
3291                 src_len, dst_len,
3292             );
3293         }
3294
3295         if self.len() != src.len() {
3296             len_mismatch_fail(self.len(), src.len());
3297         }
3298
3299         // SAFETY: `self` is valid for `self.len()` elements by definition, and `src` was
3300         // checked to have the same length. The slices cannot overlap because
3301         // mutable references are exclusive.
3302         unsafe {
3303             ptr::copy_nonoverlapping(src.as_ptr(), self.as_mut_ptr(), self.len());
3304         }
3305     }
3306
3307     /// Copies elements from one part of the slice to another part of itself,
3308     /// using a memmove.
3309     ///
3310     /// `src` is the range within `self` to copy from. `dest` is the starting
3311     /// index of the range within `self` to copy to, which will have the same
3312     /// length as `src`. The two ranges may overlap. The ends of the two ranges
3313     /// must be less than or equal to `self.len()`.
3314     ///
3315     /// # Panics
3316     ///
3317     /// This function will panic if either range exceeds the end of the slice,
3318     /// or if the end of `src` is before the start.
3319     ///
3320     /// # Examples
3321     ///
3322     /// Copying four bytes within a slice:
3323     ///
3324     /// ```
3325     /// let mut bytes = *b"Hello, World!";
3326     ///
3327     /// bytes.copy_within(1..5, 8);
3328     ///
3329     /// assert_eq!(&bytes, b"Hello, Wello!");
3330     /// ```
3331     #[stable(feature = "copy_within", since = "1.37.0")]
3332     #[track_caller]
3333     pub fn copy_within<R: RangeBounds<usize>>(&mut self, src: R, dest: usize)
3334     where
3335         T: Copy,
3336     {
3337         let Range { start: src_start, end: src_end } = slice::range(src, ..self.len());
3338         let count = src_end - src_start;
3339         assert!(dest <= self.len() - count, "dest is out of bounds");
3340         // SAFETY: the conditions for `ptr::copy` have all been checked above,
3341         // as have those for `ptr::add`.
3342         unsafe {
3343             // Derive both `src_ptr` and `dest_ptr` from the same loan
3344             let ptr = self.as_mut_ptr();
3345             let src_ptr = ptr.add(src_start);
3346             let dest_ptr = ptr.add(dest);
3347             ptr::copy(src_ptr, dest_ptr, count);
3348         }
3349     }
3350
3351     /// Swaps all elements in `self` with those in `other`.
3352     ///
3353     /// The length of `other` must be the same as `self`.
3354     ///
3355     /// # Panics
3356     ///
3357     /// This function will panic if the two slices have different lengths.
3358     ///
3359     /// # Example
3360     ///
3361     /// Swapping two elements across slices:
3362     ///
3363     /// ```
3364     /// let mut slice1 = [0, 0];
3365     /// let mut slice2 = [1, 2, 3, 4];
3366     ///
3367     /// slice1.swap_with_slice(&mut slice2[2..]);
3368     ///
3369     /// assert_eq!(slice1, [3, 4]);
3370     /// assert_eq!(slice2, [1, 2, 0, 0]);
3371     /// ```
3372     ///
3373     /// Rust enforces that there can only be one mutable reference to a
3374     /// particular piece of data in a particular scope. Because of this,
3375     /// attempting to use `swap_with_slice` on a single slice will result in
3376     /// a compile failure:
3377     ///
3378     /// ```compile_fail
3379     /// let mut slice = [1, 2, 3, 4, 5];
3380     /// slice[..2].swap_with_slice(&mut slice[3..]); // compile fail!
3381     /// ```
3382     ///
3383     /// To work around this, we can use [`split_at_mut`] to create two distinct
3384     /// mutable sub-slices from a slice:
3385     ///
3386     /// ```
3387     /// let mut slice = [1, 2, 3, 4, 5];
3388     ///
3389     /// {
3390     ///     let (left, right) = slice.split_at_mut(2);
3391     ///     left.swap_with_slice(&mut right[1..]);
3392     /// }
3393     ///
3394     /// assert_eq!(slice, [4, 5, 3, 1, 2]);
3395     /// ```
3396     ///
3397     /// [`split_at_mut`]: slice::split_at_mut
3398     #[stable(feature = "swap_with_slice", since = "1.27.0")]
3399     #[track_caller]
3400     pub fn swap_with_slice(&mut self, other: &mut [T]) {
3401         assert!(self.len() == other.len(), "destination and source slices have different lengths");
3402         // SAFETY: `self` is valid for `self.len()` elements by definition, and `src` was
3403         // checked to have the same length. The slices cannot overlap because
3404         // mutable references are exclusive.
3405         unsafe {
3406             ptr::swap_nonoverlapping(self.as_mut_ptr(), other.as_mut_ptr(), self.len());
3407         }
3408     }
3409
3410     /// Function to calculate lengths of the middle and trailing slice for `align_to{,_mut}`.
3411     fn align_to_offsets<U>(&self) -> (usize, usize) {
3412         // What we gonna do about `rest` is figure out what multiple of `U`s we can put in a
3413         // lowest number of `T`s. And how many `T`s we need for each such "multiple".
3414         //
3415         // Consider for example T=u8 U=u16. Then we can put 1 U in 2 Ts. Simple. Now, consider
3416         // for example a case where size_of::<T> = 16, size_of::<U> = 24. We can put 2 Us in
3417         // place of every 3 Ts in the `rest` slice. A bit more complicated.
3418         //
3419         // Formula to calculate this is:
3420         //
3421         // Us = lcm(size_of::<T>, size_of::<U>) / size_of::<U>
3422         // Ts = lcm(size_of::<T>, size_of::<U>) / size_of::<T>
3423         //
3424         // Expanded and simplified:
3425         //
3426         // Us = size_of::<T> / gcd(size_of::<T>, size_of::<U>)
3427         // Ts = size_of::<U> / gcd(size_of::<T>, size_of::<U>)
3428         //
3429         // Luckily since all this is constant-evaluated... performance here matters not!
3430         #[inline]
3431         fn gcd(a: usize, b: usize) -> usize {
3432             use crate::intrinsics;
3433             // iterative stein’s algorithm
3434             // We should still make this `const fn` (and revert to recursive algorithm if we do)
3435             // because relying on llvm to consteval all this is… well, it makes me uncomfortable.
3436
3437             // SAFETY: `a` and `b` are checked to be non-zero values.
3438             let (ctz_a, mut ctz_b) = unsafe {
3439                 if a == 0 {
3440                     return b;
3441                 }
3442                 if b == 0 {
3443                     return a;
3444                 }
3445                 (intrinsics::cttz_nonzero(a), intrinsics::cttz_nonzero(b))
3446             };
3447             let k = ctz_a.min(ctz_b);
3448             let mut a = a >> ctz_a;
3449             let mut b = b;
3450             loop {
3451                 // remove all factors of 2 from b
3452                 b >>= ctz_b;
3453                 if a > b {
3454                     mem::swap(&mut a, &mut b);
3455                 }
3456                 b = b - a;
3457                 // SAFETY: `b` is checked to be non-zero.
3458                 unsafe {
3459                     if b == 0 {
3460                         break;
3461                     }
3462                     ctz_b = intrinsics::cttz_nonzero(b);
3463                 }
3464             }
3465             a << k
3466         }
3467         let gcd: usize = gcd(mem::size_of::<T>(), mem::size_of::<U>());
3468         let ts: usize = mem::size_of::<U>() / gcd;
3469         let us: usize = mem::size_of::<T>() / gcd;
3470
3471         // Armed with this knowledge, we can find how many `U`s we can fit!
3472         let us_len = self.len() / ts * us;
3473         // And how many `T`s will be in the trailing slice!
3474         let ts_len = self.len() % ts;
3475         (us_len, ts_len)
3476     }
3477
3478     /// Transmute the slice to a slice of another type, ensuring alignment of the types is
3479     /// maintained.
3480     ///
3481     /// This method splits the slice into three distinct slices: prefix, correctly aligned middle
3482     /// slice of a new type, and the suffix slice. How exactly the slice is split up is not
3483     /// specified; the middle part may be smaller than necessary. However, if this fails to return a
3484     /// maximal middle part, that is because code is running in a context where performance does not
3485     /// matter, such as a sanitizer attempting to find alignment bugs. Regular code running
3486     /// in a default (debug or release) execution *will* return a maximal middle part.
3487     ///
3488     /// This method has no purpose when either input element `T` or output element `U` are
3489     /// zero-sized and will return the original slice without splitting anything.
3490     ///
3491     /// # Safety
3492     ///
3493     /// This method is essentially a `transmute` with respect to the elements in the returned
3494     /// middle slice, so all the usual caveats pertaining to `transmute::<T, U>` also apply here.
3495     ///
3496     /// # Examples
3497     ///
3498     /// Basic usage:
3499     ///
3500     /// ```
3501     /// unsafe {
3502     ///     let bytes: [u8; 7] = [1, 2, 3, 4, 5, 6, 7];
3503     ///     let (prefix, shorts, suffix) = bytes.align_to::<u16>();
3504     ///     // less_efficient_algorithm_for_bytes(prefix);
3505     ///     // more_efficient_algorithm_for_aligned_shorts(shorts);
3506     ///     // less_efficient_algorithm_for_bytes(suffix);
3507     /// }
3508     /// ```
3509     #[stable(feature = "slice_align_to", since = "1.30.0")]
3510     #[must_use]
3511     pub unsafe fn align_to<U>(&self) -> (&[T], &[U], &[T]) {
3512         // Note that most of this function will be constant-evaluated,
3513         if U::IS_ZST || T::IS_ZST {
3514             // handle ZSTs specially, which is â€“ don't handle them at all.
3515             return (self, &[], &[]);
3516         }
3517
3518         // First, find at what point do we split between the first and 2nd slice. Easy with
3519         // ptr.align_offset.
3520         let ptr = self.as_ptr();
3521         // SAFETY: See the `align_to_mut` method for the detailed safety comment.
3522         let offset = unsafe { crate::ptr::align_offset(ptr, mem::align_of::<U>()) };
3523         if offset > self.len() {
3524             (self, &[], &[])
3525         } else {
3526             let (left, rest) = self.split_at(offset);
3527             let (us_len, ts_len) = rest.align_to_offsets::<U>();
3528             // SAFETY: now `rest` is definitely aligned, so `from_raw_parts` below is okay,
3529             // since the caller guarantees that we can transmute `T` to `U` safely.
3530             unsafe {
3531                 (
3532                     left,
3533                     from_raw_parts(rest.as_ptr() as *const U, us_len),
3534                     from_raw_parts(rest.as_ptr().add(rest.len() - ts_len), ts_len),
3535                 )
3536             }
3537         }
3538     }
3539
3540     /// Transmute the mutable slice to a mutable slice of another type, ensuring alignment of the
3541     /// types is maintained.
3542     ///
3543     /// This method splits the slice into three distinct slices: prefix, correctly aligned middle
3544     /// slice of a new type, and the suffix slice. How exactly the slice is split up is not
3545     /// specified; the middle part may be smaller than necessary. However, if this fails to return a
3546     /// maximal middle part, that is because code is running in a context where performance does not
3547     /// matter, such as a sanitizer attempting to find alignment bugs. Regular code running
3548     /// in a default (debug or release) execution *will* return a maximal middle part.
3549     ///
3550     /// This method has no purpose when either input element `T` or output element `U` are
3551     /// zero-sized and will return the original slice without splitting anything.
3552     ///
3553     /// # Safety
3554     ///
3555     /// This method is essentially a `transmute` with respect to the elements in the returned
3556     /// middle slice, so all the usual caveats pertaining to `transmute::<T, U>` also apply here.
3557     ///
3558     /// # Examples
3559     ///
3560     /// Basic usage:
3561     ///
3562     /// ```
3563     /// unsafe {
3564     ///     let mut bytes: [u8; 7] = [1, 2, 3, 4, 5, 6, 7];
3565     ///     let (prefix, shorts, suffix) = bytes.align_to_mut::<u16>();
3566     ///     // less_efficient_algorithm_for_bytes(prefix);
3567     ///     // more_efficient_algorithm_for_aligned_shorts(shorts);
3568     ///     // less_efficient_algorithm_for_bytes(suffix);
3569     /// }
3570     /// ```
3571     #[stable(feature = "slice_align_to", since = "1.30.0")]
3572     #[must_use]
3573     pub unsafe fn align_to_mut<U>(&mut self) -> (&mut [T], &mut [U], &mut [T]) {
3574         // Note that most of this function will be constant-evaluated,
3575         if U::IS_ZST || T::IS_ZST {
3576             // handle ZSTs specially, which is â€“ don't handle them at all.
3577             return (self, &mut [], &mut []);
3578         }
3579
3580         // First, find at what point do we split between the first and 2nd slice. Easy with
3581         // ptr.align_offset.
3582         let ptr = self.as_ptr();
3583         // SAFETY: Here we are ensuring we will use aligned pointers for U for the
3584         // rest of the method. This is done by passing a pointer to &[T] with an
3585         // alignment targeted for U.
3586         // `crate::ptr::align_offset` is called with a correctly aligned and
3587         // valid pointer `ptr` (it comes from a reference to `self`) and with
3588         // a size that is a power of two (since it comes from the alignment for U),
3589         // satisfying its safety constraints.
3590         let offset = unsafe { crate::ptr::align_offset(ptr, mem::align_of::<U>()) };
3591         if offset > self.len() {
3592             (self, &mut [], &mut [])
3593         } else {
3594             let (left, rest) = self.split_at_mut(offset);
3595             let (us_len, ts_len) = rest.align_to_offsets::<U>();
3596             let rest_len = rest.len();
3597             let mut_ptr = rest.as_mut_ptr();
3598             // We can't use `rest` again after this, that would invalidate its alias `mut_ptr`!
3599             // SAFETY: see comments for `align_to`.
3600             unsafe {
3601                 (
3602                     left,
3603                     from_raw_parts_mut(mut_ptr as *mut U, us_len),
3604                     from_raw_parts_mut(mut_ptr.add(rest_len - ts_len), ts_len),
3605                 )
3606             }
3607         }
3608     }
3609
3610     /// Split a slice into a prefix, a middle of aligned SIMD types, and a suffix.
3611     ///
3612     /// This is a safe wrapper around [`slice::align_to`], so has the same weak
3613     /// postconditions as that method.  You're only assured that
3614     /// `self.len() == prefix.len() + middle.len() * LANES + suffix.len()`.
3615     ///
3616     /// Notably, all of the following are possible:
3617     /// - `prefix.len() >= LANES`.
3618     /// - `middle.is_empty()` despite `self.len() >= 3 * LANES`.
3619     /// - `suffix.len() >= LANES`.
3620     ///
3621     /// That said, this is a safe method, so if you're only writing safe code,
3622     /// then this can at most cause incorrect logic, not unsoundness.
3623     ///
3624     /// # Panics
3625     ///
3626     /// This will panic if the size of the SIMD type is different from
3627     /// `LANES` times that of the scalar.
3628     ///
3629     /// At the time of writing, the trait restrictions on `Simd<T, LANES>` keeps
3630     /// that from ever happening, as only power-of-two numbers of lanes are
3631     /// supported.  It's possible that, in the future, those restrictions might
3632     /// be lifted in a way that would make it possible to see panics from this
3633     /// method for something like `LANES == 3`.
3634     ///
3635     /// # Examples
3636     ///
3637     /// ```
3638     /// #![feature(portable_simd)]
3639     /// use core::simd::SimdFloat;
3640     ///
3641     /// let short = &[1, 2, 3];
3642     /// let (prefix, middle, suffix) = short.as_simd::<4>();
3643     /// assert_eq!(middle, []); // Not enough elements for anything in the middle
3644     ///
3645     /// // They might be split in any possible way between prefix and suffix
3646     /// let it = prefix.iter().chain(suffix).copied();
3647     /// assert_eq!(it.collect::<Vec<_>>(), vec![1, 2, 3]);
3648     ///
3649     /// fn basic_simd_sum(x: &[f32]) -> f32 {
3650     ///     use std::ops::Add;
3651     ///     use std::simd::f32x4;
3652     ///     let (prefix, middle, suffix) = x.as_simd();
3653     ///     let sums = f32x4::from_array([
3654     ///         prefix.iter().copied().sum(),
3655     ///         0.0,
3656     ///         0.0,
3657     ///         suffix.iter().copied().sum(),
3658     ///     ]);
3659     ///     let sums = middle.iter().copied().fold(sums, f32x4::add);
3660     ///     sums.reduce_sum()
3661     /// }
3662     ///
3663     /// let numbers: Vec<f32> = (1..101).map(|x| x as _).collect();
3664     /// assert_eq!(basic_simd_sum(&numbers[1..99]), 4949.0);
3665     /// ```
3666     #[unstable(feature = "portable_simd", issue = "86656")]
3667     #[must_use]
3668     pub fn as_simd<const LANES: usize>(&self) -> (&[T], &[Simd<T, LANES>], &[T])
3669     where
3670         Simd<T, LANES>: AsRef<[T; LANES]>,
3671         T: simd::SimdElement,
3672         simd::LaneCount<LANES>: simd::SupportedLaneCount,
3673     {
3674         // These are expected to always match, as vector types are laid out like
3675         // arrays per <https://llvm.org/docs/LangRef.html#vector-type>, but we
3676         // might as well double-check since it'll optimize away anyhow.
3677         assert_eq!(mem::size_of::<Simd<T, LANES>>(), mem::size_of::<[T; LANES]>());
3678
3679         // SAFETY: The simd types have the same layout as arrays, just with
3680         // potentially-higher alignment, so the de-facto transmutes are sound.
3681         unsafe { self.align_to() }
3682     }
3683
3684     /// Split a mutable slice into a mutable prefix, a middle of aligned SIMD types,
3685     /// and a mutable suffix.
3686     ///
3687     /// This is a safe wrapper around [`slice::align_to_mut`], so has the same weak
3688     /// postconditions as that method.  You're only assured that
3689     /// `self.len() == prefix.len() + middle.len() * LANES + suffix.len()`.
3690     ///
3691     /// Notably, all of the following are possible:
3692     /// - `prefix.len() >= LANES`.
3693     /// - `middle.is_empty()` despite `self.len() >= 3 * LANES`.
3694     /// - `suffix.len() >= LANES`.
3695     ///
3696     /// That said, this is a safe method, so if you're only writing safe code,
3697     /// then this can at most cause incorrect logic, not unsoundness.
3698     ///
3699     /// This is the mutable version of [`slice::as_simd`]; see that for examples.
3700     ///
3701     /// # Panics
3702     ///
3703     /// This will panic if the size of the SIMD type is different from
3704     /// `LANES` times that of the scalar.
3705     ///
3706     /// At the time of writing, the trait restrictions on `Simd<T, LANES>` keeps
3707     /// that from ever happening, as only power-of-two numbers of lanes are
3708     /// supported.  It's possible that, in the future, those restrictions might
3709     /// be lifted in a way that would make it possible to see panics from this
3710     /// method for something like `LANES == 3`.
3711     #[unstable(feature = "portable_simd", issue = "86656")]
3712     #[must_use]
3713     pub fn as_simd_mut<const LANES: usize>(&mut self) -> (&mut [T], &mut [Simd<T, LANES>], &mut [T])
3714     where
3715         Simd<T, LANES>: AsMut<[T; LANES]>,
3716         T: simd::SimdElement,
3717         simd::LaneCount<LANES>: simd::SupportedLaneCount,
3718     {
3719         // These are expected to always match, as vector types are laid out like
3720         // arrays per <https://llvm.org/docs/LangRef.html#vector-type>, but we
3721         // might as well double-check since it'll optimize away anyhow.
3722         assert_eq!(mem::size_of::<Simd<T, LANES>>(), mem::size_of::<[T; LANES]>());
3723
3724         // SAFETY: The simd types have the same layout as arrays, just with
3725         // potentially-higher alignment, so the de-facto transmutes are sound.
3726         unsafe { self.align_to_mut() }
3727     }
3728
3729     /// Checks if the elements of this slice are sorted.
3730     ///
3731     /// That is, for each element `a` and its following element `b`, `a <= b` must hold. If the
3732     /// slice yields exactly zero or one element, `true` is returned.
3733     ///
3734     /// Note that if `Self::Item` is only `PartialOrd`, but not `Ord`, the above definition
3735     /// implies that this function returns `false` if any two consecutive items are not
3736     /// comparable.
3737     ///
3738     /// # Examples
3739     ///
3740     /// ```
3741     /// #![feature(is_sorted)]
3742     /// let empty: [i32; 0] = [];
3743     ///
3744     /// assert!([1, 2, 2, 9].is_sorted());
3745     /// assert!(![1, 3, 2, 4].is_sorted());
3746     /// assert!([0].is_sorted());
3747     /// assert!(empty.is_sorted());
3748     /// assert!(![0.0, 1.0, f32::NAN].is_sorted());
3749     /// ```
3750     #[inline]
3751     #[unstable(feature = "is_sorted", reason = "new API", issue = "53485")]
3752     #[must_use]
3753     pub fn is_sorted(&self) -> bool
3754     where
3755         T: PartialOrd,
3756     {
3757         self.is_sorted_by(|a, b| a.partial_cmp(b))
3758     }
3759
3760     /// Checks if the elements of this slice are sorted using the given comparator function.
3761     ///
3762     /// Instead of using `PartialOrd::partial_cmp`, this function uses the given `compare`
3763     /// function to determine the ordering of two elements. Apart from that, it's equivalent to
3764     /// [`is_sorted`]; see its documentation for more information.
3765     ///
3766     /// [`is_sorted`]: slice::is_sorted
3767     #[unstable(feature = "is_sorted", reason = "new API", issue = "53485")]
3768     #[must_use]
3769     pub fn is_sorted_by<'a, F>(&'a self, mut compare: F) -> bool
3770     where
3771         F: FnMut(&'a T, &'a T) -> Option<Ordering>,
3772     {
3773         self.iter().is_sorted_by(|a, b| compare(*a, *b))
3774     }
3775
3776     /// Checks if the elements of this slice are sorted using the given key extraction function.
3777     ///
3778     /// Instead of comparing the slice's elements directly, this function compares the keys of the
3779     /// elements, as determined by `f`. Apart from that, it's equivalent to [`is_sorted`]; see its
3780     /// documentation for more information.
3781     ///
3782     /// [`is_sorted`]: slice::is_sorted
3783     ///
3784     /// # Examples
3785     ///
3786     /// ```
3787     /// #![feature(is_sorted)]
3788     ///
3789     /// assert!(["c", "bb", "aaa"].is_sorted_by_key(|s| s.len()));
3790     /// assert!(![-2i32, -1, 0, 3].is_sorted_by_key(|n| n.abs()));
3791     /// ```
3792     #[inline]
3793     #[unstable(feature = "is_sorted", reason = "new API", issue = "53485")]
3794     #[must_use]
3795     pub fn is_sorted_by_key<'a, F, K>(&'a self, f: F) -> bool
3796     where
3797         F: FnMut(&'a T) -> K,
3798         K: PartialOrd,
3799     {
3800         self.iter().is_sorted_by_key(f)
3801     }
3802
3803     /// Returns the index of the partition point according to the given predicate
3804     /// (the index of the first element of the second partition).
3805     ///
3806     /// The slice is assumed to be partitioned according to the given predicate.
3807     /// This means that all elements for which the predicate returns true are at the start of the slice
3808     /// and all elements for which the predicate returns false are at the end.
3809     /// For example, `[7, 15, 3, 5, 4, 12, 6]` is partitioned under the predicate `x % 2 != 0`
3810     /// (all odd numbers are at the start, all even at the end).
3811     ///
3812     /// If this slice is not partitioned, the returned result is unspecified and meaningless,
3813     /// as this method performs a kind of binary search.
3814     ///
3815     /// See also [`binary_search`], [`binary_search_by`], and [`binary_search_by_key`].
3816     ///
3817     /// [`binary_search`]: slice::binary_search
3818     /// [`binary_search_by`]: slice::binary_search_by
3819     /// [`binary_search_by_key`]: slice::binary_search_by_key
3820     ///
3821     /// # Examples
3822     ///
3823     /// ```
3824     /// let v = [1, 2, 3, 3, 5, 6, 7];
3825     /// let i = v.partition_point(|&x| x < 5);
3826     ///
3827     /// assert_eq!(i, 4);
3828     /// assert!(v[..i].iter().all(|&x| x < 5));
3829     /// assert!(v[i..].iter().all(|&x| !(x < 5)));
3830     /// ```
3831     ///
3832     /// If all elements of the slice match the predicate, including if the slice
3833     /// is empty, then the length of the slice will be returned:
3834     ///
3835     /// ```
3836     /// let a = [2, 4, 8];
3837     /// assert_eq!(a.partition_point(|x| x < &100), a.len());
3838     /// let a: [i32; 0] = [];
3839     /// assert_eq!(a.partition_point(|x| x < &100), 0);
3840     /// ```
3841     ///
3842     /// If you want to insert an item to a sorted vector, while maintaining
3843     /// sort order:
3844     ///
3845     /// ```
3846     /// let mut s = vec![0, 1, 1, 1, 1, 2, 3, 5, 8, 13, 21, 34, 55];
3847     /// let num = 42;
3848     /// let idx = s.partition_point(|&x| x < num);
3849     /// s.insert(idx, num);
3850     /// assert_eq!(s, [0, 1, 1, 1, 1, 2, 3, 5, 8, 13, 21, 34, 42, 55]);
3851     /// ```
3852     #[stable(feature = "partition_point", since = "1.52.0")]
3853     #[must_use]
3854     pub fn partition_point<P>(&self, mut pred: P) -> usize
3855     where
3856         P: FnMut(&T) -> bool,
3857     {
3858         self.binary_search_by(|x| if pred(x) { Less } else { Greater }).unwrap_or_else(|i| i)
3859     }
3860
3861     /// Removes the subslice corresponding to the given range
3862     /// and returns a reference to it.
3863     ///
3864     /// Returns `None` and does not modify the slice if the given
3865     /// range is out of bounds.
3866     ///
3867     /// Note that this method only accepts one-sided ranges such as
3868     /// `2..` or `..6`, but not `2..6`.
3869     ///
3870     /// # Examples
3871     ///
3872     /// Taking the first three elements of a slice:
3873     ///
3874     /// ```
3875     /// #![feature(slice_take)]
3876     ///
3877     /// let mut slice: &[_] = &['a', 'b', 'c', 'd'];
3878     /// let mut first_three = slice.take(..3).unwrap();
3879     ///
3880     /// assert_eq!(slice, &['d']);
3881     /// assert_eq!(first_three, &['a', 'b', 'c']);
3882     /// ```
3883     ///
3884     /// Taking the last two elements of a slice:
3885     ///
3886     /// ```
3887     /// #![feature(slice_take)]
3888     ///
3889     /// let mut slice: &[_] = &['a', 'b', 'c', 'd'];
3890     /// let mut tail = slice.take(2..).unwrap();
3891     ///
3892     /// assert_eq!(slice, &['a', 'b']);
3893     /// assert_eq!(tail, &['c', 'd']);
3894     /// ```
3895     ///
3896     /// Getting `None` when `range` is out of bounds:
3897     ///
3898     /// ```
3899     /// #![feature(slice_take)]
3900     ///
3901     /// let mut slice: &[_] = &['a', 'b', 'c', 'd'];
3902     ///
3903     /// assert_eq!(None, slice.take(5..));
3904     /// assert_eq!(None, slice.take(..5));
3905     /// assert_eq!(None, slice.take(..=4));
3906     /// let expected: &[char] = &['a', 'b', 'c', 'd'];
3907     /// assert_eq!(Some(expected), slice.take(..4));
3908     /// ```
3909     #[inline]
3910     #[must_use = "method does not modify the slice if the range is out of bounds"]
3911     #[unstable(feature = "slice_take", issue = "62280")]
3912     pub fn take<'a, R: OneSidedRange<usize>>(self: &mut &'a Self, range: R) -> Option<&'a Self> {
3913         let (direction, split_index) = split_point_of(range)?;
3914         if split_index > self.len() {
3915             return None;
3916         }
3917         let (front, back) = self.split_at(split_index);
3918         match direction {
3919             Direction::Front => {
3920                 *self = back;
3921                 Some(front)
3922             }
3923             Direction::Back => {
3924                 *self = front;
3925                 Some(back)
3926             }
3927         }
3928     }
3929
3930     /// Removes the subslice corresponding to the given range
3931     /// and returns a mutable reference to it.
3932     ///
3933     /// Returns `None` and does not modify the slice if the given
3934     /// range is out of bounds.
3935     ///
3936     /// Note that this method only accepts one-sided ranges such as
3937     /// `2..` or `..6`, but not `2..6`.
3938     ///
3939     /// # Examples
3940     ///
3941     /// Taking the first three elements of a slice:
3942     ///
3943     /// ```
3944     /// #![feature(slice_take)]
3945     ///
3946     /// let mut slice: &mut [_] = &mut ['a', 'b', 'c', 'd'];
3947     /// let mut first_three = slice.take_mut(..3).unwrap();
3948     ///
3949     /// assert_eq!(slice, &mut ['d']);
3950     /// assert_eq!(first_three, &mut ['a', 'b', 'c']);
3951     /// ```
3952     ///
3953     /// Taking the last two elements of a slice:
3954     ///
3955     /// ```
3956     /// #![feature(slice_take)]
3957     ///
3958     /// let mut slice: &mut [_] = &mut ['a', 'b', 'c', 'd'];
3959     /// let mut tail = slice.take_mut(2..).unwrap();
3960     ///
3961     /// assert_eq!(slice, &mut ['a', 'b']);
3962     /// assert_eq!(tail, &mut ['c', 'd']);
3963     /// ```
3964     ///
3965     /// Getting `None` when `range` is out of bounds:
3966     ///
3967     /// ```
3968     /// #![feature(slice_take)]
3969     ///
3970     /// let mut slice: &mut [_] = &mut ['a', 'b', 'c', 'd'];
3971     ///
3972     /// assert_eq!(None, slice.take_mut(5..));
3973     /// assert_eq!(None, slice.take_mut(..5));
3974     /// assert_eq!(None, slice.take_mut(..=4));
3975     /// let expected: &mut [_] = &mut ['a', 'b', 'c', 'd'];
3976     /// assert_eq!(Some(expected), slice.take_mut(..4));
3977     /// ```
3978     #[inline]
3979     #[must_use = "method does not modify the slice if the range is out of bounds"]
3980     #[unstable(feature = "slice_take", issue = "62280")]
3981     pub fn take_mut<'a, R: OneSidedRange<usize>>(
3982         self: &mut &'a mut Self,
3983         range: R,
3984     ) -> Option<&'a mut Self> {
3985         let (direction, split_index) = split_point_of(range)?;
3986         if split_index > self.len() {
3987             return None;
3988         }
3989         let (front, back) = mem::take(self).split_at_mut(split_index);
3990         match direction {
3991             Direction::Front => {
3992                 *self = back;
3993                 Some(front)
3994             }
3995             Direction::Back => {
3996                 *self = front;
3997                 Some(back)
3998             }
3999         }
4000     }
4001
4002     /// Removes the first element of the slice and returns a reference
4003     /// to it.
4004     ///
4005     /// Returns `None` if the slice is empty.
4006     ///
4007     /// # Examples
4008     ///
4009     /// ```
4010     /// #![feature(slice_take)]
4011     ///
4012     /// let mut slice: &[_] = &['a', 'b', 'c'];
4013     /// let first = slice.take_first().unwrap();
4014     ///
4015     /// assert_eq!(slice, &['b', 'c']);
4016     /// assert_eq!(first, &'a');
4017     /// ```
4018     #[inline]
4019     #[unstable(feature = "slice_take", issue = "62280")]
4020     pub fn take_first<'a>(self: &mut &'a Self) -> Option<&'a T> {
4021         let (first, rem) = self.split_first()?;
4022         *self = rem;
4023         Some(first)
4024     }
4025
4026     /// Removes the first element of the slice and returns a mutable
4027     /// reference to it.
4028     ///
4029     /// Returns `None` if the slice is empty.
4030     ///
4031     /// # Examples
4032     ///
4033     /// ```
4034     /// #![feature(slice_take)]
4035     ///
4036     /// let mut slice: &mut [_] = &mut ['a', 'b', 'c'];
4037     /// let first = slice.take_first_mut().unwrap();
4038     /// *first = 'd';
4039     ///
4040     /// assert_eq!(slice, &['b', 'c']);
4041     /// assert_eq!(first, &'d');
4042     /// ```
4043     #[inline]
4044     #[unstable(feature = "slice_take", issue = "62280")]
4045     pub fn take_first_mut<'a>(self: &mut &'a mut Self) -> Option<&'a mut T> {
4046         let (first, rem) = mem::take(self).split_first_mut()?;
4047         *self = rem;
4048         Some(first)
4049     }
4050
4051     /// Removes the last element of the slice and returns a reference
4052     /// to it.
4053     ///
4054     /// Returns `None` if the slice is empty.
4055     ///
4056     /// # Examples
4057     ///
4058     /// ```
4059     /// #![feature(slice_take)]
4060     ///
4061     /// let mut slice: &[_] = &['a', 'b', 'c'];
4062     /// let last = slice.take_last().unwrap();
4063     ///
4064     /// assert_eq!(slice, &['a', 'b']);
4065     /// assert_eq!(last, &'c');
4066     /// ```
4067     #[inline]
4068     #[unstable(feature = "slice_take", issue = "62280")]
4069     pub fn take_last<'a>(self: &mut &'a Self) -> Option<&'a T> {
4070         let (last, rem) = self.split_last()?;
4071         *self = rem;
4072         Some(last)
4073     }
4074
4075     /// Removes the last element of the slice and returns a mutable
4076     /// reference to it.
4077     ///
4078     /// Returns `None` if the slice is empty.
4079     ///
4080     /// # Examples
4081     ///
4082     /// ```
4083     /// #![feature(slice_take)]
4084     ///
4085     /// let mut slice: &mut [_] = &mut ['a', 'b', 'c'];
4086     /// let last = slice.take_last_mut().unwrap();
4087     /// *last = 'd';
4088     ///
4089     /// assert_eq!(slice, &['a', 'b']);
4090     /// assert_eq!(last, &'d');
4091     /// ```
4092     #[inline]
4093     #[unstable(feature = "slice_take", issue = "62280")]
4094     pub fn take_last_mut<'a>(self: &mut &'a mut Self) -> Option<&'a mut T> {
4095         let (last, rem) = mem::take(self).split_last_mut()?;
4096         *self = rem;
4097         Some(last)
4098     }
4099
4100     /// Returns mutable references to many indices at once, without doing any checks.
4101     ///
4102     /// For a safe alternative see [`get_many_mut`].
4103     ///
4104     /// # Safety
4105     ///
4106     /// Calling this method with overlapping or out-of-bounds indices is *[undefined behavior]*
4107     /// even if the resulting references are not used.
4108     ///
4109     /// # Examples
4110     ///
4111     /// ```
4112     /// #![feature(get_many_mut)]
4113     ///
4114     /// let x = &mut [1, 2, 4];
4115     ///
4116     /// unsafe {
4117     ///     let [a, b] = x.get_many_unchecked_mut([0, 2]);
4118     ///     *a *= 10;
4119     ///     *b *= 100;
4120     /// }
4121     /// assert_eq!(x, &[10, 2, 400]);
4122     /// ```
4123     ///
4124     /// [`get_many_mut`]: slice::get_many_mut
4125     /// [undefined behavior]: https://doc.rust-lang.org/reference/behavior-considered-undefined.html
4126     #[unstable(feature = "get_many_mut", issue = "104642")]
4127     #[inline]
4128     pub unsafe fn get_many_unchecked_mut<const N: usize>(
4129         &mut self,
4130         indices: [usize; N],
4131     ) -> [&mut T; N] {
4132         // NB: This implementation is written as it is because any variation of
4133         // `indices.map(|i| self.get_unchecked_mut(i))` would make miri unhappy,
4134         // or generate worse code otherwise. This is also why we need to go
4135         // through a raw pointer here.
4136         let slice: *mut [T] = self;
4137         let mut arr: mem::MaybeUninit<[&mut T; N]> = mem::MaybeUninit::uninit();
4138         let arr_ptr = arr.as_mut_ptr();
4139
4140         // SAFETY: We expect `indices` to contain disjunct values that are
4141         // in bounds of `self`.
4142         unsafe {
4143             for i in 0..N {
4144                 let idx = *indices.get_unchecked(i);
4145                 *(*arr_ptr).get_unchecked_mut(i) = &mut *slice.get_unchecked_mut(idx);
4146             }
4147             arr.assume_init()
4148         }
4149     }
4150
4151     /// Returns mutable references to many indices at once.
4152     ///
4153     /// Returns an error if any index is out-of-bounds, or if the same index was
4154     /// passed more than once.
4155     ///
4156     /// # Examples
4157     ///
4158     /// ```
4159     /// #![feature(get_many_mut)]
4160     ///
4161     /// let v = &mut [1, 2, 3];
4162     /// if let Ok([a, b]) = v.get_many_mut([0, 2]) {
4163     ///     *a = 413;
4164     ///     *b = 612;
4165     /// }
4166     /// assert_eq!(v, &[413, 2, 612]);
4167     /// ```
4168     #[unstable(feature = "get_many_mut", issue = "104642")]
4169     #[inline]
4170     pub fn get_many_mut<const N: usize>(
4171         &mut self,
4172         indices: [usize; N],
4173     ) -> Result<[&mut T; N], GetManyMutError<N>> {
4174         if !get_many_check_valid(&indices, self.len()) {
4175             return Err(GetManyMutError { _private: () });
4176         }
4177         // SAFETY: The `get_many_check_valid()` call checked that all indices
4178         // are disjunct and in bounds.
4179         unsafe { Ok(self.get_many_unchecked_mut(indices)) }
4180     }
4181 }
4182
4183 impl<T, const N: usize> [[T; N]] {
4184     /// Takes a `&[[T; N]]`, and flattens it to a `&[T]`.
4185     ///
4186     /// # Panics
4187     ///
4188     /// This panics if the length of the resulting slice would overflow a `usize`.
4189     ///
4190     /// This is only possible when flattening a slice of arrays of zero-sized
4191     /// types, and thus tends to be irrelevant in practice. If
4192     /// `size_of::<T>() > 0`, this will never panic.
4193     ///
4194     /// # Examples
4195     ///
4196     /// ```
4197     /// #![feature(slice_flatten)]
4198     ///
4199     /// assert_eq!([[1, 2, 3], [4, 5, 6]].flatten(), &[1, 2, 3, 4, 5, 6]);
4200     ///
4201     /// assert_eq!(
4202     ///     [[1, 2, 3], [4, 5, 6]].flatten(),
4203     ///     [[1, 2], [3, 4], [5, 6]].flatten(),
4204     /// );
4205     ///
4206     /// let slice_of_empty_arrays: &[[i32; 0]] = &[[], [], [], [], []];
4207     /// assert!(slice_of_empty_arrays.flatten().is_empty());
4208     ///
4209     /// let empty_slice_of_arrays: &[[u32; 10]] = &[];
4210     /// assert!(empty_slice_of_arrays.flatten().is_empty());
4211     /// ```
4212     #[unstable(feature = "slice_flatten", issue = "95629")]
4213     pub fn flatten(&self) -> &[T] {
4214         let len = if T::IS_ZST {
4215             self.len().checked_mul(N).expect("slice len overflow")
4216         } else {
4217             // SAFETY: `self.len() * N` cannot overflow because `self` is
4218             // already in the address space.
4219             unsafe { self.len().unchecked_mul(N) }
4220         };
4221         // SAFETY: `[T]` is layout-identical to `[T; N]`
4222         unsafe { from_raw_parts(self.as_ptr().cast(), len) }
4223     }
4224
4225     /// Takes a `&mut [[T; N]]`, and flattens it to a `&mut [T]`.
4226     ///
4227     /// # Panics
4228     ///
4229     /// This panics if the length of the resulting slice would overflow a `usize`.
4230     ///
4231     /// This is only possible when flattening a slice of arrays of zero-sized
4232     /// types, and thus tends to be irrelevant in practice. If
4233     /// `size_of::<T>() > 0`, this will never panic.
4234     ///
4235     /// # Examples
4236     ///
4237     /// ```
4238     /// #![feature(slice_flatten)]
4239     ///
4240     /// fn add_5_to_all(slice: &mut [i32]) {
4241     ///     for i in slice {
4242     ///         *i += 5;
4243     ///     }
4244     /// }
4245     ///
4246     /// let mut array = [[1, 2, 3], [4, 5, 6], [7, 8, 9]];
4247     /// add_5_to_all(array.flatten_mut());
4248     /// assert_eq!(array, [[6, 7, 8], [9, 10, 11], [12, 13, 14]]);
4249     /// ```
4250     #[unstable(feature = "slice_flatten", issue = "95629")]
4251     pub fn flatten_mut(&mut self) -> &mut [T] {
4252         let len = if T::IS_ZST {
4253             self.len().checked_mul(N).expect("slice len overflow")
4254         } else {
4255             // SAFETY: `self.len() * N` cannot overflow because `self` is
4256             // already in the address space.
4257             unsafe { self.len().unchecked_mul(N) }
4258         };
4259         // SAFETY: `[T]` is layout-identical to `[T; N]`
4260         unsafe { from_raw_parts_mut(self.as_mut_ptr().cast(), len) }
4261     }
4262 }
4263
4264 #[cfg(not(test))]
4265 impl [f32] {
4266     /// Sorts the slice of floats.
4267     ///
4268     /// This sort is in-place (i.e. does not allocate), *O*(*n* \* log(*n*)) worst-case, and uses
4269     /// the ordering defined by [`f32::total_cmp`].
4270     ///
4271     /// # Current implementation
4272     ///
4273     /// This uses the same sorting algorithm as [`sort_unstable_by`](slice::sort_unstable_by).
4274     ///
4275     /// # Examples
4276     ///
4277     /// ```
4278     /// #![feature(sort_floats)]
4279     /// let mut v = [2.6, -5e-8, f32::NAN, 8.29, f32::INFINITY, -1.0, 0.0, -f32::INFINITY, -0.0];
4280     ///
4281     /// v.sort_floats();
4282     /// let sorted = [-f32::INFINITY, -1.0, -5e-8, -0.0, 0.0, 2.6, 8.29, f32::INFINITY, f32::NAN];
4283     /// assert_eq!(&v[..8], &sorted[..8]);
4284     /// assert!(v[8].is_nan());
4285     /// ```
4286     #[unstable(feature = "sort_floats", issue = "93396")]
4287     #[inline]
4288     pub fn sort_floats(&mut self) {
4289         self.sort_unstable_by(f32::total_cmp);
4290     }
4291 }
4292
4293 #[cfg(not(test))]
4294 impl [f64] {
4295     /// Sorts the slice of floats.
4296     ///
4297     /// This sort is in-place (i.e. does not allocate), *O*(*n* \* log(*n*)) worst-case, and uses
4298     /// the ordering defined by [`f64::total_cmp`].
4299     ///
4300     /// # Current implementation
4301     ///
4302     /// This uses the same sorting algorithm as [`sort_unstable_by`](slice::sort_unstable_by).
4303     ///
4304     /// # Examples
4305     ///
4306     /// ```
4307     /// #![feature(sort_floats)]
4308     /// let mut v = [2.6, -5e-8, f64::NAN, 8.29, f64::INFINITY, -1.0, 0.0, -f64::INFINITY, -0.0];
4309     ///
4310     /// v.sort_floats();
4311     /// let sorted = [-f64::INFINITY, -1.0, -5e-8, -0.0, 0.0, 2.6, 8.29, f64::INFINITY, f64::NAN];
4312     /// assert_eq!(&v[..8], &sorted[..8]);
4313     /// assert!(v[8].is_nan());
4314     /// ```
4315     #[unstable(feature = "sort_floats", issue = "93396")]
4316     #[inline]
4317     pub fn sort_floats(&mut self) {
4318         self.sort_unstable_by(f64::total_cmp);
4319     }
4320 }
4321
4322 trait CloneFromSpec<T> {
4323     fn spec_clone_from(&mut self, src: &[T]);
4324 }
4325
4326 impl<T> CloneFromSpec<T> for [T]
4327 where
4328     T: Clone,
4329 {
4330     #[track_caller]
4331     default fn spec_clone_from(&mut self, src: &[T]) {
4332         assert!(self.len() == src.len(), "destination and source slices have different lengths");
4333         // NOTE: We need to explicitly slice them to the same length
4334         // to make it easier for the optimizer to elide bounds checking.
4335         // But since it can't be relied on we also have an explicit specialization for T: Copy.
4336         let len = self.len();
4337         let src = &src[..len];
4338         for i in 0..len {
4339             self[i].clone_from(&src[i]);
4340         }
4341     }
4342 }
4343
4344 impl<T> CloneFromSpec<T> for [T]
4345 where
4346     T: Copy,
4347 {
4348     #[track_caller]
4349     fn spec_clone_from(&mut self, src: &[T]) {
4350         self.copy_from_slice(src);
4351     }
4352 }
4353
4354 #[stable(feature = "rust1", since = "1.0.0")]
4355 #[rustc_const_unstable(feature = "const_default_impls", issue = "87864")]
4356 impl<T> const Default for &[T] {
4357     /// Creates an empty slice.
4358     fn default() -> Self {
4359         &[]
4360     }
4361 }
4362
4363 #[stable(feature = "mut_slice_default", since = "1.5.0")]
4364 #[rustc_const_unstable(feature = "const_default_impls", issue = "87864")]
4365 impl<T> const Default for &mut [T] {
4366     /// Creates a mutable empty slice.
4367     fn default() -> Self {
4368         &mut []
4369     }
4370 }
4371
4372 #[unstable(feature = "slice_pattern", reason = "stopgap trait for slice patterns", issue = "56345")]
4373 /// Patterns in slices - currently, only used by `strip_prefix` and `strip_suffix`.  At a future
4374 /// point, we hope to generalise `core::str::Pattern` (which at the time of writing is limited to
4375 /// `str`) to slices, and then this trait will be replaced or abolished.
4376 pub trait SlicePattern {
4377     /// The element type of the slice being matched on.
4378     type Item;
4379
4380     /// Currently, the consumers of `SlicePattern` need a slice.
4381     fn as_slice(&self) -> &[Self::Item];
4382 }
4383
4384 #[stable(feature = "slice_strip", since = "1.51.0")]
4385 impl<T> SlicePattern for [T] {
4386     type Item = T;
4387
4388     #[inline]
4389     fn as_slice(&self) -> &[Self::Item] {
4390         self
4391     }
4392 }
4393
4394 #[stable(feature = "slice_strip", since = "1.51.0")]
4395 impl<T, const N: usize> SlicePattern for [T; N] {
4396     type Item = T;
4397
4398     #[inline]
4399     fn as_slice(&self) -> &[Self::Item] {
4400         self
4401     }
4402 }
4403
4404 /// This checks every index against each other, and against `len`.
4405 ///
4406 /// This will do `binomial(N + 1, 2) = N * (N + 1) / 2 = 0, 1, 3, 6, 10, ..`
4407 /// comparison operations.
4408 fn get_many_check_valid<const N: usize>(indices: &[usize; N], len: usize) -> bool {
4409     // NB: The optimzer should inline the loops into a sequence
4410     // of instructions without additional branching.
4411     let mut valid = true;
4412     for (i, &idx) in indices.iter().enumerate() {
4413         valid &= idx < len;
4414         for &idx2 in &indices[..i] {
4415             valid &= idx != idx2;
4416         }
4417     }
4418     valid
4419 }
4420
4421 /// The error type returned by [`get_many_mut<N>`][`slice::get_many_mut`].
4422 ///
4423 /// It indicates one of two possible errors:
4424 /// - An index is out-of-bounds.
4425 /// - The same index appeared multiple times in the array.
4426 ///
4427 /// # Examples
4428 ///
4429 /// ```
4430 /// #![feature(get_many_mut)]
4431 ///
4432 /// let v = &mut [1, 2, 3];
4433 /// assert!(v.get_many_mut([0, 999]).is_err());
4434 /// assert!(v.get_many_mut([1, 1]).is_err());
4435 /// ```
4436 #[unstable(feature = "get_many_mut", issue = "104642")]
4437 // NB: The N here is there to be forward-compatible with adding more details
4438 // to the error type at a later point
4439 pub struct GetManyMutError<const N: usize> {
4440     _private: (),
4441 }
4442
4443 #[unstable(feature = "get_many_mut", issue = "104642")]
4444 impl<const N: usize> fmt::Debug for GetManyMutError<N> {
4445     fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
4446         f.debug_struct("GetManyMutError").finish_non_exhaustive()
4447     }
4448 }
4449
4450 #[unstable(feature = "get_many_mut", issue = "104642")]
4451 impl<const N: usize> fmt::Display for GetManyMutError<N> {
4452     fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
4453         fmt::Display::fmt("an index is out of bounds or appeared multiple times in the array", f)
4454     }
4455 }