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