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