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