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