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