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