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