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