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