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