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