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