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