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