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