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