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