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