]> git.lizzy.rs Git - rust.git/blob - src/libcore/slice/mod.rs
update backtrace-rs
[rust.git] / src / libcore / slice / mod.rs
1 // ignore-tidy-filelength
2 // ignore-tidy-undocumented-unsafe
3
4 //! Slice management and manipulation.
5 //!
6 //! For more details see [`std::slice`].
7 //!
8 //! [`std::slice`]: ../../std/slice/index.html
9
10 #![stable(feature = "rust1", since = "1.0.0")]
11
12 // How this module is organized.
13 //
14 // The library infrastructure for slices is fairly messy. There's
15 // a lot of stuff defined here. Let's keep it clean.
16 //
17 // The layout of this file is thus:
18 //
19 // * Inherent methods. This is where most of the slice API resides.
20 // * Implementations of a few common traits with important slice ops.
21 // * Definitions of a bunch of iterators.
22 // * Free functions.
23 // * The `raw` and `bytes` submodules.
24 // * Boilerplate trait implementations.
25
26 use crate::cmp;
27 use crate::cmp::Ordering::{self, Equal, Greater, Less};
28 use crate::fmt;
29 use crate::intrinsics::{assume, exact_div, is_aligned_and_not_null, unchecked_sub};
30 use crate::iter::*;
31 use crate::marker::{self, Copy, Send, Sized, Sync};
32 use crate::mem;
33 use crate::ops::{self, FnMut, Range};
34 use crate::option::Option;
35 use crate::option::Option::{None, Some};
36 use crate::ptr::{self, NonNull};
37 use crate::result::Result;
38 use crate::result::Result::{Err, Ok};
39
40 #[unstable(
41     feature = "slice_internals",
42     issue = "none",
43     reason = "exposed from core to be reused in std; use the memchr crate"
44 )]
45 /// Pure rust memchr implementation, taken from rust-memchr
46 pub mod memchr;
47
48 mod rotate;
49 mod sort;
50
51 //
52 // Extension traits
53 //
54
55 #[lang = "slice"]
56 #[cfg(not(test))]
57 impl<T> [T] {
58     /// Returns the number of elements in the slice.
59     ///
60     /// # Examples
61     ///
62     /// ```
63     /// let a = [1, 2, 3];
64     /// assert_eq!(a.len(), 3);
65     /// ```
66     #[stable(feature = "rust1", since = "1.0.0")]
67     #[rustc_const_stable(feature = "const_slice_len", since = "1.32.0")]
68     #[inline]
69     // SAFETY: const sound because we transmute out the length field as a usize (which it must be)
70     #[allow(unused_attributes)]
71     #[allow_internal_unstable(const_fn_union)]
72     pub const fn len(&self) -> usize {
73         unsafe { crate::ptr::Repr { rust: self }.raw.len }
74     }
75
76     /// Returns `true` if the slice has a length of 0.
77     ///
78     /// # Examples
79     ///
80     /// ```
81     /// let a = [1, 2, 3];
82     /// assert!(!a.is_empty());
83     /// ```
84     #[stable(feature = "rust1", since = "1.0.0")]
85     #[rustc_const_stable(feature = "const_slice_is_empty", since = "1.32.0")]
86     #[inline]
87     pub const fn is_empty(&self) -> bool {
88         self.len() == 0
89     }
90
91     /// Returns the first element of the slice, or `None` if it is empty.
92     ///
93     /// # Examples
94     ///
95     /// ```
96     /// let v = [10, 40, 30];
97     /// assert_eq!(Some(&10), v.first());
98     ///
99     /// let w: &[i32] = &[];
100     /// assert_eq!(None, w.first());
101     /// ```
102     #[stable(feature = "rust1", since = "1.0.0")]
103     #[inline]
104     pub fn first(&self) -> Option<&T> {
105         if let [first, ..] = self { Some(first) } else { None }
106     }
107
108     /// Returns a mutable pointer to the first element of the slice, or `None` if it is empty.
109     ///
110     /// # Examples
111     ///
112     /// ```
113     /// let x = &mut [0, 1, 2];
114     ///
115     /// if let Some(first) = x.first_mut() {
116     ///     *first = 5;
117     /// }
118     /// assert_eq!(x, &[5, 1, 2]);
119     /// ```
120     #[stable(feature = "rust1", since = "1.0.0")]
121     #[inline]
122     pub fn first_mut(&mut self) -> Option<&mut T> {
123         if let [first, ..] = self { Some(first) } else { None }
124     }
125
126     /// Returns the first and all the rest of the elements of the slice, or `None` if it is empty.
127     ///
128     /// # Examples
129     ///
130     /// ```
131     /// let x = &[0, 1, 2];
132     ///
133     /// if let Some((first, elements)) = x.split_first() {
134     ///     assert_eq!(first, &0);
135     ///     assert_eq!(elements, &[1, 2]);
136     /// }
137     /// ```
138     #[stable(feature = "slice_splits", since = "1.5.0")]
139     #[inline]
140     pub fn split_first(&self) -> Option<(&T, &[T])> {
141         if let [first, tail @ ..] = self { Some((first, tail)) } else { None }
142     }
143
144     /// Returns the first and all the rest of the elements of the slice, or `None` if it is empty.
145     ///
146     /// # Examples
147     ///
148     /// ```
149     /// let x = &mut [0, 1, 2];
150     ///
151     /// if let Some((first, elements)) = x.split_first_mut() {
152     ///     *first = 3;
153     ///     elements[0] = 4;
154     ///     elements[1] = 5;
155     /// }
156     /// assert_eq!(x, &[3, 4, 5]);
157     /// ```
158     #[stable(feature = "slice_splits", since = "1.5.0")]
159     #[inline]
160     pub fn split_first_mut(&mut self) -> Option<(&mut T, &mut [T])> {
161         if let [first, tail @ ..] = self { Some((first, tail)) } else { None }
162     }
163
164     /// Returns the last and all the rest of the elements of the slice, or `None` if it is empty.
165     ///
166     /// # Examples
167     ///
168     /// ```
169     /// let x = &[0, 1, 2];
170     ///
171     /// if let Some((last, elements)) = x.split_last() {
172     ///     assert_eq!(last, &2);
173     ///     assert_eq!(elements, &[0, 1]);
174     /// }
175     /// ```
176     #[stable(feature = "slice_splits", since = "1.5.0")]
177     #[inline]
178     pub fn split_last(&self) -> Option<(&T, &[T])> {
179         if let [init @ .., last] = self { Some((last, init)) } else { None }
180     }
181
182     /// Returns the last and all the rest of the elements of the slice, or `None` if it is empty.
183     ///
184     /// # Examples
185     ///
186     /// ```
187     /// let x = &mut [0, 1, 2];
188     ///
189     /// if let Some((last, elements)) = x.split_last_mut() {
190     ///     *last = 3;
191     ///     elements[0] = 4;
192     ///     elements[1] = 5;
193     /// }
194     /// assert_eq!(x, &[4, 5, 3]);
195     /// ```
196     #[stable(feature = "slice_splits", since = "1.5.0")]
197     #[inline]
198     pub fn split_last_mut(&mut self) -> Option<(&mut T, &mut [T])> {
199         if let [init @ .., last] = self { Some((last, init)) } else { None }
200     }
201
202     /// Returns the last element of the slice, or `None` if it is empty.
203     ///
204     /// # Examples
205     ///
206     /// ```
207     /// let v = [10, 40, 30];
208     /// assert_eq!(Some(&30), v.last());
209     ///
210     /// let w: &[i32] = &[];
211     /// assert_eq!(None, w.last());
212     /// ```
213     #[stable(feature = "rust1", since = "1.0.0")]
214     #[inline]
215     pub fn last(&self) -> Option<&T> {
216         if let [.., last] = self { Some(last) } else { None }
217     }
218
219     /// Returns a mutable pointer to the last item in the slice.
220     ///
221     /// # Examples
222     ///
223     /// ```
224     /// let x = &mut [0, 1, 2];
225     ///
226     /// if let Some(last) = x.last_mut() {
227     ///     *last = 10;
228     /// }
229     /// assert_eq!(x, &[0, 1, 10]);
230     /// ```
231     #[stable(feature = "rust1", since = "1.0.0")]
232     #[inline]
233     pub fn last_mut(&mut self) -> Option<&mut T> {
234         if let [.., last] = self { Some(last) } else { None }
235     }
236
237     /// Returns a reference to an element or subslice depending on the type of
238     /// index.
239     ///
240     /// - If given a position, returns a reference to the element at that
241     ///   position or `None` if out of bounds.
242     /// - If given a range, returns the subslice corresponding to that range,
243     ///   or `None` if out of bounds.
244     ///
245     /// # Examples
246     ///
247     /// ```
248     /// let v = [10, 40, 30];
249     /// assert_eq!(Some(&40), v.get(1));
250     /// assert_eq!(Some(&[10, 40][..]), v.get(0..2));
251     /// assert_eq!(None, v.get(3));
252     /// assert_eq!(None, v.get(0..4));
253     /// ```
254     #[stable(feature = "rust1", since = "1.0.0")]
255     #[inline]
256     pub fn get<I>(&self, index: I) -> Option<&I::Output>
257     where
258         I: SliceIndex<Self>,
259     {
260         index.get(self)
261     }
262
263     /// Returns a mutable reference to an element or subslice depending on the
264     /// type of index (see [`get`]) or `None` if the index is out of bounds.
265     ///
266     /// [`get`]: #method.get
267     ///
268     /// # Examples
269     ///
270     /// ```
271     /// let x = &mut [0, 1, 2];
272     ///
273     /// if let Some(elem) = x.get_mut(1) {
274     ///     *elem = 42;
275     /// }
276     /// assert_eq!(x, &[0, 42, 2]);
277     /// ```
278     #[stable(feature = "rust1", since = "1.0.0")]
279     #[inline]
280     pub fn get_mut<I>(&mut self, index: I) -> Option<&mut I::Output>
281     where
282         I: SliceIndex<Self>,
283     {
284         index.get_mut(self)
285     }
286
287     /// Returns a reference to an element or subslice, without doing bounds
288     /// checking.
289     ///
290     /// This is generally not recommended, use with caution!
291     /// Calling this method with an out-of-bounds index is *[undefined behavior]*
292     /// even if the resulting reference is not used.
293     /// For a safe alternative see [`get`].
294     ///
295     /// [`get`]: #method.get
296     /// [undefined behavior]: https://doc.rust-lang.org/reference/behavior-considered-undefined.html
297     ///
298     /// # Examples
299     ///
300     /// ```
301     /// let x = &[1, 2, 4];
302     ///
303     /// unsafe {
304     ///     assert_eq!(x.get_unchecked(1), &2);
305     /// }
306     /// ```
307     #[stable(feature = "rust1", since = "1.0.0")]
308     #[inline]
309     pub unsafe fn get_unchecked<I>(&self, index: I) -> &I::Output
310     where
311         I: SliceIndex<Self>,
312     {
313         // SAFETY: the caller must uphold most of the safety requirements for `get_unchecked`;
314         // the slice is dereferencable because `self` is a safe reference.
315         // The returned pointer is safe because impls of `SliceIndex` have to guarantee that it is.
316         unsafe { &*index.get_unchecked(self) }
317     }
318
319     /// Returns a mutable reference to an element or subslice, without doing
320     /// bounds checking.
321     ///
322     /// This is generally not recommended, use with caution!
323     /// Calling this method with an out-of-bounds index is *[undefined behavior]*
324     /// even if the resulting reference is not used.
325     /// For a safe alternative see [`get_mut`].
326     ///
327     /// [`get_mut`]: #method.get_mut
328     /// [undefined behavior]: https://doc.rust-lang.org/reference/behavior-considered-undefined.html
329     ///
330     /// # Examples
331     ///
332     /// ```
333     /// let x = &mut [1, 2, 4];
334     ///
335     /// unsafe {
336     ///     let elem = x.get_unchecked_mut(1);
337     ///     *elem = 13;
338     /// }
339     /// assert_eq!(x, &[1, 13, 4]);
340     /// ```
341     #[stable(feature = "rust1", since = "1.0.0")]
342     #[inline]
343     pub unsafe fn get_unchecked_mut<I>(&mut self, index: I) -> &mut I::Output
344     where
345         I: SliceIndex<Self>,
346     {
347         // SAFETY: the caller must uphold the safety requirements for `get_unchecked_mut`;
348         // the slice is dereferencable because `self` is a safe reference.
349         // The returned pointer is safe because impls of `SliceIndex` have to guarantee that it is.
350         unsafe { &mut *index.get_unchecked_mut(self) }
351     }
352
353     /// Returns a raw pointer to the slice's buffer.
354     ///
355     /// The caller must ensure that the slice outlives the pointer this
356     /// function returns, or else it will end up pointing to garbage.
357     ///
358     /// The caller must also ensure that the memory the pointer (non-transitively) points to
359     /// is never written to (except inside an `UnsafeCell`) using this pointer or any pointer
360     /// derived from it. If you need to mutate the contents of the slice, use [`as_mut_ptr`].
361     ///
362     /// Modifying the container referenced by this slice may cause its buffer
363     /// to be reallocated, which would also make any pointers to it invalid.
364     ///
365     /// # Examples
366     ///
367     /// ```
368     /// let x = &[1, 2, 4];
369     /// let x_ptr = x.as_ptr();
370     ///
371     /// unsafe {
372     ///     for i in 0..x.len() {
373     ///         assert_eq!(x.get_unchecked(i), &*x_ptr.add(i));
374     ///     }
375     /// }
376     /// ```
377     ///
378     /// [`as_mut_ptr`]: #method.as_mut_ptr
379     #[stable(feature = "rust1", since = "1.0.0")]
380     #[rustc_const_stable(feature = "const_slice_as_ptr", since = "1.32.0")]
381     #[inline]
382     pub const fn as_ptr(&self) -> *const T {
383         self as *const [T] as *const T
384     }
385
386     /// Returns an unsafe mutable pointer to the slice's buffer.
387     ///
388     /// The caller must ensure that the slice outlives the pointer this
389     /// function returns, or else it will end up pointing to garbage.
390     ///
391     /// Modifying the container referenced by this slice may cause its buffer
392     /// to be reallocated, which would also make any pointers to it invalid.
393     ///
394     /// # Examples
395     ///
396     /// ```
397     /// let x = &mut [1, 2, 4];
398     /// let x_ptr = x.as_mut_ptr();
399     ///
400     /// unsafe {
401     ///     for i in 0..x.len() {
402     ///         *x_ptr.add(i) += 2;
403     ///     }
404     /// }
405     /// assert_eq!(x, &[3, 4, 6]);
406     /// ```
407     #[stable(feature = "rust1", since = "1.0.0")]
408     #[inline]
409     pub fn as_mut_ptr(&mut self) -> *mut T {
410         self as *mut [T] as *mut T
411     }
412
413     /// Returns the two raw pointers spanning the slice.
414     ///
415     /// The returned range is half-open, which means that the end pointer
416     /// points *one past* the last element of the slice. This way, an empty
417     /// slice is represented by two equal pointers, and the difference between
418     /// the two pointers represents the size of the slice.
419     ///
420     /// See [`as_ptr`] for warnings on using these pointers. The end pointer
421     /// requires extra caution, as it does not point to a valid element in the
422     /// slice.
423     ///
424     /// This function is useful for interacting with foreign interfaces which
425     /// use two pointers to refer to a range of elements in memory, as is
426     /// common in C++.
427     ///
428     /// It can also be useful to check if a pointer to an element refers to an
429     /// element of this slice:
430     ///
431     /// ```
432     /// #![feature(slice_ptr_range)]
433     ///
434     /// let a = [1, 2, 3];
435     /// let x = &a[1] as *const _;
436     /// let y = &5 as *const _;
437     ///
438     /// assert!(a.as_ptr_range().contains(&x));
439     /// assert!(!a.as_ptr_range().contains(&y));
440     /// ```
441     ///
442     /// [`as_ptr`]: #method.as_ptr
443     #[unstable(feature = "slice_ptr_range", issue = "65807")]
444     #[inline]
445     pub fn as_ptr_range(&self) -> Range<*const T> {
446         // The `add` here is safe, because:
447         //
448         //   - Both pointers are part of the same object, as pointing directly
449         //     past the object also counts.
450         //
451         //   - The size of the slice is never larger than isize::MAX bytes, as
452         //     noted here:
453         //       - https://github.com/rust-lang/unsafe-code-guidelines/issues/102#issuecomment-473340447
454         //       - https://doc.rust-lang.org/reference/behavior-considered-undefined.html
455         //       - https://doc.rust-lang.org/core/slice/fn.from_raw_parts.html#safety
456         //     (This doesn't seem normative yet, but the very same assumption is
457         //     made in many places, including the Index implementation of slices.)
458         //
459         //   - There is no wrapping around involved, as slices do not wrap past
460         //     the end of the address space.
461         //
462         // See the documentation of pointer::add.
463         let start = self.as_ptr();
464         let end = unsafe { start.add(self.len()) };
465         start..end
466     }
467
468     /// Returns the two unsafe mutable pointers spanning the slice.
469     ///
470     /// The returned range is half-open, which means that the end pointer
471     /// points *one past* the last element of the slice. This way, an empty
472     /// slice is represented by two equal pointers, and the difference between
473     /// the two pointers represents the size of the slice.
474     ///
475     /// See [`as_mut_ptr`] for warnings on using these pointers. The end
476     /// pointer requires extra caution, as it does not point to a valid element
477     /// in the slice.
478     ///
479     /// This function is useful for interacting with foreign interfaces which
480     /// use two pointers to refer to a range of elements in memory, as is
481     /// common in C++.
482     ///
483     /// [`as_mut_ptr`]: #method.as_mut_ptr
484     #[unstable(feature = "slice_ptr_range", issue = "65807")]
485     #[inline]
486     pub fn as_mut_ptr_range(&mut self) -> Range<*mut T> {
487         // See as_ptr_range() above for why `add` here is safe.
488         let start = self.as_mut_ptr();
489         let end = unsafe { start.add(self.len()) };
490         start..end
491     }
492
493     /// Swaps two elements in the slice.
494     ///
495     /// # Arguments
496     ///
497     /// * a - The index of the first element
498     /// * b - The index of the second element
499     ///
500     /// # Panics
501     ///
502     /// Panics if `a` or `b` are out of bounds.
503     ///
504     /// # Examples
505     ///
506     /// ```
507     /// let mut v = ["a", "b", "c", "d"];
508     /// v.swap(1, 3);
509     /// assert!(v == ["a", "d", "c", "b"]);
510     /// ```
511     #[stable(feature = "rust1", since = "1.0.0")]
512     #[inline]
513     pub fn swap(&mut self, a: usize, b: usize) {
514         unsafe {
515             // Can't take two mutable loans from one vector, so instead just cast
516             // them to their raw pointers to do the swap
517             let pa: *mut T = &mut self[a];
518             let pb: *mut T = &mut self[b];
519             ptr::swap(pa, pb);
520         }
521     }
522
523     /// Reverses the order of elements in the slice, in place.
524     ///
525     /// # Examples
526     ///
527     /// ```
528     /// let mut v = [1, 2, 3];
529     /// v.reverse();
530     /// assert!(v == [3, 2, 1]);
531     /// ```
532     #[stable(feature = "rust1", since = "1.0.0")]
533     #[inline]
534     pub fn reverse(&mut self) {
535         let mut i: usize = 0;
536         let ln = self.len();
537
538         // For very small types, all the individual reads in the normal
539         // path perform poorly.  We can do better, given efficient unaligned
540         // load/store, by loading a larger chunk and reversing a register.
541
542         // Ideally LLVM would do this for us, as it knows better than we do
543         // whether unaligned reads are efficient (since that changes between
544         // different ARM versions, for example) and what the best chunk size
545         // would be.  Unfortunately, as of LLVM 4.0 (2017-05) it only unrolls
546         // the loop, so we need to do this ourselves.  (Hypothesis: reverse
547         // is troublesome because the sides can be aligned differently --
548         // will be, when the length is odd -- so there's no way of emitting
549         // pre- and postludes to use fully-aligned SIMD in the middle.)
550
551         let fast_unaligned = cfg!(any(target_arch = "x86", target_arch = "x86_64"));
552
553         if fast_unaligned && mem::size_of::<T>() == 1 {
554             // Use the llvm.bswap intrinsic to reverse u8s in a usize
555             let chunk = mem::size_of::<usize>();
556             while i + chunk - 1 < ln / 2 {
557                 unsafe {
558                     let pa: *mut T = self.get_unchecked_mut(i);
559                     let pb: *mut T = self.get_unchecked_mut(ln - i - chunk);
560                     let va = ptr::read_unaligned(pa as *mut usize);
561                     let vb = ptr::read_unaligned(pb as *mut usize);
562                     ptr::write_unaligned(pa as *mut usize, vb.swap_bytes());
563                     ptr::write_unaligned(pb as *mut usize, va.swap_bytes());
564                 }
565                 i += chunk;
566             }
567         }
568
569         if fast_unaligned && mem::size_of::<T>() == 2 {
570             // Use rotate-by-16 to reverse u16s in a u32
571             let chunk = mem::size_of::<u32>() / 2;
572             while i + chunk - 1 < ln / 2 {
573                 unsafe {
574                     let pa: *mut T = self.get_unchecked_mut(i);
575                     let pb: *mut T = self.get_unchecked_mut(ln - i - chunk);
576                     let va = ptr::read_unaligned(pa as *mut u32);
577                     let vb = ptr::read_unaligned(pb as *mut u32);
578                     ptr::write_unaligned(pa as *mut u32, vb.rotate_left(16));
579                     ptr::write_unaligned(pb as *mut u32, va.rotate_left(16));
580                 }
581                 i += chunk;
582             }
583         }
584
585         while i < ln / 2 {
586             // Unsafe swap to avoid the bounds check in safe swap.
587             unsafe {
588                 let pa: *mut T = self.get_unchecked_mut(i);
589                 let pb: *mut T = self.get_unchecked_mut(ln - i - 1);
590                 ptr::swap(pa, pb);
591             }
592             i += 1;
593         }
594     }
595
596     /// Returns an iterator over the slice.
597     ///
598     /// # Examples
599     ///
600     /// ```
601     /// let x = &[1, 2, 4];
602     /// let mut iterator = x.iter();
603     ///
604     /// assert_eq!(iterator.next(), Some(&1));
605     /// assert_eq!(iterator.next(), Some(&2));
606     /// assert_eq!(iterator.next(), Some(&4));
607     /// assert_eq!(iterator.next(), None);
608     /// ```
609     #[stable(feature = "rust1", since = "1.0.0")]
610     #[inline]
611     pub fn iter(&self) -> Iter<'_, T> {
612         unsafe {
613             let ptr = self.as_ptr();
614             assume(!ptr.is_null());
615
616             let end = if mem::size_of::<T>() == 0 {
617                 (ptr as *const u8).wrapping_add(self.len()) as *const T
618             } else {
619                 ptr.add(self.len())
620             };
621
622             Iter { ptr: NonNull::new_unchecked(ptr as *mut T), end, _marker: marker::PhantomData }
623         }
624     }
625
626     /// Returns an iterator that allows modifying each value.
627     ///
628     /// # Examples
629     ///
630     /// ```
631     /// let x = &mut [1, 2, 4];
632     /// for elem in x.iter_mut() {
633     ///     *elem += 2;
634     /// }
635     /// assert_eq!(x, &[3, 4, 6]);
636     /// ```
637     #[stable(feature = "rust1", since = "1.0.0")]
638     #[inline]
639     pub fn iter_mut(&mut self) -> IterMut<'_, T> {
640         unsafe {
641             let ptr = self.as_mut_ptr();
642             assume(!ptr.is_null());
643
644             let end = if mem::size_of::<T>() == 0 {
645                 (ptr as *mut u8).wrapping_add(self.len()) as *mut T
646             } else {
647                 ptr.add(self.len())
648             };
649
650             IterMut { ptr: NonNull::new_unchecked(ptr), end, _marker: marker::PhantomData }
651         }
652     }
653
654     /// Returns an iterator over all contiguous windows of length
655     /// `size`. The windows overlap. If the slice is shorter than
656     /// `size`, the iterator returns no values.
657     ///
658     /// # Panics
659     ///
660     /// Panics if `size` is 0.
661     ///
662     /// # Examples
663     ///
664     /// ```
665     /// let slice = ['r', 'u', 's', 't'];
666     /// let mut iter = slice.windows(2);
667     /// assert_eq!(iter.next().unwrap(), &['r', 'u']);
668     /// assert_eq!(iter.next().unwrap(), &['u', 's']);
669     /// assert_eq!(iter.next().unwrap(), &['s', 't']);
670     /// assert!(iter.next().is_none());
671     /// ```
672     ///
673     /// If the slice is shorter than `size`:
674     ///
675     /// ```
676     /// let slice = ['f', 'o', 'o'];
677     /// let mut iter = slice.windows(4);
678     /// assert!(iter.next().is_none());
679     /// ```
680     #[stable(feature = "rust1", since = "1.0.0")]
681     #[inline]
682     pub fn windows(&self, size: usize) -> Windows<'_, T> {
683         assert!(size != 0);
684         Windows { v: self, size }
685     }
686
687     /// Returns an iterator over `chunk_size` elements of the slice at a time, starting at the
688     /// beginning of the slice.
689     ///
690     /// The chunks are slices and do not overlap. If `chunk_size` does not divide the length of the
691     /// slice, then the last chunk will not have length `chunk_size`.
692     ///
693     /// See [`chunks_exact`] for a variant of this iterator that returns chunks of always exactly
694     /// `chunk_size` elements, and [`rchunks`] for the same iterator but starting at the end of the
695     /// slice.
696     ///
697     /// # Panics
698     ///
699     /// Panics if `chunk_size` is 0.
700     ///
701     /// # Examples
702     ///
703     /// ```
704     /// let slice = ['l', 'o', 'r', 'e', 'm'];
705     /// let mut iter = slice.chunks(2);
706     /// assert_eq!(iter.next().unwrap(), &['l', 'o']);
707     /// assert_eq!(iter.next().unwrap(), &['r', 'e']);
708     /// assert_eq!(iter.next().unwrap(), &['m']);
709     /// assert!(iter.next().is_none());
710     /// ```
711     ///
712     /// [`chunks_exact`]: #method.chunks_exact
713     /// [`rchunks`]: #method.rchunks
714     #[stable(feature = "rust1", since = "1.0.0")]
715     #[inline]
716     pub fn chunks(&self, chunk_size: usize) -> Chunks<'_, T> {
717         assert!(chunk_size != 0);
718         Chunks { v: self, chunk_size }
719     }
720
721     /// Returns an iterator over `chunk_size` elements of the slice at a time, starting at the
722     /// beginning of the slice.
723     ///
724     /// The chunks are mutable slices, and do not overlap. If `chunk_size` does not divide the
725     /// length of the slice, then the last chunk will not have length `chunk_size`.
726     ///
727     /// See [`chunks_exact_mut`] for a variant of this iterator that returns chunks of always
728     /// exactly `chunk_size` elements, and [`rchunks_mut`] for the same iterator but starting at
729     /// the end of the slice.
730     ///
731     /// # Panics
732     ///
733     /// Panics if `chunk_size` is 0.
734     ///
735     /// # Examples
736     ///
737     /// ```
738     /// let v = &mut [0, 0, 0, 0, 0];
739     /// let mut count = 1;
740     ///
741     /// for chunk in v.chunks_mut(2) {
742     ///     for elem in chunk.iter_mut() {
743     ///         *elem += count;
744     ///     }
745     ///     count += 1;
746     /// }
747     /// assert_eq!(v, &[1, 1, 2, 2, 3]);
748     /// ```
749     ///
750     /// [`chunks_exact_mut`]: #method.chunks_exact_mut
751     /// [`rchunks_mut`]: #method.rchunks_mut
752     #[stable(feature = "rust1", since = "1.0.0")]
753     #[inline]
754     pub fn chunks_mut(&mut self, chunk_size: usize) -> ChunksMut<'_, T> {
755         assert!(chunk_size != 0);
756         ChunksMut { v: self, chunk_size }
757     }
758
759     /// Returns an iterator over `chunk_size` elements of the slice at a time, starting at the
760     /// beginning of the slice.
761     ///
762     /// The chunks are slices and do not overlap. If `chunk_size` does not divide the length of the
763     /// slice, then the last up to `chunk_size-1` elements will be omitted and can be retrieved
764     /// from the `remainder` function of the iterator.
765     ///
766     /// Due to each chunk having exactly `chunk_size` elements, the compiler can often optimize the
767     /// resulting code better than in the case of [`chunks`].
768     ///
769     /// See [`chunks`] for a variant of this iterator that also returns the remainder as a smaller
770     /// chunk, and [`rchunks_exact`] for the same iterator but starting at the end of the slice.
771     ///
772     /// # Panics
773     ///
774     /// Panics if `chunk_size` is 0.
775     ///
776     /// # Examples
777     ///
778     /// ```
779     /// let slice = ['l', 'o', 'r', 'e', 'm'];
780     /// let mut iter = slice.chunks_exact(2);
781     /// assert_eq!(iter.next().unwrap(), &['l', 'o']);
782     /// assert_eq!(iter.next().unwrap(), &['r', 'e']);
783     /// assert!(iter.next().is_none());
784     /// assert_eq!(iter.remainder(), &['m']);
785     /// ```
786     ///
787     /// [`chunks`]: #method.chunks
788     /// [`rchunks_exact`]: #method.rchunks_exact
789     #[stable(feature = "chunks_exact", since = "1.31.0")]
790     #[inline]
791     pub fn chunks_exact(&self, chunk_size: usize) -> ChunksExact<'_, T> {
792         assert!(chunk_size != 0);
793         let rem = self.len() % chunk_size;
794         let len = self.len() - rem;
795         let (fst, snd) = self.split_at(len);
796         ChunksExact { v: fst, rem: snd, chunk_size }
797     }
798
799     /// Returns an iterator over `chunk_size` elements of the slice at a time, starting at the
800     /// beginning of the slice.
801     ///
802     /// The chunks are mutable slices, and do not overlap. If `chunk_size` does not divide the
803     /// length of the slice, then the last up to `chunk_size-1` elements will be omitted and can be
804     /// retrieved from the `into_remainder` function of the iterator.
805     ///
806     /// Due to each chunk having exactly `chunk_size` elements, the compiler can often optimize the
807     /// resulting code better than in the case of [`chunks_mut`].
808     ///
809     /// See [`chunks_mut`] for a variant of this iterator that also returns the remainder as a
810     /// smaller chunk, and [`rchunks_exact_mut`] for the same iterator but starting at the end of
811     /// the slice.
812     ///
813     /// # Panics
814     ///
815     /// Panics if `chunk_size` is 0.
816     ///
817     /// # Examples
818     ///
819     /// ```
820     /// let v = &mut [0, 0, 0, 0, 0];
821     /// let mut count = 1;
822     ///
823     /// for chunk in v.chunks_exact_mut(2) {
824     ///     for elem in chunk.iter_mut() {
825     ///         *elem += count;
826     ///     }
827     ///     count += 1;
828     /// }
829     /// assert_eq!(v, &[1, 1, 2, 2, 0]);
830     /// ```
831     ///
832     /// [`chunks_mut`]: #method.chunks_mut
833     /// [`rchunks_exact_mut`]: #method.rchunks_exact_mut
834     #[stable(feature = "chunks_exact", since = "1.31.0")]
835     #[inline]
836     pub fn chunks_exact_mut(&mut self, chunk_size: usize) -> ChunksExactMut<'_, T> {
837         assert!(chunk_size != 0);
838         let rem = self.len() % chunk_size;
839         let len = self.len() - rem;
840         let (fst, snd) = self.split_at_mut(len);
841         ChunksExactMut { v: fst, rem: snd, chunk_size }
842     }
843
844     /// Returns an iterator over `chunk_size` elements of the slice at a time, starting at the end
845     /// of the slice.
846     ///
847     /// The chunks are slices and do not overlap. If `chunk_size` does not divide the length of the
848     /// slice, then the last chunk will not have length `chunk_size`.
849     ///
850     /// See [`rchunks_exact`] for a variant of this iterator that returns chunks of always exactly
851     /// `chunk_size` elements, and [`chunks`] for the same iterator but starting at the beginning
852     /// of the slice.
853     ///
854     /// # Panics
855     ///
856     /// Panics if `chunk_size` is 0.
857     ///
858     /// # Examples
859     ///
860     /// ```
861     /// let slice = ['l', 'o', 'r', 'e', 'm'];
862     /// let mut iter = slice.rchunks(2);
863     /// assert_eq!(iter.next().unwrap(), &['e', 'm']);
864     /// assert_eq!(iter.next().unwrap(), &['o', 'r']);
865     /// assert_eq!(iter.next().unwrap(), &['l']);
866     /// assert!(iter.next().is_none());
867     /// ```
868     ///
869     /// [`rchunks_exact`]: #method.rchunks_exact
870     /// [`chunks`]: #method.chunks
871     #[stable(feature = "rchunks", since = "1.31.0")]
872     #[inline]
873     pub fn rchunks(&self, chunk_size: usize) -> RChunks<'_, T> {
874         assert!(chunk_size != 0);
875         RChunks { v: self, chunk_size }
876     }
877
878     /// Returns an iterator over `chunk_size` elements of the slice at a time, starting at the end
879     /// of the slice.
880     ///
881     /// The chunks are mutable slices, and do not overlap. If `chunk_size` does not divide the
882     /// length of the slice, then the last chunk will not have length `chunk_size`.
883     ///
884     /// See [`rchunks_exact_mut`] for a variant of this iterator that returns chunks of always
885     /// exactly `chunk_size` elements, and [`chunks_mut`] for the same iterator but starting at the
886     /// beginning of the slice.
887     ///
888     /// # Panics
889     ///
890     /// Panics if `chunk_size` is 0.
891     ///
892     /// # Examples
893     ///
894     /// ```
895     /// let v = &mut [0, 0, 0, 0, 0];
896     /// let mut count = 1;
897     ///
898     /// for chunk in v.rchunks_mut(2) {
899     ///     for elem in chunk.iter_mut() {
900     ///         *elem += count;
901     ///     }
902     ///     count += 1;
903     /// }
904     /// assert_eq!(v, &[3, 2, 2, 1, 1]);
905     /// ```
906     ///
907     /// [`rchunks_exact_mut`]: #method.rchunks_exact_mut
908     /// [`chunks_mut`]: #method.chunks_mut
909     #[stable(feature = "rchunks", since = "1.31.0")]
910     #[inline]
911     pub fn rchunks_mut(&mut self, chunk_size: usize) -> RChunksMut<'_, T> {
912         assert!(chunk_size != 0);
913         RChunksMut { v: self, chunk_size }
914     }
915
916     /// Returns an iterator over `chunk_size` elements of the slice at a time, starting at the
917     /// end of the slice.
918     ///
919     /// The chunks are slices and do not overlap. If `chunk_size` does not divide the length of the
920     /// slice, then the last up to `chunk_size-1` elements will be omitted and can be retrieved
921     /// from the `remainder` function of the iterator.
922     ///
923     /// Due to each chunk having exactly `chunk_size` elements, the compiler can often optimize the
924     /// resulting code better than in the case of [`chunks`].
925     ///
926     /// See [`rchunks`] for a variant of this iterator that also returns the remainder as a smaller
927     /// chunk, and [`chunks_exact`] for the same iterator but starting at the beginning of the
928     /// slice.
929     ///
930     /// # Panics
931     ///
932     /// Panics if `chunk_size` is 0.
933     ///
934     /// # Examples
935     ///
936     /// ```
937     /// let slice = ['l', 'o', 'r', 'e', 'm'];
938     /// let mut iter = slice.rchunks_exact(2);
939     /// assert_eq!(iter.next().unwrap(), &['e', 'm']);
940     /// assert_eq!(iter.next().unwrap(), &['o', 'r']);
941     /// assert!(iter.next().is_none());
942     /// assert_eq!(iter.remainder(), &['l']);
943     /// ```
944     ///
945     /// [`chunks`]: #method.chunks
946     /// [`rchunks`]: #method.rchunks
947     /// [`chunks_exact`]: #method.chunks_exact
948     #[stable(feature = "rchunks", since = "1.31.0")]
949     #[inline]
950     pub fn rchunks_exact(&self, chunk_size: usize) -> RChunksExact<'_, T> {
951         assert!(chunk_size != 0);
952         let rem = self.len() % chunk_size;
953         let (fst, snd) = self.split_at(rem);
954         RChunksExact { v: snd, rem: fst, chunk_size }
955     }
956
957     /// Returns an iterator over `chunk_size` elements of the slice at a time, starting at the end
958     /// of the slice.
959     ///
960     /// The chunks are mutable slices, and do not overlap. If `chunk_size` does not divide the
961     /// length of the slice, then the last up to `chunk_size-1` elements will be omitted and can be
962     /// retrieved from the `into_remainder` function of the iterator.
963     ///
964     /// Due to each chunk having exactly `chunk_size` elements, the compiler can often optimize the
965     /// resulting code better than in the case of [`chunks_mut`].
966     ///
967     /// See [`rchunks_mut`] for a variant of this iterator that also returns the remainder as a
968     /// smaller chunk, and [`chunks_exact_mut`] for the same iterator but starting at the beginning
969     /// of the slice.
970     ///
971     /// # Panics
972     ///
973     /// Panics if `chunk_size` is 0.
974     ///
975     /// # Examples
976     ///
977     /// ```
978     /// let v = &mut [0, 0, 0, 0, 0];
979     /// let mut count = 1;
980     ///
981     /// for chunk in v.rchunks_exact_mut(2) {
982     ///     for elem in chunk.iter_mut() {
983     ///         *elem += count;
984     ///     }
985     ///     count += 1;
986     /// }
987     /// assert_eq!(v, &[0, 2, 2, 1, 1]);
988     /// ```
989     ///
990     /// [`chunks_mut`]: #method.chunks_mut
991     /// [`rchunks_mut`]: #method.rchunks_mut
992     /// [`chunks_exact_mut`]: #method.chunks_exact_mut
993     #[stable(feature = "rchunks", since = "1.31.0")]
994     #[inline]
995     pub fn rchunks_exact_mut(&mut self, chunk_size: usize) -> RChunksExactMut<'_, T> {
996         assert!(chunk_size != 0);
997         let rem = self.len() % chunk_size;
998         let (fst, snd) = self.split_at_mut(rem);
999         RChunksExactMut { v: snd, rem: fst, chunk_size }
1000     }
1001
1002     /// Divides one slice into two at an index.
1003     ///
1004     /// The first will contain all indices from `[0, mid)` (excluding
1005     /// the index `mid` itself) and the second will contain all
1006     /// indices from `[mid, len)` (excluding the index `len` itself).
1007     ///
1008     /// # Panics
1009     ///
1010     /// Panics if `mid > len`.
1011     ///
1012     /// # Examples
1013     ///
1014     /// ```
1015     /// let v = [1, 2, 3, 4, 5, 6];
1016     ///
1017     /// {
1018     ///    let (left, right) = v.split_at(0);
1019     ///    assert!(left == []);
1020     ///    assert!(right == [1, 2, 3, 4, 5, 6]);
1021     /// }
1022     ///
1023     /// {
1024     ///     let (left, right) = v.split_at(2);
1025     ///     assert!(left == [1, 2]);
1026     ///     assert!(right == [3, 4, 5, 6]);
1027     /// }
1028     ///
1029     /// {
1030     ///     let (left, right) = v.split_at(6);
1031     ///     assert!(left == [1, 2, 3, 4, 5, 6]);
1032     ///     assert!(right == []);
1033     /// }
1034     /// ```
1035     #[stable(feature = "rust1", since = "1.0.0")]
1036     #[inline]
1037     pub fn split_at(&self, mid: usize) -> (&[T], &[T]) {
1038         (&self[..mid], &self[mid..])
1039     }
1040
1041     /// Divides one mutable slice into two at an index.
1042     ///
1043     /// The first will contain all indices from `[0, mid)` (excluding
1044     /// the index `mid` itself) and the second will contain all
1045     /// indices from `[mid, len)` (excluding the index `len` itself).
1046     ///
1047     /// # Panics
1048     ///
1049     /// Panics if `mid > len`.
1050     ///
1051     /// # Examples
1052     ///
1053     /// ```
1054     /// let mut v = [1, 0, 3, 0, 5, 6];
1055     /// // scoped to restrict the lifetime of the borrows
1056     /// {
1057     ///     let (left, right) = v.split_at_mut(2);
1058     ///     assert!(left == [1, 0]);
1059     ///     assert!(right == [3, 0, 5, 6]);
1060     ///     left[1] = 2;
1061     ///     right[1] = 4;
1062     /// }
1063     /// assert!(v == [1, 2, 3, 4, 5, 6]);
1064     /// ```
1065     #[stable(feature = "rust1", since = "1.0.0")]
1066     #[inline]
1067     pub fn split_at_mut(&mut self, mid: usize) -> (&mut [T], &mut [T]) {
1068         let len = self.len();
1069         let ptr = self.as_mut_ptr();
1070
1071         unsafe {
1072             assert!(mid <= len);
1073
1074             (from_raw_parts_mut(ptr, mid), from_raw_parts_mut(ptr.add(mid), len - mid))
1075         }
1076     }
1077
1078     /// Returns an iterator over subslices separated by elements that match
1079     /// `pred`. The matched element is not contained in the subslices.
1080     ///
1081     /// # Examples
1082     ///
1083     /// ```
1084     /// let slice = [10, 40, 33, 20];
1085     /// let mut iter = slice.split(|num| num % 3 == 0);
1086     ///
1087     /// assert_eq!(iter.next().unwrap(), &[10, 40]);
1088     /// assert_eq!(iter.next().unwrap(), &[20]);
1089     /// assert!(iter.next().is_none());
1090     /// ```
1091     ///
1092     /// If the first element is matched, an empty slice will be the first item
1093     /// returned by the iterator. Similarly, if the last element in the slice
1094     /// is matched, an empty slice will be the last item returned by the
1095     /// iterator:
1096     ///
1097     /// ```
1098     /// let slice = [10, 40, 33];
1099     /// let mut iter = slice.split(|num| num % 3 == 0);
1100     ///
1101     /// assert_eq!(iter.next().unwrap(), &[10, 40]);
1102     /// assert_eq!(iter.next().unwrap(), &[]);
1103     /// assert!(iter.next().is_none());
1104     /// ```
1105     ///
1106     /// If two matched elements are directly adjacent, an empty slice will be
1107     /// present between them:
1108     ///
1109     /// ```
1110     /// let slice = [10, 6, 33, 20];
1111     /// let mut iter = slice.split(|num| num % 3 == 0);
1112     ///
1113     /// assert_eq!(iter.next().unwrap(), &[10]);
1114     /// assert_eq!(iter.next().unwrap(), &[]);
1115     /// assert_eq!(iter.next().unwrap(), &[20]);
1116     /// assert!(iter.next().is_none());
1117     /// ```
1118     #[stable(feature = "rust1", since = "1.0.0")]
1119     #[inline]
1120     pub fn split<F>(&self, pred: F) -> Split<'_, T, F>
1121     where
1122         F: FnMut(&T) -> bool,
1123     {
1124         Split { v: self, pred, finished: false }
1125     }
1126
1127     /// Returns an iterator over mutable subslices separated by elements that
1128     /// match `pred`. The matched element is not contained in the subslices.
1129     ///
1130     /// # Examples
1131     ///
1132     /// ```
1133     /// let mut v = [10, 40, 30, 20, 60, 50];
1134     ///
1135     /// for group in v.split_mut(|num| *num % 3 == 0) {
1136     ///     group[0] = 1;
1137     /// }
1138     /// assert_eq!(v, [1, 40, 30, 1, 60, 1]);
1139     /// ```
1140     #[stable(feature = "rust1", since = "1.0.0")]
1141     #[inline]
1142     pub fn split_mut<F>(&mut self, pred: F) -> SplitMut<'_, T, F>
1143     where
1144         F: FnMut(&T) -> bool,
1145     {
1146         SplitMut { v: self, pred, finished: false }
1147     }
1148
1149     /// Returns an iterator over subslices separated by elements that match
1150     /// `pred`. The matched element is contained in the end of the previous
1151     /// subslice as a terminator.
1152     ///
1153     /// # Examples
1154     ///
1155     /// ```
1156     /// #![feature(split_inclusive)]
1157     /// let slice = [10, 40, 33, 20];
1158     /// let mut iter = slice.split_inclusive(|num| num % 3 == 0);
1159     ///
1160     /// assert_eq!(iter.next().unwrap(), &[10, 40, 33]);
1161     /// assert_eq!(iter.next().unwrap(), &[20]);
1162     /// assert!(iter.next().is_none());
1163     /// ```
1164     ///
1165     /// If the last element of the slice is matched,
1166     /// that element will be considered the terminator of the preceding slice.
1167     /// That slice will be the last item returned by the iterator.
1168     ///
1169     /// ```
1170     /// #![feature(split_inclusive)]
1171     /// let slice = [3, 10, 40, 33];
1172     /// let mut iter = slice.split_inclusive(|num| num % 3 == 0);
1173     ///
1174     /// assert_eq!(iter.next().unwrap(), &[3]);
1175     /// assert_eq!(iter.next().unwrap(), &[10, 40, 33]);
1176     /// assert!(iter.next().is_none());
1177     /// ```
1178     #[unstable(feature = "split_inclusive", issue = "72360")]
1179     #[inline]
1180     pub fn split_inclusive<F>(&self, pred: F) -> SplitInclusive<'_, T, F>
1181     where
1182         F: FnMut(&T) -> bool,
1183     {
1184         SplitInclusive { v: self, pred, finished: false }
1185     }
1186
1187     /// Returns an iterator over mutable subslices separated by elements that
1188     /// match `pred`. The matched element is contained in the previous
1189     /// subslice as a terminator.
1190     ///
1191     /// # Examples
1192     ///
1193     /// ```
1194     /// #![feature(split_inclusive)]
1195     /// let mut v = [10, 40, 30, 20, 60, 50];
1196     ///
1197     /// for group in v.split_inclusive_mut(|num| *num % 3 == 0) {
1198     ///     let terminator_idx = group.len()-1;
1199     ///     group[terminator_idx] = 1;
1200     /// }
1201     /// assert_eq!(v, [10, 40, 1, 20, 1, 1]);
1202     /// ```
1203     #[unstable(feature = "split_inclusive", issue = "72360")]
1204     #[inline]
1205     pub fn split_inclusive_mut<F>(&mut self, pred: F) -> SplitInclusiveMut<'_, T, F>
1206     where
1207         F: FnMut(&T) -> bool,
1208     {
1209         SplitInclusiveMut { v: self, pred, finished: false }
1210     }
1211
1212     /// Returns an iterator over subslices separated by elements that match
1213     /// `pred`, starting at the end of the slice and working backwards.
1214     /// The matched element is not contained in the subslices.
1215     ///
1216     /// # Examples
1217     ///
1218     /// ```
1219     /// let slice = [11, 22, 33, 0, 44, 55];
1220     /// let mut iter = slice.rsplit(|num| *num == 0);
1221     ///
1222     /// assert_eq!(iter.next().unwrap(), &[44, 55]);
1223     /// assert_eq!(iter.next().unwrap(), &[11, 22, 33]);
1224     /// assert_eq!(iter.next(), None);
1225     /// ```
1226     ///
1227     /// As with `split()`, if the first or last element is matched, an empty
1228     /// slice will be the first (or last) item returned by the iterator.
1229     ///
1230     /// ```
1231     /// let v = &[0, 1, 1, 2, 3, 5, 8];
1232     /// let mut it = v.rsplit(|n| *n % 2 == 0);
1233     /// assert_eq!(it.next().unwrap(), &[]);
1234     /// assert_eq!(it.next().unwrap(), &[3, 5]);
1235     /// assert_eq!(it.next().unwrap(), &[1, 1]);
1236     /// assert_eq!(it.next().unwrap(), &[]);
1237     /// assert_eq!(it.next(), None);
1238     /// ```
1239     #[stable(feature = "slice_rsplit", since = "1.27.0")]
1240     #[inline]
1241     pub fn rsplit<F>(&self, pred: F) -> RSplit<'_, T, F>
1242     where
1243         F: FnMut(&T) -> bool,
1244     {
1245         RSplit { inner: self.split(pred) }
1246     }
1247
1248     /// Returns an iterator over mutable subslices separated by elements that
1249     /// match `pred`, starting at the end of the slice and working
1250     /// backwards. The matched element is not contained in the subslices.
1251     ///
1252     /// # Examples
1253     ///
1254     /// ```
1255     /// let mut v = [100, 400, 300, 200, 600, 500];
1256     ///
1257     /// let mut count = 0;
1258     /// for group in v.rsplit_mut(|num| *num % 3 == 0) {
1259     ///     count += 1;
1260     ///     group[0] = count;
1261     /// }
1262     /// assert_eq!(v, [3, 400, 300, 2, 600, 1]);
1263     /// ```
1264     ///
1265     #[stable(feature = "slice_rsplit", since = "1.27.0")]
1266     #[inline]
1267     pub fn rsplit_mut<F>(&mut self, pred: F) -> RSplitMut<'_, T, F>
1268     where
1269         F: FnMut(&T) -> bool,
1270     {
1271         RSplitMut { inner: self.split_mut(pred) }
1272     }
1273
1274     /// Returns an iterator over subslices separated by elements that match
1275     /// `pred`, limited to returning at most `n` items. The matched element is
1276     /// not contained in the subslices.
1277     ///
1278     /// The last element returned, if any, will contain the remainder of the
1279     /// slice.
1280     ///
1281     /// # Examples
1282     ///
1283     /// Print the slice split once by numbers divisible by 3 (i.e., `[10, 40]`,
1284     /// `[20, 60, 50]`):
1285     ///
1286     /// ```
1287     /// let v = [10, 40, 30, 20, 60, 50];
1288     ///
1289     /// for group in v.splitn(2, |num| *num % 3 == 0) {
1290     ///     println!("{:?}", group);
1291     /// }
1292     /// ```
1293     #[stable(feature = "rust1", since = "1.0.0")]
1294     #[inline]
1295     pub fn splitn<F>(&self, n: usize, pred: F) -> SplitN<'_, T, F>
1296     where
1297         F: FnMut(&T) -> bool,
1298     {
1299         SplitN { inner: GenericSplitN { iter: self.split(pred), count: n } }
1300     }
1301
1302     /// Returns an iterator over subslices separated by elements that match
1303     /// `pred`, limited to returning at most `n` items. The matched element is
1304     /// not contained in the subslices.
1305     ///
1306     /// The last element returned, if any, will contain the remainder of the
1307     /// slice.
1308     ///
1309     /// # Examples
1310     ///
1311     /// ```
1312     /// let mut v = [10, 40, 30, 20, 60, 50];
1313     ///
1314     /// for group in v.splitn_mut(2, |num| *num % 3 == 0) {
1315     ///     group[0] = 1;
1316     /// }
1317     /// assert_eq!(v, [1, 40, 30, 1, 60, 50]);
1318     /// ```
1319     #[stable(feature = "rust1", since = "1.0.0")]
1320     #[inline]
1321     pub fn splitn_mut<F>(&mut self, n: usize, pred: F) -> SplitNMut<'_, T, F>
1322     where
1323         F: FnMut(&T) -> bool,
1324     {
1325         SplitNMut { inner: GenericSplitN { iter: self.split_mut(pred), count: n } }
1326     }
1327
1328     /// Returns an iterator over subslices separated by elements that match
1329     /// `pred` limited to returning at most `n` items. This starts at the end of
1330     /// the slice and works backwards. The matched element is not contained in
1331     /// the subslices.
1332     ///
1333     /// The last element returned, if any, will contain the remainder of the
1334     /// slice.
1335     ///
1336     /// # Examples
1337     ///
1338     /// Print the slice split once, starting from the end, by numbers divisible
1339     /// by 3 (i.e., `[50]`, `[10, 40, 30, 20]`):
1340     ///
1341     /// ```
1342     /// let v = [10, 40, 30, 20, 60, 50];
1343     ///
1344     /// for group in v.rsplitn(2, |num| *num % 3 == 0) {
1345     ///     println!("{:?}", group);
1346     /// }
1347     /// ```
1348     #[stable(feature = "rust1", since = "1.0.0")]
1349     #[inline]
1350     pub fn rsplitn<F>(&self, n: usize, pred: F) -> RSplitN<'_, T, F>
1351     where
1352         F: FnMut(&T) -> bool,
1353     {
1354         RSplitN { inner: GenericSplitN { iter: self.rsplit(pred), count: n } }
1355     }
1356
1357     /// Returns an iterator over subslices separated by elements that match
1358     /// `pred` limited to returning at most `n` items. This starts at the end of
1359     /// the slice and works backwards. The matched element is not contained in
1360     /// the subslices.
1361     ///
1362     /// The last element returned, if any, will contain the remainder of the
1363     /// slice.
1364     ///
1365     /// # Examples
1366     ///
1367     /// ```
1368     /// let mut s = [10, 40, 30, 20, 60, 50];
1369     ///
1370     /// for group in s.rsplitn_mut(2, |num| *num % 3 == 0) {
1371     ///     group[0] = 1;
1372     /// }
1373     /// assert_eq!(s, [1, 40, 30, 20, 60, 1]);
1374     /// ```
1375     #[stable(feature = "rust1", since = "1.0.0")]
1376     #[inline]
1377     pub fn rsplitn_mut<F>(&mut self, n: usize, pred: F) -> RSplitNMut<'_, T, F>
1378     where
1379         F: FnMut(&T) -> bool,
1380     {
1381         RSplitNMut { inner: GenericSplitN { iter: self.rsplit_mut(pred), count: n } }
1382     }
1383
1384     /// Returns `true` if the slice contains an element with the given value.
1385     ///
1386     /// # Examples
1387     ///
1388     /// ```
1389     /// let v = [10, 40, 30];
1390     /// assert!(v.contains(&30));
1391     /// assert!(!v.contains(&50));
1392     /// ```
1393     ///
1394     /// If you do not have an `&T`, but just an `&U` such that `T: Borrow<U>`
1395     /// (e.g. `String: Borrow<str>`), you can use `iter().any`:
1396     ///
1397     /// ```
1398     /// let v = [String::from("hello"), String::from("world")]; // slice of `String`
1399     /// assert!(v.iter().any(|e| e == "hello")); // search with `&str`
1400     /// assert!(!v.iter().any(|e| e == "hi"));
1401     /// ```
1402     #[stable(feature = "rust1", since = "1.0.0")]
1403     pub fn contains(&self, x: &T) -> bool
1404     where
1405         T: PartialEq,
1406     {
1407         x.slice_contains(self)
1408     }
1409
1410     /// Returns `true` if `needle` is a prefix of the slice.
1411     ///
1412     /// # Examples
1413     ///
1414     /// ```
1415     /// let v = [10, 40, 30];
1416     /// assert!(v.starts_with(&[10]));
1417     /// assert!(v.starts_with(&[10, 40]));
1418     /// assert!(!v.starts_with(&[50]));
1419     /// assert!(!v.starts_with(&[10, 50]));
1420     /// ```
1421     ///
1422     /// Always returns `true` if `needle` is an empty slice:
1423     ///
1424     /// ```
1425     /// let v = &[10, 40, 30];
1426     /// assert!(v.starts_with(&[]));
1427     /// let v: &[u8] = &[];
1428     /// assert!(v.starts_with(&[]));
1429     /// ```
1430     #[stable(feature = "rust1", since = "1.0.0")]
1431     pub fn starts_with(&self, needle: &[T]) -> bool
1432     where
1433         T: PartialEq,
1434     {
1435         let n = needle.len();
1436         self.len() >= n && needle == &self[..n]
1437     }
1438
1439     /// Returns `true` if `needle` is a suffix of the slice.
1440     ///
1441     /// # Examples
1442     ///
1443     /// ```
1444     /// let v = [10, 40, 30];
1445     /// assert!(v.ends_with(&[30]));
1446     /// assert!(v.ends_with(&[40, 30]));
1447     /// assert!(!v.ends_with(&[50]));
1448     /// assert!(!v.ends_with(&[50, 30]));
1449     /// ```
1450     ///
1451     /// Always returns `true` if `needle` is an empty slice:
1452     ///
1453     /// ```
1454     /// let v = &[10, 40, 30];
1455     /// assert!(v.ends_with(&[]));
1456     /// let v: &[u8] = &[];
1457     /// assert!(v.ends_with(&[]));
1458     /// ```
1459     #[stable(feature = "rust1", since = "1.0.0")]
1460     pub fn ends_with(&self, needle: &[T]) -> bool
1461     where
1462         T: PartialEq,
1463     {
1464         let (m, n) = (self.len(), needle.len());
1465         m >= n && needle == &self[m - n..]
1466     }
1467
1468     /// Returns a subslice with the prefix removed.
1469     ///
1470     /// This method returns [`None`] if slice does not start with `prefix`.
1471     /// Also it returns the original slice if `prefix` is an empty slice.
1472     ///
1473     /// # Examples
1474     ///
1475     /// ```
1476     /// #![feature(slice_strip)]
1477     /// let v = &[10, 40, 30];
1478     /// assert_eq!(v.strip_prefix(&[10]), Some(&[40, 30][..]));
1479     /// assert_eq!(v.strip_prefix(&[10, 40]), Some(&[30][..]));
1480     /// assert_eq!(v.strip_prefix(&[50]), None);
1481     /// assert_eq!(v.strip_prefix(&[10, 50]), None);
1482     /// ```
1483     #[must_use = "returns the subslice without modifying the original"]
1484     #[unstable(feature = "slice_strip", issue = "73413")]
1485     pub fn strip_prefix(&self, prefix: &[T]) -> Option<&[T]>
1486     where
1487         T: PartialEq,
1488     {
1489         let n = prefix.len();
1490         if n <= self.len() {
1491             let (head, tail) = self.split_at(n);
1492             if head == prefix {
1493                 return Some(tail);
1494             }
1495         }
1496         None
1497     }
1498
1499     /// Returns a subslice with the suffix removed.
1500     ///
1501     /// This method returns [`None`] if slice does not end with `suffix`.
1502     /// Also it returns the original slice if `suffix` is an empty slice
1503     ///
1504     /// # Examples
1505     ///
1506     /// ```
1507     /// #![feature(slice_strip)]
1508     /// let v = &[10, 40, 30];
1509     /// assert_eq!(v.strip_suffix(&[30]), Some(&[10, 40][..]));
1510     /// assert_eq!(v.strip_suffix(&[40, 30]), Some(&[10][..]));
1511     /// assert_eq!(v.strip_suffix(&[50]), None);
1512     /// assert_eq!(v.strip_suffix(&[50, 30]), None);
1513     /// ```
1514     #[must_use = "returns the subslice without modifying the original"]
1515     #[unstable(feature = "slice_strip", issue = "73413")]
1516     pub fn strip_suffix(&self, suffix: &[T]) -> Option<&[T]>
1517     where
1518         T: PartialEq,
1519     {
1520         let (len, n) = (self.len(), suffix.len());
1521         if n <= len {
1522             let (head, tail) = self.split_at(len - n);
1523             if tail == suffix {
1524                 return Some(head);
1525             }
1526         }
1527         None
1528     }
1529
1530     /// Binary searches this sorted slice for a given element.
1531     ///
1532     /// If the value is found then [`Result::Ok`] is returned, containing the
1533     /// index of the matching element. If there are multiple matches, then any
1534     /// one of the matches could be returned. If the value is not found then
1535     /// [`Result::Err`] is returned, containing the index where a matching
1536     /// element could be inserted while maintaining sorted order.
1537     ///
1538     /// # Examples
1539     ///
1540     /// Looks up a series of four elements. The first is found, with a
1541     /// uniquely determined position; the second and third are not
1542     /// found; the fourth could match any position in `[1, 4]`.
1543     ///
1544     /// ```
1545     /// let s = [0, 1, 1, 1, 1, 2, 3, 5, 8, 13, 21, 34, 55];
1546     ///
1547     /// assert_eq!(s.binary_search(&13),  Ok(9));
1548     /// assert_eq!(s.binary_search(&4),   Err(7));
1549     /// assert_eq!(s.binary_search(&100), Err(13));
1550     /// let r = s.binary_search(&1);
1551     /// assert!(match r { Ok(1..=4) => true, _ => false, });
1552     /// ```
1553     ///
1554     /// If you want to insert an item to a sorted vector, while maintaining
1555     /// sort order:
1556     ///
1557     /// ```
1558     /// let mut s = vec![0, 1, 1, 1, 1, 2, 3, 5, 8, 13, 21, 34, 55];
1559     /// let num = 42;
1560     /// let idx = s.binary_search(&num).unwrap_or_else(|x| x);
1561     /// s.insert(idx, num);
1562     /// assert_eq!(s, [0, 1, 1, 1, 1, 2, 3, 5, 8, 13, 21, 34, 42, 55]);
1563     /// ```
1564     #[stable(feature = "rust1", since = "1.0.0")]
1565     pub fn binary_search(&self, x: &T) -> Result<usize, usize>
1566     where
1567         T: Ord,
1568     {
1569         self.binary_search_by(|p| p.cmp(x))
1570     }
1571
1572     /// Binary searches this sorted slice with a comparator function.
1573     ///
1574     /// The comparator function should implement an order consistent
1575     /// with the sort order of the underlying slice, returning an
1576     /// order code that indicates whether its argument is `Less`,
1577     /// `Equal` or `Greater` the desired target.
1578     ///
1579     /// If the value is found then [`Result::Ok`] is returned, containing the
1580     /// index of the matching element. If there are multiple matches, then any
1581     /// one of the matches could be returned. If the value is not found then
1582     /// [`Result::Err`] is returned, containing the index where a matching
1583     /// element could be inserted while maintaining sorted order.
1584     ///
1585     /// # Examples
1586     ///
1587     /// Looks up a series of four elements. The first is found, with a
1588     /// uniquely determined position; the second and third are not
1589     /// found; the fourth could match any position in `[1, 4]`.
1590     ///
1591     /// ```
1592     /// let s = [0, 1, 1, 1, 1, 2, 3, 5, 8, 13, 21, 34, 55];
1593     ///
1594     /// let seek = 13;
1595     /// assert_eq!(s.binary_search_by(|probe| probe.cmp(&seek)), Ok(9));
1596     /// let seek = 4;
1597     /// assert_eq!(s.binary_search_by(|probe| probe.cmp(&seek)), Err(7));
1598     /// let seek = 100;
1599     /// assert_eq!(s.binary_search_by(|probe| probe.cmp(&seek)), Err(13));
1600     /// let seek = 1;
1601     /// let r = s.binary_search_by(|probe| probe.cmp(&seek));
1602     /// assert!(match r { Ok(1..=4) => true, _ => false, });
1603     /// ```
1604     #[stable(feature = "rust1", since = "1.0.0")]
1605     #[inline]
1606     pub fn binary_search_by<'a, F>(&'a self, mut f: F) -> Result<usize, usize>
1607     where
1608         F: FnMut(&'a T) -> Ordering,
1609     {
1610         let s = self;
1611         let mut size = s.len();
1612         if size == 0 {
1613             return Err(0);
1614         }
1615         let mut base = 0usize;
1616         while size > 1 {
1617             let half = size / 2;
1618             let mid = base + half;
1619             // mid is always in [0, size), that means mid is >= 0 and < size.
1620             // mid >= 0: by definition
1621             // mid < size: mid = size / 2 + size / 4 + size / 8 ...
1622             let cmp = f(unsafe { s.get_unchecked(mid) });
1623             base = if cmp == Greater { base } else { mid };
1624             size -= half;
1625         }
1626         // base is always in [0, size) because base <= mid.
1627         let cmp = f(unsafe { s.get_unchecked(base) });
1628         if cmp == Equal { Ok(base) } else { Err(base + (cmp == Less) as usize) }
1629     }
1630
1631     /// Binary searches this sorted slice with a key extraction function.
1632     ///
1633     /// Assumes that the slice is sorted by the key, for instance with
1634     /// [`sort_by_key`] using the same key extraction function.
1635     ///
1636     /// If the value is found then [`Result::Ok`] is returned, containing the
1637     /// index of the matching element. If there are multiple matches, then any
1638     /// one of the matches could be returned. If the value is not found then
1639     /// [`Result::Err`] is returned, containing the index where a matching
1640     /// element could be inserted while maintaining sorted order.
1641     ///
1642     /// [`sort_by_key`]: #method.sort_by_key
1643     ///
1644     /// # Examples
1645     ///
1646     /// Looks up a series of four elements in a slice of pairs sorted by
1647     /// their second elements. The first is found, with a uniquely
1648     /// determined position; the second and third are not found; the
1649     /// fourth could match any position in `[1, 4]`.
1650     ///
1651     /// ```
1652     /// let s = [(0, 0), (2, 1), (4, 1), (5, 1), (3, 1),
1653     ///          (1, 2), (2, 3), (4, 5), (5, 8), (3, 13),
1654     ///          (1, 21), (2, 34), (4, 55)];
1655     ///
1656     /// assert_eq!(s.binary_search_by_key(&13, |&(a,b)| b),  Ok(9));
1657     /// assert_eq!(s.binary_search_by_key(&4, |&(a,b)| b),   Err(7));
1658     /// assert_eq!(s.binary_search_by_key(&100, |&(a,b)| b), Err(13));
1659     /// let r = s.binary_search_by_key(&1, |&(a,b)| b);
1660     /// assert!(match r { Ok(1..=4) => true, _ => false, });
1661     /// ```
1662     #[stable(feature = "slice_binary_search_by_key", since = "1.10.0")]
1663     #[inline]
1664     pub fn binary_search_by_key<'a, B, F>(&'a self, b: &B, mut f: F) -> Result<usize, usize>
1665     where
1666         F: FnMut(&'a T) -> B,
1667         B: Ord,
1668     {
1669         self.binary_search_by(|k| f(k).cmp(b))
1670     }
1671
1672     /// Sorts the slice, but may not preserve the order of equal elements.
1673     ///
1674     /// This sort is unstable (i.e., may reorder equal elements), in-place
1675     /// (i.e., does not allocate), and `O(n * log(n))` worst-case.
1676     ///
1677     /// # Current implementation
1678     ///
1679     /// The current algorithm is based on [pattern-defeating quicksort][pdqsort] by Orson Peters,
1680     /// which combines the fast average case of randomized quicksort with the fast worst case of
1681     /// heapsort, while achieving linear time on slices with certain patterns. It uses some
1682     /// randomization to avoid degenerate cases, but with a fixed seed to always provide
1683     /// deterministic behavior.
1684     ///
1685     /// It is typically faster than stable sorting, except in a few special cases, e.g., when the
1686     /// slice consists of several concatenated sorted sequences.
1687     ///
1688     /// # Examples
1689     ///
1690     /// ```
1691     /// let mut v = [-5, 4, 1, -3, 2];
1692     ///
1693     /// v.sort_unstable();
1694     /// assert!(v == [-5, -3, 1, 2, 4]);
1695     /// ```
1696     ///
1697     /// [pdqsort]: https://github.com/orlp/pdqsort
1698     #[stable(feature = "sort_unstable", since = "1.20.0")]
1699     #[inline]
1700     pub fn sort_unstable(&mut self)
1701     where
1702         T: Ord,
1703     {
1704         sort::quicksort(self, |a, b| a.lt(b));
1705     }
1706
1707     /// Sorts the slice with a comparator function, but may not preserve the order of equal
1708     /// elements.
1709     ///
1710     /// This sort is unstable (i.e., may reorder equal elements), in-place
1711     /// (i.e., does not allocate), and `O(n * log(n))` worst-case.
1712     ///
1713     /// The comparator function must define a total ordering for the elements in the slice. If
1714     /// the ordering is not total, the order of the elements is unspecified. An order is a
1715     /// total order if it is (for all a, b and c):
1716     ///
1717     /// * total and antisymmetric: exactly one of a < b, a == b or a > b is true; and
1718     /// * transitive, a < b and b < c implies a < c. The same must hold for both == and >.
1719     ///
1720     /// For example, while [`f64`] doesn't implement [`Ord`] because `NaN != NaN`, we can use
1721     /// `partial_cmp` as our sort function when we know the slice doesn't contain a `NaN`.
1722     ///
1723     /// ```
1724     /// let mut floats = [5f64, 4.0, 1.0, 3.0, 2.0];
1725     /// floats.sort_unstable_by(|a, b| a.partial_cmp(b).unwrap());
1726     /// assert_eq!(floats, [1.0, 2.0, 3.0, 4.0, 5.0]);
1727     /// ```
1728     ///
1729     /// # Current implementation
1730     ///
1731     /// The current algorithm is based on [pattern-defeating quicksort][pdqsort] by Orson Peters,
1732     /// which combines the fast average case of randomized quicksort with the fast worst case of
1733     /// heapsort, while achieving linear time on slices with certain patterns. It uses some
1734     /// randomization to avoid degenerate cases, but with a fixed seed to always provide
1735     /// deterministic behavior.
1736     ///
1737     /// It is typically faster than stable sorting, except in a few special cases, e.g., when the
1738     /// slice consists of several concatenated sorted sequences.
1739     ///
1740     /// # Examples
1741     ///
1742     /// ```
1743     /// let mut v = [5, 4, 1, 3, 2];
1744     /// v.sort_unstable_by(|a, b| a.cmp(b));
1745     /// assert!(v == [1, 2, 3, 4, 5]);
1746     ///
1747     /// // reverse sorting
1748     /// v.sort_unstable_by(|a, b| b.cmp(a));
1749     /// assert!(v == [5, 4, 3, 2, 1]);
1750     /// ```
1751     ///
1752     /// [pdqsort]: https://github.com/orlp/pdqsort
1753     #[stable(feature = "sort_unstable", since = "1.20.0")]
1754     #[inline]
1755     pub fn sort_unstable_by<F>(&mut self, mut compare: F)
1756     where
1757         F: FnMut(&T, &T) -> Ordering,
1758     {
1759         sort::quicksort(self, |a, b| compare(a, b) == Ordering::Less);
1760     }
1761
1762     /// Sorts the slice with a key extraction function, but may not preserve the order of equal
1763     /// elements.
1764     ///
1765     /// This sort is unstable (i.e., may reorder equal elements), in-place
1766     /// (i.e., does not allocate), and `O(m * n * log(n))` worst-case, where the key function is
1767     /// `O(m)`.
1768     ///
1769     /// # Current implementation
1770     ///
1771     /// The current algorithm is based on [pattern-defeating quicksort][pdqsort] by Orson Peters,
1772     /// which combines the fast average case of randomized quicksort with the fast worst case of
1773     /// heapsort, while achieving linear time on slices with certain patterns. It uses some
1774     /// randomization to avoid degenerate cases, but with a fixed seed to always provide
1775     /// deterministic behavior.
1776     ///
1777     /// Due to its key calling strategy, [`sort_unstable_by_key`](#method.sort_unstable_by_key)
1778     /// is likely to be slower than [`sort_by_cached_key`](#method.sort_by_cached_key) in
1779     /// cases where the key function is expensive.
1780     ///
1781     /// # Examples
1782     ///
1783     /// ```
1784     /// let mut v = [-5i32, 4, 1, -3, 2];
1785     ///
1786     /// v.sort_unstable_by_key(|k| k.abs());
1787     /// assert!(v == [1, 2, -3, 4, -5]);
1788     /// ```
1789     ///
1790     /// [pdqsort]: https://github.com/orlp/pdqsort
1791     #[stable(feature = "sort_unstable", since = "1.20.0")]
1792     #[inline]
1793     pub fn sort_unstable_by_key<K, F>(&mut self, mut f: F)
1794     where
1795         F: FnMut(&T) -> K,
1796         K: Ord,
1797     {
1798         sort::quicksort(self, |a, b| f(a).lt(&f(b)));
1799     }
1800
1801     /// Reorder the slice such that the element at `index` is at its final sorted position.
1802     ///
1803     /// This reordering has the additional property that any value at position `i < index` will be
1804     /// less than or equal to any value at a position `j > index`. Additionally, this reordering is
1805     /// unstable (i.e. any number of equal elements may end up at position `index`), in-place
1806     /// (i.e. does not allocate), and `O(n)` worst-case. This function is also/ known as "kth
1807     /// element" in other libraries. It returns a triplet of the following values: all elements less
1808     /// than the one at the given index, the value at the given index, and all elements greater than
1809     /// the one at the given index.
1810     ///
1811     /// # Current implementation
1812     ///
1813     /// The current algorithm is based on the quickselect portion of the same quicksort algorithm
1814     /// used for [`sort_unstable`].
1815     ///
1816     /// [`sort_unstable`]: #method.sort_unstable
1817     ///
1818     /// # Panics
1819     ///
1820     /// Panics when `index >= len()`, meaning it always panics on empty slices.
1821     ///
1822     /// # Examples
1823     ///
1824     /// ```
1825     /// #![feature(slice_partition_at_index)]
1826     ///
1827     /// let mut v = [-5i32, 4, 1, -3, 2];
1828     ///
1829     /// // Find the median
1830     /// v.partition_at_index(2);
1831     ///
1832     /// // We are only guaranteed the slice will be one of the following, based on the way we sort
1833     /// // about the specified index.
1834     /// assert!(v == [-3, -5, 1, 2, 4] ||
1835     ///         v == [-5, -3, 1, 2, 4] ||
1836     ///         v == [-3, -5, 1, 4, 2] ||
1837     ///         v == [-5, -3, 1, 4, 2]);
1838     /// ```
1839     #[unstable(feature = "slice_partition_at_index", issue = "55300")]
1840     #[inline]
1841     pub fn partition_at_index(&mut self, index: usize) -> (&mut [T], &mut T, &mut [T])
1842     where
1843         T: Ord,
1844     {
1845         let mut f = |a: &T, b: &T| a.lt(b);
1846         sort::partition_at_index(self, index, &mut f)
1847     }
1848
1849     /// Reorder the slice with a comparator function such that the element at `index` is at its
1850     /// final sorted position.
1851     ///
1852     /// This reordering has the additional property that any value at position `i < index` will be
1853     /// less than or equal to any value at a position `j > index` using the comparator function.
1854     /// Additionally, this reordering is unstable (i.e. any number of equal elements may end up at
1855     /// position `index`), in-place (i.e. does not allocate), and `O(n)` worst-case. This function
1856     /// is also known as "kth element" in other libraries. It returns a triplet of the following
1857     /// values: all elements less than the one at the given index, the value at the given index,
1858     /// and all elements greater than the one at the given index, using the provided comparator
1859     /// function.
1860     ///
1861     /// # Current implementation
1862     ///
1863     /// The current algorithm is based on the quickselect portion of the same quicksort algorithm
1864     /// used for [`sort_unstable`].
1865     ///
1866     /// [`sort_unstable`]: #method.sort_unstable
1867     ///
1868     /// # Panics
1869     ///
1870     /// Panics when `index >= len()`, meaning it always panics on empty slices.
1871     ///
1872     /// # Examples
1873     ///
1874     /// ```
1875     /// #![feature(slice_partition_at_index)]
1876     ///
1877     /// let mut v = [-5i32, 4, 1, -3, 2];
1878     ///
1879     /// // Find the median as if the slice were sorted in descending order.
1880     /// v.partition_at_index_by(2, |a, b| b.cmp(a));
1881     ///
1882     /// // We are only guaranteed the slice will be one of the following, based on the way we sort
1883     /// // about the specified index.
1884     /// assert!(v == [2, 4, 1, -5, -3] ||
1885     ///         v == [2, 4, 1, -3, -5] ||
1886     ///         v == [4, 2, 1, -5, -3] ||
1887     ///         v == [4, 2, 1, -3, -5]);
1888     /// ```
1889     #[unstable(feature = "slice_partition_at_index", issue = "55300")]
1890     #[inline]
1891     pub fn partition_at_index_by<F>(
1892         &mut self,
1893         index: usize,
1894         mut compare: F,
1895     ) -> (&mut [T], &mut T, &mut [T])
1896     where
1897         F: FnMut(&T, &T) -> Ordering,
1898     {
1899         let mut f = |a: &T, b: &T| compare(a, b) == Less;
1900         sort::partition_at_index(self, index, &mut f)
1901     }
1902
1903     /// Reorder the slice with a key extraction function such that the element at `index` is at its
1904     /// final sorted position.
1905     ///
1906     /// This reordering has the additional property that any value at position `i < index` will be
1907     /// less than or equal to any value at a position `j > index` using the key extraction function.
1908     /// Additionally, this reordering is unstable (i.e. any number of equal elements may end up at
1909     /// position `index`), in-place (i.e. does not allocate), and `O(n)` worst-case. This function
1910     /// is also known as "kth element" in other libraries. It returns a triplet of the following
1911     /// values: all elements less than the one at the given index, the value at the given index, and
1912     /// all elements greater than the one at the given index, using the provided key extraction
1913     /// function.
1914     ///
1915     /// # Current implementation
1916     ///
1917     /// The current algorithm is based on the quickselect portion of the same quicksort algorithm
1918     /// used for [`sort_unstable`].
1919     ///
1920     /// [`sort_unstable`]: #method.sort_unstable
1921     ///
1922     /// # Panics
1923     ///
1924     /// Panics when `index >= len()`, meaning it always panics on empty slices.
1925     ///
1926     /// # Examples
1927     ///
1928     /// ```
1929     /// #![feature(slice_partition_at_index)]
1930     ///
1931     /// let mut v = [-5i32, 4, 1, -3, 2];
1932     ///
1933     /// // Return the median as if the array were sorted according to absolute value.
1934     /// v.partition_at_index_by_key(2, |a| a.abs());
1935     ///
1936     /// // We are only guaranteed the slice will be one of the following, based on the way we sort
1937     /// // about the specified index.
1938     /// assert!(v == [1, 2, -3, 4, -5] ||
1939     ///         v == [1, 2, -3, -5, 4] ||
1940     ///         v == [2, 1, -3, 4, -5] ||
1941     ///         v == [2, 1, -3, -5, 4]);
1942     /// ```
1943     #[unstable(feature = "slice_partition_at_index", issue = "55300")]
1944     #[inline]
1945     pub fn partition_at_index_by_key<K, F>(
1946         &mut self,
1947         index: usize,
1948         mut f: F,
1949     ) -> (&mut [T], &mut T, &mut [T])
1950     where
1951         F: FnMut(&T) -> K,
1952         K: Ord,
1953     {
1954         let mut g = |a: &T, b: &T| f(a).lt(&f(b));
1955         sort::partition_at_index(self, index, &mut g)
1956     }
1957
1958     /// Moves all consecutive repeated elements to the end of the slice according to the
1959     /// [`PartialEq`] trait implementation.
1960     ///
1961     /// Returns two slices. The first contains no consecutive repeated elements.
1962     /// The second contains all the duplicates in no specified order.
1963     ///
1964     /// If the slice is sorted, the first returned slice contains no duplicates.
1965     ///
1966     /// # Examples
1967     ///
1968     /// ```
1969     /// #![feature(slice_partition_dedup)]
1970     ///
1971     /// let mut slice = [1, 2, 2, 3, 3, 2, 1, 1];
1972     ///
1973     /// let (dedup, duplicates) = slice.partition_dedup();
1974     ///
1975     /// assert_eq!(dedup, [1, 2, 3, 2, 1]);
1976     /// assert_eq!(duplicates, [2, 3, 1]);
1977     /// ```
1978     #[unstable(feature = "slice_partition_dedup", issue = "54279")]
1979     #[inline]
1980     pub fn partition_dedup(&mut self) -> (&mut [T], &mut [T])
1981     where
1982         T: PartialEq,
1983     {
1984         self.partition_dedup_by(|a, b| a == b)
1985     }
1986
1987     /// Moves all but the first of consecutive elements to the end of the slice satisfying
1988     /// a given equality relation.
1989     ///
1990     /// Returns two slices. The first contains no consecutive repeated elements.
1991     /// The second contains all the duplicates in no specified order.
1992     ///
1993     /// The `same_bucket` function is passed references to two elements from the slice and
1994     /// must determine if the elements compare equal. The elements are passed in opposite order
1995     /// from their order in the slice, so if `same_bucket(a, b)` returns `true`, `a` is moved
1996     /// at the end of the slice.
1997     ///
1998     /// If the slice is sorted, the first returned slice contains no duplicates.
1999     ///
2000     /// # Examples
2001     ///
2002     /// ```
2003     /// #![feature(slice_partition_dedup)]
2004     ///
2005     /// let mut slice = ["foo", "Foo", "BAZ", "Bar", "bar", "baz", "BAZ"];
2006     ///
2007     /// let (dedup, duplicates) = slice.partition_dedup_by(|a, b| a.eq_ignore_ascii_case(b));
2008     ///
2009     /// assert_eq!(dedup, ["foo", "BAZ", "Bar", "baz"]);
2010     /// assert_eq!(duplicates, ["bar", "Foo", "BAZ"]);
2011     /// ```
2012     #[unstable(feature = "slice_partition_dedup", issue = "54279")]
2013     #[inline]
2014     pub fn partition_dedup_by<F>(&mut self, mut same_bucket: F) -> (&mut [T], &mut [T])
2015     where
2016         F: FnMut(&mut T, &mut T) -> bool,
2017     {
2018         // Although we have a mutable reference to `self`, we cannot make
2019         // *arbitrary* changes. The `same_bucket` calls could panic, so we
2020         // must ensure that the slice is in a valid state at all times.
2021         //
2022         // The way that we handle this is by using swaps; we iterate
2023         // over all the elements, swapping as we go so that at the end
2024         // the elements we wish to keep are in the front, and those we
2025         // wish to reject are at the back. We can then split the slice.
2026         // This operation is still `O(n)`.
2027         //
2028         // Example: We start in this state, where `r` represents "next
2029         // read" and `w` represents "next_write`.
2030         //
2031         //           r
2032         //     +---+---+---+---+---+---+
2033         //     | 0 | 1 | 1 | 2 | 3 | 3 |
2034         //     +---+---+---+---+---+---+
2035         //           w
2036         //
2037         // Comparing self[r] against self[w-1], this is not a duplicate, so
2038         // we swap self[r] and self[w] (no effect as r==w) and then increment both
2039         // r and w, leaving us with:
2040         //
2041         //               r
2042         //     +---+---+---+---+---+---+
2043         //     | 0 | 1 | 1 | 2 | 3 | 3 |
2044         //     +---+---+---+---+---+---+
2045         //               w
2046         //
2047         // Comparing self[r] against self[w-1], this value is a duplicate,
2048         // so we increment `r` but leave everything else unchanged:
2049         //
2050         //                   r
2051         //     +---+---+---+---+---+---+
2052         //     | 0 | 1 | 1 | 2 | 3 | 3 |
2053         //     +---+---+---+---+---+---+
2054         //               w
2055         //
2056         // Comparing self[r] against self[w-1], this is not a duplicate,
2057         // so swap self[r] and self[w] and advance r and w:
2058         //
2059         //                       r
2060         //     +---+---+---+---+---+---+
2061         //     | 0 | 1 | 2 | 1 | 3 | 3 |
2062         //     +---+---+---+---+---+---+
2063         //                   w
2064         //
2065         // Not a duplicate, repeat:
2066         //
2067         //                           r
2068         //     +---+---+---+---+---+---+
2069         //     | 0 | 1 | 2 | 3 | 1 | 3 |
2070         //     +---+---+---+---+---+---+
2071         //                       w
2072         //
2073         // Duplicate, advance r. End of slice. Split at w.
2074
2075         let len = self.len();
2076         if len <= 1 {
2077             return (self, &mut []);
2078         }
2079
2080         let ptr = self.as_mut_ptr();
2081         let mut next_read: usize = 1;
2082         let mut next_write: usize = 1;
2083
2084         unsafe {
2085             // Avoid bounds checks by using raw pointers.
2086             while next_read < len {
2087                 let ptr_read = ptr.add(next_read);
2088                 let prev_ptr_write = ptr.add(next_write - 1);
2089                 if !same_bucket(&mut *ptr_read, &mut *prev_ptr_write) {
2090                     if next_read != next_write {
2091                         let ptr_write = prev_ptr_write.offset(1);
2092                         mem::swap(&mut *ptr_read, &mut *ptr_write);
2093                     }
2094                     next_write += 1;
2095                 }
2096                 next_read += 1;
2097             }
2098         }
2099
2100         self.split_at_mut(next_write)
2101     }
2102
2103     /// Moves all but the first of consecutive elements to the end of the slice that resolve
2104     /// to the same key.
2105     ///
2106     /// Returns two slices. The first contains no consecutive repeated elements.
2107     /// The second contains all the duplicates in no specified order.
2108     ///
2109     /// If the slice is sorted, the first returned slice contains no duplicates.
2110     ///
2111     /// # Examples
2112     ///
2113     /// ```
2114     /// #![feature(slice_partition_dedup)]
2115     ///
2116     /// let mut slice = [10, 20, 21, 30, 30, 20, 11, 13];
2117     ///
2118     /// let (dedup, duplicates) = slice.partition_dedup_by_key(|i| *i / 10);
2119     ///
2120     /// assert_eq!(dedup, [10, 20, 30, 20, 11]);
2121     /// assert_eq!(duplicates, [21, 30, 13]);
2122     /// ```
2123     #[unstable(feature = "slice_partition_dedup", issue = "54279")]
2124     #[inline]
2125     pub fn partition_dedup_by_key<K, F>(&mut self, mut key: F) -> (&mut [T], &mut [T])
2126     where
2127         F: FnMut(&mut T) -> K,
2128         K: PartialEq,
2129     {
2130         self.partition_dedup_by(|a, b| key(a) == key(b))
2131     }
2132
2133     /// Rotates the slice in-place such that the first `mid` elements of the
2134     /// slice move to the end while the last `self.len() - mid` elements move to
2135     /// the front. After calling `rotate_left`, the element previously at index
2136     /// `mid` will become the first element in the slice.
2137     ///
2138     /// # Panics
2139     ///
2140     /// This function will panic if `mid` is greater than the length of the
2141     /// slice. Note that `mid == self.len()` does _not_ panic and is a no-op
2142     /// rotation.
2143     ///
2144     /// # Complexity
2145     ///
2146     /// Takes linear (in `self.len()`) time.
2147     ///
2148     /// # Examples
2149     ///
2150     /// ```
2151     /// let mut a = ['a', 'b', 'c', 'd', 'e', 'f'];
2152     /// a.rotate_left(2);
2153     /// assert_eq!(a, ['c', 'd', 'e', 'f', 'a', 'b']);
2154     /// ```
2155     ///
2156     /// Rotating a subslice:
2157     ///
2158     /// ```
2159     /// let mut a = ['a', 'b', 'c', 'd', 'e', 'f'];
2160     /// a[1..5].rotate_left(1);
2161     /// assert_eq!(a, ['a', 'c', 'd', 'e', 'b', 'f']);
2162     /// ```
2163     #[stable(feature = "slice_rotate", since = "1.26.0")]
2164     pub fn rotate_left(&mut self, mid: usize) {
2165         assert!(mid <= self.len());
2166         let k = self.len() - mid;
2167
2168         unsafe {
2169             let p = self.as_mut_ptr();
2170             rotate::ptr_rotate(mid, p.add(mid), k);
2171         }
2172     }
2173
2174     /// Rotates the slice in-place such that the first `self.len() - k`
2175     /// elements of the slice move to the end while the last `k` elements move
2176     /// to the front. After calling `rotate_right`, the element previously at
2177     /// index `self.len() - k` will become the first element in the slice.
2178     ///
2179     /// # Panics
2180     ///
2181     /// This function will panic if `k` is greater than the length of the
2182     /// slice. Note that `k == self.len()` does _not_ panic and is a no-op
2183     /// rotation.
2184     ///
2185     /// # Complexity
2186     ///
2187     /// Takes linear (in `self.len()`) time.
2188     ///
2189     /// # Examples
2190     ///
2191     /// ```
2192     /// let mut a = ['a', 'b', 'c', 'd', 'e', 'f'];
2193     /// a.rotate_right(2);
2194     /// assert_eq!(a, ['e', 'f', 'a', 'b', 'c', 'd']);
2195     /// ```
2196     ///
2197     /// Rotate a subslice:
2198     ///
2199     /// ```
2200     /// let mut a = ['a', 'b', 'c', 'd', 'e', 'f'];
2201     /// a[1..5].rotate_right(1);
2202     /// assert_eq!(a, ['a', 'e', 'b', 'c', 'd', 'f']);
2203     /// ```
2204     #[stable(feature = "slice_rotate", since = "1.26.0")]
2205     pub fn rotate_right(&mut self, k: usize) {
2206         assert!(k <= self.len());
2207         let mid = self.len() - k;
2208
2209         unsafe {
2210             let p = self.as_mut_ptr();
2211             rotate::ptr_rotate(mid, p.add(mid), k);
2212         }
2213     }
2214
2215     /// Fills `self` with elements by cloning `value`.
2216     ///
2217     /// # Examples
2218     ///
2219     /// ```
2220     /// #![feature(slice_fill)]
2221     ///
2222     /// let mut buf = vec![0; 10];
2223     /// buf.fill(1);
2224     /// assert_eq!(buf, vec![1; 10]);
2225     /// ```
2226     #[unstable(feature = "slice_fill", issue = "70758")]
2227     pub fn fill(&mut self, value: T)
2228     where
2229         T: Clone,
2230     {
2231         if let Some((last, elems)) = self.split_last_mut() {
2232             for el in elems {
2233                 el.clone_from(&value);
2234             }
2235
2236             *last = value
2237         }
2238     }
2239
2240     /// Copies the elements from `src` into `self`.
2241     ///
2242     /// The length of `src` must be the same as `self`.
2243     ///
2244     /// If `T` implements `Copy`, it can be more performant to use
2245     /// [`copy_from_slice`].
2246     ///
2247     /// # Panics
2248     ///
2249     /// This function will panic if the two slices have different lengths.
2250     ///
2251     /// # Examples
2252     ///
2253     /// Cloning two elements from a slice into another:
2254     ///
2255     /// ```
2256     /// let src = [1, 2, 3, 4];
2257     /// let mut dst = [0, 0];
2258     ///
2259     /// // Because the slices have to be the same length,
2260     /// // we slice the source slice from four elements
2261     /// // to two. It will panic if we don't do this.
2262     /// dst.clone_from_slice(&src[2..]);
2263     ///
2264     /// assert_eq!(src, [1, 2, 3, 4]);
2265     /// assert_eq!(dst, [3, 4]);
2266     /// ```
2267     ///
2268     /// Rust enforces that there can only be one mutable reference with no
2269     /// immutable references to a particular piece of data in a particular
2270     /// scope. Because of this, attempting to use `clone_from_slice` on a
2271     /// single slice will result in a compile failure:
2272     ///
2273     /// ```compile_fail
2274     /// let mut slice = [1, 2, 3, 4, 5];
2275     ///
2276     /// slice[..2].clone_from_slice(&slice[3..]); // compile fail!
2277     /// ```
2278     ///
2279     /// To work around this, we can use [`split_at_mut`] to create two distinct
2280     /// sub-slices from a slice:
2281     ///
2282     /// ```
2283     /// let mut slice = [1, 2, 3, 4, 5];
2284     ///
2285     /// {
2286     ///     let (left, right) = slice.split_at_mut(2);
2287     ///     left.clone_from_slice(&right[1..]);
2288     /// }
2289     ///
2290     /// assert_eq!(slice, [4, 5, 3, 4, 5]);
2291     /// ```
2292     ///
2293     /// [`copy_from_slice`]: #method.copy_from_slice
2294     /// [`split_at_mut`]: #method.split_at_mut
2295     #[stable(feature = "clone_from_slice", since = "1.7.0")]
2296     pub fn clone_from_slice(&mut self, src: &[T])
2297     where
2298         T: Clone,
2299     {
2300         assert!(self.len() == src.len(), "destination and source slices have different lengths");
2301         // NOTE: We need to explicitly slice them to the same length
2302         // for bounds checking to be elided, and the optimizer will
2303         // generate memcpy for simple cases (for example T = u8).
2304         let len = self.len();
2305         let src = &src[..len];
2306         for i in 0..len {
2307             self[i].clone_from(&src[i]);
2308         }
2309     }
2310
2311     /// Copies all elements from `src` into `self`, using a memcpy.
2312     ///
2313     /// The length of `src` must be the same as `self`.
2314     ///
2315     /// If `T` does not implement `Copy`, use [`clone_from_slice`].
2316     ///
2317     /// # Panics
2318     ///
2319     /// This function will panic if the two slices have different lengths.
2320     ///
2321     /// # Examples
2322     ///
2323     /// Copying two elements from a slice into another:
2324     ///
2325     /// ```
2326     /// let src = [1, 2, 3, 4];
2327     /// let mut dst = [0, 0];
2328     ///
2329     /// // Because the slices have to be the same length,
2330     /// // we slice the source slice from four elements
2331     /// // to two. It will panic if we don't do this.
2332     /// dst.copy_from_slice(&src[2..]);
2333     ///
2334     /// assert_eq!(src, [1, 2, 3, 4]);
2335     /// assert_eq!(dst, [3, 4]);
2336     /// ```
2337     ///
2338     /// Rust enforces that there can only be one mutable reference with no
2339     /// immutable references to a particular piece of data in a particular
2340     /// scope. Because of this, attempting to use `copy_from_slice` on a
2341     /// single slice will result in a compile failure:
2342     ///
2343     /// ```compile_fail
2344     /// let mut slice = [1, 2, 3, 4, 5];
2345     ///
2346     /// slice[..2].copy_from_slice(&slice[3..]); // compile fail!
2347     /// ```
2348     ///
2349     /// To work around this, we can use [`split_at_mut`] to create two distinct
2350     /// sub-slices from a slice:
2351     ///
2352     /// ```
2353     /// let mut slice = [1, 2, 3, 4, 5];
2354     ///
2355     /// {
2356     ///     let (left, right) = slice.split_at_mut(2);
2357     ///     left.copy_from_slice(&right[1..]);
2358     /// }
2359     ///
2360     /// assert_eq!(slice, [4, 5, 3, 4, 5]);
2361     /// ```
2362     ///
2363     /// [`clone_from_slice`]: #method.clone_from_slice
2364     /// [`split_at_mut`]: #method.split_at_mut
2365     #[stable(feature = "copy_from_slice", since = "1.9.0")]
2366     pub fn copy_from_slice(&mut self, src: &[T])
2367     where
2368         T: Copy,
2369     {
2370         assert_eq!(self.len(), src.len(), "destination and source slices have different lengths");
2371         unsafe {
2372             ptr::copy_nonoverlapping(src.as_ptr(), self.as_mut_ptr(), self.len());
2373         }
2374     }
2375
2376     /// Copies elements from one part of the slice to another part of itself,
2377     /// using a memmove.
2378     ///
2379     /// `src` is the range within `self` to copy from. `dest` is the starting
2380     /// index of the range within `self` to copy to, which will have the same
2381     /// length as `src`. The two ranges may overlap. The ends of the two ranges
2382     /// must be less than or equal to `self.len()`.
2383     ///
2384     /// # Panics
2385     ///
2386     /// This function will panic if either range exceeds the end of the slice,
2387     /// or if the end of `src` is before the start.
2388     ///
2389     /// # Examples
2390     ///
2391     /// Copying four bytes within a slice:
2392     ///
2393     /// ```
2394     /// let mut bytes = *b"Hello, World!";
2395     ///
2396     /// bytes.copy_within(1..5, 8);
2397     ///
2398     /// assert_eq!(&bytes, b"Hello, Wello!");
2399     /// ```
2400     #[stable(feature = "copy_within", since = "1.37.0")]
2401     #[track_caller]
2402     pub fn copy_within<R: ops::RangeBounds<usize>>(&mut self, src: R, dest: usize)
2403     where
2404         T: Copy,
2405     {
2406         let src_start = match src.start_bound() {
2407             ops::Bound::Included(&n) => n,
2408             ops::Bound::Excluded(&n) => {
2409                 n.checked_add(1).unwrap_or_else(|| slice_index_overflow_fail())
2410             }
2411             ops::Bound::Unbounded => 0,
2412         };
2413         let src_end = match src.end_bound() {
2414             ops::Bound::Included(&n) => {
2415                 n.checked_add(1).unwrap_or_else(|| slice_index_overflow_fail())
2416             }
2417             ops::Bound::Excluded(&n) => n,
2418             ops::Bound::Unbounded => self.len(),
2419         };
2420         assert!(src_start <= src_end, "src end is before src start");
2421         assert!(src_end <= self.len(), "src is out of bounds");
2422         let count = src_end - src_start;
2423         assert!(dest <= self.len() - count, "dest is out of bounds");
2424         unsafe {
2425             ptr::copy(self.as_ptr().add(src_start), self.as_mut_ptr().add(dest), count);
2426         }
2427     }
2428
2429     /// Swaps all elements in `self` with those in `other`.
2430     ///
2431     /// The length of `other` must be the same as `self`.
2432     ///
2433     /// # Panics
2434     ///
2435     /// This function will panic if the two slices have different lengths.
2436     ///
2437     /// # Example
2438     ///
2439     /// Swapping two elements across slices:
2440     ///
2441     /// ```
2442     /// let mut slice1 = [0, 0];
2443     /// let mut slice2 = [1, 2, 3, 4];
2444     ///
2445     /// slice1.swap_with_slice(&mut slice2[2..]);
2446     ///
2447     /// assert_eq!(slice1, [3, 4]);
2448     /// assert_eq!(slice2, [1, 2, 0, 0]);
2449     /// ```
2450     ///
2451     /// Rust enforces that there can only be one mutable reference to a
2452     /// particular piece of data in a particular scope. Because of this,
2453     /// attempting to use `swap_with_slice` on a single slice will result in
2454     /// a compile failure:
2455     ///
2456     /// ```compile_fail
2457     /// let mut slice = [1, 2, 3, 4, 5];
2458     /// slice[..2].swap_with_slice(&mut slice[3..]); // compile fail!
2459     /// ```
2460     ///
2461     /// To work around this, we can use [`split_at_mut`] to create two distinct
2462     /// mutable sub-slices from a slice:
2463     ///
2464     /// ```
2465     /// let mut slice = [1, 2, 3, 4, 5];
2466     ///
2467     /// {
2468     ///     let (left, right) = slice.split_at_mut(2);
2469     ///     left.swap_with_slice(&mut right[1..]);
2470     /// }
2471     ///
2472     /// assert_eq!(slice, [4, 5, 3, 1, 2]);
2473     /// ```
2474     ///
2475     /// [`split_at_mut`]: #method.split_at_mut
2476     #[stable(feature = "swap_with_slice", since = "1.27.0")]
2477     pub fn swap_with_slice(&mut self, other: &mut [T]) {
2478         assert!(self.len() == other.len(), "destination and source slices have different lengths");
2479         unsafe {
2480             ptr::swap_nonoverlapping(self.as_mut_ptr(), other.as_mut_ptr(), self.len());
2481         }
2482     }
2483
2484     /// Function to calculate lengths of the middle and trailing slice for `align_to{,_mut}`.
2485     fn align_to_offsets<U>(&self) -> (usize, usize) {
2486         // What we gonna do about `rest` is figure out what multiple of `U`s we can put in a
2487         // lowest number of `T`s. And how many `T`s we need for each such "multiple".
2488         //
2489         // Consider for example T=u8 U=u16. Then we can put 1 U in 2 Ts. Simple. Now, consider
2490         // for example a case where size_of::<T> = 16, size_of::<U> = 24. We can put 2 Us in
2491         // place of every 3 Ts in the `rest` slice. A bit more complicated.
2492         //
2493         // Formula to calculate this is:
2494         //
2495         // Us = lcm(size_of::<T>, size_of::<U>) / size_of::<U>
2496         // Ts = lcm(size_of::<T>, size_of::<U>) / size_of::<T>
2497         //
2498         // Expanded and simplified:
2499         //
2500         // Us = size_of::<T> / gcd(size_of::<T>, size_of::<U>)
2501         // Ts = size_of::<U> / gcd(size_of::<T>, size_of::<U>)
2502         //
2503         // Luckily since all this is constant-evaluated... performance here matters not!
2504         #[inline]
2505         fn gcd(a: usize, b: usize) -> usize {
2506             use crate::intrinsics;
2507             // iterative stein’s algorithm
2508             // We should still make this `const fn` (and revert to recursive algorithm if we do)
2509             // because relying on llvm to consteval all this is… well, it makes me uncomfortable.
2510             let (ctz_a, mut ctz_b) = unsafe {
2511                 if a == 0 {
2512                     return b;
2513                 }
2514                 if b == 0 {
2515                     return a;
2516                 }
2517                 (intrinsics::cttz_nonzero(a), intrinsics::cttz_nonzero(b))
2518             };
2519             let k = ctz_a.min(ctz_b);
2520             let mut a = a >> ctz_a;
2521             let mut b = b;
2522             loop {
2523                 // remove all factors of 2 from b
2524                 b >>= ctz_b;
2525                 if a > b {
2526                     mem::swap(&mut a, &mut b);
2527                 }
2528                 b = b - a;
2529                 unsafe {
2530                     if b == 0 {
2531                         break;
2532                     }
2533                     ctz_b = intrinsics::cttz_nonzero(b);
2534                 }
2535             }
2536             a << k
2537         }
2538         let gcd: usize = gcd(mem::size_of::<T>(), mem::size_of::<U>());
2539         let ts: usize = mem::size_of::<U>() / gcd;
2540         let us: usize = mem::size_of::<T>() / gcd;
2541
2542         // Armed with this knowledge, we can find how many `U`s we can fit!
2543         let us_len = self.len() / ts * us;
2544         // And how many `T`s will be in the trailing slice!
2545         let ts_len = self.len() % ts;
2546         (us_len, ts_len)
2547     }
2548
2549     /// Transmute the slice to a slice of another type, ensuring alignment of the types is
2550     /// maintained.
2551     ///
2552     /// This method splits the slice into three distinct slices: prefix, correctly aligned middle
2553     /// slice of a new type, and the suffix slice. The method may make the middle slice the greatest
2554     /// length possible for a given type and input slice, but only your algorithm's performance
2555     /// should depend on that, not its correctness. It is permissible for all of the input data to
2556     /// be returned as the prefix or suffix slice.
2557     ///
2558     /// This method has no purpose when either input element `T` or output element `U` are
2559     /// zero-sized and will return the original slice without splitting anything.
2560     ///
2561     /// # Safety
2562     ///
2563     /// This method is essentially a `transmute` with respect to the elements in the returned
2564     /// middle slice, so all the usual caveats pertaining to `transmute::<T, U>` also apply here.
2565     ///
2566     /// # Examples
2567     ///
2568     /// Basic usage:
2569     ///
2570     /// ```
2571     /// unsafe {
2572     ///     let bytes: [u8; 7] = [1, 2, 3, 4, 5, 6, 7];
2573     ///     let (prefix, shorts, suffix) = bytes.align_to::<u16>();
2574     ///     // less_efficient_algorithm_for_bytes(prefix);
2575     ///     // more_efficient_algorithm_for_aligned_shorts(shorts);
2576     ///     // less_efficient_algorithm_for_bytes(suffix);
2577     /// }
2578     /// ```
2579     #[stable(feature = "slice_align_to", since = "1.30.0")]
2580     pub unsafe fn align_to<U>(&self) -> (&[T], &[U], &[T]) {
2581         // Note that most of this function will be constant-evaluated,
2582         if mem::size_of::<U>() == 0 || mem::size_of::<T>() == 0 {
2583             // handle ZSTs specially, which is – don't handle them at all.
2584             return (self, &[], &[]);
2585         }
2586
2587         // First, find at what point do we split between the first and 2nd slice. Easy with
2588         // ptr.align_offset.
2589         let ptr = self.as_ptr();
2590         let offset = unsafe { crate::ptr::align_offset(ptr, mem::align_of::<U>()) };
2591         if offset > self.len() {
2592             (self, &[], &[])
2593         } else {
2594             let (left, rest) = self.split_at(offset);
2595             let (us_len, ts_len) = rest.align_to_offsets::<U>();
2596             // SAFETY: now `rest` is definitely aligned, so `from_raw_parts` below is okay,
2597             // since the caller guarantees that we can transmute `T` to `U` safely.
2598             unsafe {
2599                 (
2600                     left,
2601                     from_raw_parts(rest.as_ptr() as *const U, us_len),
2602                     from_raw_parts(rest.as_ptr().add(rest.len() - ts_len), ts_len),
2603                 )
2604             }
2605         }
2606     }
2607
2608     /// Transmute the slice to a slice of another type, ensuring alignment of the types is
2609     /// maintained.
2610     ///
2611     /// This method splits the slice into three distinct slices: prefix, correctly aligned middle
2612     /// slice of a new type, and the suffix slice. The method may make the middle slice the greatest
2613     /// length possible for a given type and input slice, but only your algorithm's performance
2614     /// should depend on that, not its correctness. It is permissible for all of the input data to
2615     /// be returned as the prefix or suffix slice.
2616     ///
2617     /// This method has no purpose when either input element `T` or output element `U` are
2618     /// zero-sized and will return the original slice without splitting anything.
2619     ///
2620     /// # Safety
2621     ///
2622     /// This method is essentially a `transmute` with respect to the elements in the returned
2623     /// middle slice, so all the usual caveats pertaining to `transmute::<T, U>` also apply here.
2624     ///
2625     /// # Examples
2626     ///
2627     /// Basic usage:
2628     ///
2629     /// ```
2630     /// unsafe {
2631     ///     let mut bytes: [u8; 7] = [1, 2, 3, 4, 5, 6, 7];
2632     ///     let (prefix, shorts, suffix) = bytes.align_to_mut::<u16>();
2633     ///     // less_efficient_algorithm_for_bytes(prefix);
2634     ///     // more_efficient_algorithm_for_aligned_shorts(shorts);
2635     ///     // less_efficient_algorithm_for_bytes(suffix);
2636     /// }
2637     /// ```
2638     #[stable(feature = "slice_align_to", since = "1.30.0")]
2639     pub unsafe fn align_to_mut<U>(&mut self) -> (&mut [T], &mut [U], &mut [T]) {
2640         // Note that most of this function will be constant-evaluated,
2641         if mem::size_of::<U>() == 0 || mem::size_of::<T>() == 0 {
2642             // handle ZSTs specially, which is – don't handle them at all.
2643             return (self, &mut [], &mut []);
2644         }
2645
2646         // First, find at what point do we split between the first and 2nd slice. Easy with
2647         // ptr.align_offset.
2648         let ptr = self.as_ptr();
2649         let offset = unsafe { crate::ptr::align_offset(ptr, mem::align_of::<U>()) };
2650         if offset > self.len() {
2651             (self, &mut [], &mut [])
2652         } else {
2653             let (left, rest) = self.split_at_mut(offset);
2654             let (us_len, ts_len) = rest.align_to_offsets::<U>();
2655             let rest_len = rest.len();
2656             let mut_ptr = rest.as_mut_ptr();
2657             // We can't use `rest` again after this, that would invalidate its alias `mut_ptr`!
2658             // SAFETY: see comments for `align_to`.
2659             unsafe {
2660                 (
2661                     left,
2662                     from_raw_parts_mut(mut_ptr as *mut U, us_len),
2663                     from_raw_parts_mut(mut_ptr.add(rest_len - ts_len), ts_len),
2664                 )
2665             }
2666         }
2667     }
2668
2669     /// Checks if the elements of this slice are sorted.
2670     ///
2671     /// That is, for each element `a` and its following element `b`, `a <= b` must hold. If the
2672     /// slice yields exactly zero or one element, `true` is returned.
2673     ///
2674     /// Note that if `Self::Item` is only `PartialOrd`, but not `Ord`, the above definition
2675     /// implies that this function returns `false` if any two consecutive items are not
2676     /// comparable.
2677     ///
2678     /// # Examples
2679     ///
2680     /// ```
2681     /// #![feature(is_sorted)]
2682     /// let empty: [i32; 0] = [];
2683     ///
2684     /// assert!([1, 2, 2, 9].is_sorted());
2685     /// assert!(![1, 3, 2, 4].is_sorted());
2686     /// assert!([0].is_sorted());
2687     /// assert!(empty.is_sorted());
2688     /// assert!(![0.0, 1.0, f32::NAN].is_sorted());
2689     /// ```
2690     #[inline]
2691     #[unstable(feature = "is_sorted", reason = "new API", issue = "53485")]
2692     pub fn is_sorted(&self) -> bool
2693     where
2694         T: PartialOrd,
2695     {
2696         self.is_sorted_by(|a, b| a.partial_cmp(b))
2697     }
2698
2699     /// Checks if the elements of this slice are sorted using the given comparator function.
2700     ///
2701     /// Instead of using `PartialOrd::partial_cmp`, this function uses the given `compare`
2702     /// function to determine the ordering of two elements. Apart from that, it's equivalent to
2703     /// [`is_sorted`]; see its documentation for more information.
2704     ///
2705     /// [`is_sorted`]: #method.is_sorted
2706     #[unstable(feature = "is_sorted", reason = "new API", issue = "53485")]
2707     pub fn is_sorted_by<F>(&self, mut compare: F) -> bool
2708     where
2709         F: FnMut(&T, &T) -> Option<Ordering>,
2710     {
2711         self.iter().is_sorted_by(|a, b| compare(*a, *b))
2712     }
2713
2714     /// Checks if the elements of this slice are sorted using the given key extraction function.
2715     ///
2716     /// Instead of comparing the slice's elements directly, this function compares the keys of the
2717     /// elements, as determined by `f`. Apart from that, it's equivalent to [`is_sorted`]; see its
2718     /// documentation for more information.
2719     ///
2720     /// [`is_sorted`]: #method.is_sorted
2721     ///
2722     /// # Examples
2723     ///
2724     /// ```
2725     /// #![feature(is_sorted)]
2726     ///
2727     /// assert!(["c", "bb", "aaa"].is_sorted_by_key(|s| s.len()));
2728     /// assert!(![-2i32, -1, 0, 3].is_sorted_by_key(|n| n.abs()));
2729     /// ```
2730     #[inline]
2731     #[unstable(feature = "is_sorted", reason = "new API", issue = "53485")]
2732     pub fn is_sorted_by_key<F, K>(&self, f: F) -> bool
2733     where
2734         F: FnMut(&T) -> K,
2735         K: PartialOrd,
2736     {
2737         self.iter().is_sorted_by_key(f)
2738     }
2739
2740     /// Returns the index of the partition point according to the given predicate
2741     /// (the index of the first element of the second partition).
2742     ///
2743     /// The slice is assumed to be partitioned according to the given predicate.
2744     /// This means that all elements for which the predicate returns true are at the start of the slice
2745     /// and all elements for which the predicate returns false are at the end.
2746     /// For example, [7, 15, 3, 5, 4, 12, 6] is a partitioned under the predicate x % 2 != 0
2747     /// (all odd numbers are at the start, all even at the end).
2748     ///
2749     /// If this slice is not partitioned, the returned result is unspecified and meaningless,
2750     /// as this method performs a kind of binary search.
2751     ///
2752     /// # Examples
2753     ///
2754     /// ```
2755     /// #![feature(partition_point)]
2756     ///
2757     /// let v = [1, 2, 3, 3, 5, 6, 7];
2758     /// let i = v.partition_point(|&x| x < 5);
2759     ///
2760     /// assert_eq!(i, 4);
2761     /// assert!(v[..i].iter().all(|&x| x < 5));
2762     /// assert!(v[i..].iter().all(|&x| !(x < 5)));
2763     /// ```
2764     #[unstable(feature = "partition_point", reason = "new API", issue = "73831")]
2765     pub fn partition_point<P>(&self, mut pred: P) -> usize
2766     where
2767         P: FnMut(&T) -> bool,
2768     {
2769         let mut left = 0;
2770         let mut right = self.len();
2771
2772         while left != right {
2773             let mid = left + (right - left) / 2;
2774             // SAFETY:
2775             // When left < right, left <= mid < right.
2776             // Therefore left always increases and right always decreases,
2777             // and eigher of them is selected.
2778             // In both cases left <= right is satisfied.
2779             // Therefore if left < right in a step,
2780             // left <= right is satisfied in the next step.
2781             // Therefore as long as left != right, 0 <= left < right <= len is satisfied
2782             // and if this case 0 <= mid < len is satisfied too.
2783             let value = unsafe { self.get_unchecked(mid) };
2784             if pred(value) {
2785                 left = mid + 1;
2786             } else {
2787                 right = mid;
2788             }
2789         }
2790
2791         left
2792     }
2793 }
2794
2795 #[lang = "slice_u8"]
2796 #[cfg(not(test))]
2797 impl [u8] {
2798     /// Checks if all bytes in this slice are within the ASCII range.
2799     #[stable(feature = "ascii_methods_on_intrinsics", since = "1.23.0")]
2800     #[inline]
2801     pub fn is_ascii(&self) -> bool {
2802         is_ascii(self)
2803     }
2804
2805     /// Checks that two slices are an ASCII case-insensitive match.
2806     ///
2807     /// Same as `to_ascii_lowercase(a) == to_ascii_lowercase(b)`,
2808     /// but without allocating and copying temporaries.
2809     #[stable(feature = "ascii_methods_on_intrinsics", since = "1.23.0")]
2810     #[inline]
2811     pub fn eq_ignore_ascii_case(&self, other: &[u8]) -> bool {
2812         self.len() == other.len() && self.iter().zip(other).all(|(a, b)| a.eq_ignore_ascii_case(b))
2813     }
2814
2815     /// Converts this slice to its ASCII upper case equivalent in-place.
2816     ///
2817     /// ASCII letters 'a' to 'z' are mapped to 'A' to 'Z',
2818     /// but non-ASCII letters are unchanged.
2819     ///
2820     /// To return a new uppercased value without modifying the existing one, use
2821     /// [`to_ascii_uppercase`].
2822     ///
2823     /// [`to_ascii_uppercase`]: #method.to_ascii_uppercase
2824     #[stable(feature = "ascii_methods_on_intrinsics", since = "1.23.0")]
2825     #[inline]
2826     pub fn make_ascii_uppercase(&mut self) {
2827         for byte in self {
2828             byte.make_ascii_uppercase();
2829         }
2830     }
2831
2832     /// Converts this slice to its ASCII lower case equivalent in-place.
2833     ///
2834     /// ASCII letters 'A' to 'Z' are mapped to 'a' to 'z',
2835     /// but non-ASCII letters are unchanged.
2836     ///
2837     /// To return a new lowercased value without modifying the existing one, use
2838     /// [`to_ascii_lowercase`].
2839     ///
2840     /// [`to_ascii_lowercase`]: #method.to_ascii_lowercase
2841     #[stable(feature = "ascii_methods_on_intrinsics", since = "1.23.0")]
2842     #[inline]
2843     pub fn make_ascii_lowercase(&mut self) {
2844         for byte in self {
2845             byte.make_ascii_lowercase();
2846         }
2847     }
2848 }
2849
2850 /// Returns `true` if any byte in the word `v` is nonascii (>= 128). Snarfed
2851 /// from `../str/mod.rs`, which does something similar for utf8 validation.
2852 #[inline]
2853 fn contains_nonascii(v: usize) -> bool {
2854     const NONASCII_MASK: usize = 0x80808080_80808080u64 as usize;
2855     (NONASCII_MASK & v) != 0
2856 }
2857
2858 /// Optimized ASCII test that will use usize-at-a-time operations instead of
2859 /// byte-at-a-time operations (when possible).
2860 ///
2861 /// The algorithm we use here is pretty simple. If `s` is too short, we just
2862 /// check each byte and be done with it. Otherwise:
2863 ///
2864 /// - Read the first word with an unaligned load.
2865 /// - Align the pointer, read subsequent words until end with aligned loads.
2866 /// - If there's a tail, the last `usize` from `s` with an unaligned load.
2867 ///
2868 /// If any of these loads produces something for which `contains_nonascii`
2869 /// (above) returns true, then we know the answer is false.
2870 #[inline]
2871 fn is_ascii(s: &[u8]) -> bool {
2872     const USIZE_SIZE: usize = mem::size_of::<usize>();
2873
2874     let len = s.len();
2875     let align_offset = s.as_ptr().align_offset(USIZE_SIZE);
2876
2877     // If we wouldn't gain anything from the word-at-a-time implementation, fall
2878     // back to a scalar loop.
2879     //
2880     // We also do this for architectures where `size_of::<usize>()` isn't
2881     // sufficient alignment for `usize`, because it's a weird edge case.
2882     if len < USIZE_SIZE || len < align_offset || USIZE_SIZE < mem::align_of::<usize>() {
2883         return s.iter().all(|b| b.is_ascii());
2884     }
2885
2886     // We always read the first word unaligned, which means `align_offset` is
2887     // 0, we'd read the same value again for the aligned read.
2888     let offset_to_aligned = if align_offset == 0 { USIZE_SIZE } else { align_offset };
2889
2890     let start = s.as_ptr();
2891     // SAFETY: We verify `len < USIZE_SIZE` above.
2892     let first_word = unsafe { (start as *const usize).read_unaligned() };
2893
2894     if contains_nonascii(first_word) {
2895         return false;
2896     }
2897     // We checked this above, somewhat implicitly. Note that `offset_to_aligned`
2898     // is either `align_offset` or `USIZE_SIZE`, both of are explicitly checked
2899     // above.
2900     debug_assert!(offset_to_aligned <= len);
2901
2902     // word_ptr is the (properly aligned) usize ptr we use to read the middle chunk of the slice.
2903     let mut word_ptr = unsafe { start.add(offset_to_aligned) as *const usize };
2904
2905     // `byte_pos` is the byte index of `word_ptr`, used for loop end checks.
2906     let mut byte_pos = offset_to_aligned;
2907
2908     // Paranoia check about alignment, since we're about to do a bunch of
2909     // unaligned loads. In practice this should be impossible barring a bug in
2910     // `align_offset` though.
2911     debug_assert_eq!((word_ptr as usize) % mem::align_of::<usize>(), 0);
2912
2913     while byte_pos <= len - USIZE_SIZE {
2914         debug_assert!(
2915             // Sanity check that the read is in bounds
2916             (word_ptr as usize + USIZE_SIZE) <= (start.wrapping_add(len) as usize) &&
2917             // And that our assumptions about `byte_pos` hold.
2918             (word_ptr as usize) - (start as usize) == byte_pos
2919         );
2920
2921         // Safety: We know `word_ptr` is properly aligned (because of
2922         // `align_offset`), and we know that we have enough bytes between `word_ptr` and the end
2923         let word = unsafe { word_ptr.read() };
2924         if contains_nonascii(word) {
2925             return false;
2926         }
2927
2928         byte_pos += USIZE_SIZE;
2929         // SAFETY: We know that `byte_pos <= len - USIZE_SIZE`, which means that
2930         // after this `add`, `word_ptr` will be at most one-past-the-end.
2931         word_ptr = unsafe { word_ptr.add(1) };
2932     }
2933
2934     // If we have anything left over, it should be at-most 1 usize worth of bytes,
2935     // which we check with a read_unaligned.
2936     if byte_pos == len {
2937         return true;
2938     }
2939
2940     // Sanity check to ensure there really is only one `usize` left. This should
2941     // be guaranteed by our loop condition.
2942     debug_assert!(byte_pos < len && len - byte_pos < USIZE_SIZE);
2943
2944     // SAFETY: This relies on `len >= USIZE_SIZE`, which we check at the start.
2945     let last_word = unsafe { (start.add(len - USIZE_SIZE) as *const usize).read_unaligned() };
2946
2947     !contains_nonascii(last_word)
2948 }
2949
2950 #[stable(feature = "rust1", since = "1.0.0")]
2951 impl<T, I> ops::Index<I> for [T]
2952 where
2953     I: SliceIndex<[T]>,
2954 {
2955     type Output = I::Output;
2956
2957     #[inline]
2958     fn index(&self, index: I) -> &I::Output {
2959         index.index(self)
2960     }
2961 }
2962
2963 #[stable(feature = "rust1", since = "1.0.0")]
2964 impl<T, I> ops::IndexMut<I> for [T]
2965 where
2966     I: SliceIndex<[T]>,
2967 {
2968     #[inline]
2969     fn index_mut(&mut self, index: I) -> &mut I::Output {
2970         index.index_mut(self)
2971     }
2972 }
2973
2974 #[inline(never)]
2975 #[cold]
2976 #[track_caller]
2977 fn slice_index_len_fail(index: usize, len: usize) -> ! {
2978     panic!("index {} out of range for slice of length {}", index, len);
2979 }
2980
2981 #[inline(never)]
2982 #[cold]
2983 #[track_caller]
2984 fn slice_index_order_fail(index: usize, end: usize) -> ! {
2985     panic!("slice index starts at {} but ends at {}", index, end);
2986 }
2987
2988 #[inline(never)]
2989 #[cold]
2990 #[track_caller]
2991 fn slice_index_overflow_fail() -> ! {
2992     panic!("attempted to index slice up to maximum usize");
2993 }
2994
2995 mod private_slice_index {
2996     use super::ops;
2997     #[stable(feature = "slice_get_slice", since = "1.28.0")]
2998     pub trait Sealed {}
2999
3000     #[stable(feature = "slice_get_slice", since = "1.28.0")]
3001     impl Sealed for usize {}
3002     #[stable(feature = "slice_get_slice", since = "1.28.0")]
3003     impl Sealed for ops::Range<usize> {}
3004     #[stable(feature = "slice_get_slice", since = "1.28.0")]
3005     impl Sealed for ops::RangeTo<usize> {}
3006     #[stable(feature = "slice_get_slice", since = "1.28.0")]
3007     impl Sealed for ops::RangeFrom<usize> {}
3008     #[stable(feature = "slice_get_slice", since = "1.28.0")]
3009     impl Sealed for ops::RangeFull {}
3010     #[stable(feature = "slice_get_slice", since = "1.28.0")]
3011     impl Sealed for ops::RangeInclusive<usize> {}
3012     #[stable(feature = "slice_get_slice", since = "1.28.0")]
3013     impl Sealed for ops::RangeToInclusive<usize> {}
3014 }
3015
3016 /// A helper trait used for indexing operations.
3017 ///
3018 /// Implementations of this trait have to promise that if the argument
3019 /// to `get_(mut_)unchecked` is a safe reference, then so is the result.
3020 #[stable(feature = "slice_get_slice", since = "1.28.0")]
3021 #[rustc_on_unimplemented(
3022     on(T = "str", label = "string indices are ranges of `usize`",),
3023     on(
3024         all(any(T = "str", T = "&str", T = "std::string::String"), _Self = "{integer}"),
3025         note = "you can use `.chars().nth()` or `.bytes().nth()`
3026 see chapter in The Book <https://doc.rust-lang.org/book/ch08-02-strings.html#indexing-into-strings>"
3027     ),
3028     message = "the type `{T}` cannot be indexed by `{Self}`",
3029     label = "slice indices are of type `usize` or ranges of `usize`"
3030 )]
3031 pub unsafe trait SliceIndex<T: ?Sized>: private_slice_index::Sealed {
3032     /// The output type returned by methods.
3033     #[stable(feature = "slice_get_slice", since = "1.28.0")]
3034     type Output: ?Sized;
3035
3036     /// Returns a shared reference to the output at this location, if in
3037     /// bounds.
3038     #[unstable(feature = "slice_index_methods", issue = "none")]
3039     fn get(self, slice: &T) -> Option<&Self::Output>;
3040
3041     /// Returns a mutable reference to the output at this location, if in
3042     /// bounds.
3043     #[unstable(feature = "slice_index_methods", issue = "none")]
3044     fn get_mut(self, slice: &mut T) -> Option<&mut Self::Output>;
3045
3046     /// Returns a shared reference to the output at this location, without
3047     /// performing any bounds checking.
3048     /// Calling this method with an out-of-bounds index or a dangling `slice` pointer
3049     /// is *[undefined behavior]* even if the resulting reference is not used.
3050     ///
3051     /// [undefined behavior]: ../../reference/behavior-considered-undefined.html
3052     #[unstable(feature = "slice_index_methods", issue = "none")]
3053     unsafe fn get_unchecked(self, slice: *const T) -> *const Self::Output;
3054
3055     /// Returns a mutable reference to the output at this location, without
3056     /// performing any bounds checking.
3057     /// Calling this method with an out-of-bounds index or a dangling `slice` pointer
3058     /// is *[undefined behavior]* even if the resulting reference is not used.
3059     ///
3060     /// [undefined behavior]: ../../reference/behavior-considered-undefined.html
3061     #[unstable(feature = "slice_index_methods", issue = "none")]
3062     unsafe fn get_unchecked_mut(self, slice: *mut T) -> *mut Self::Output;
3063
3064     /// Returns a shared reference to the output at this location, panicking
3065     /// if out of bounds.
3066     #[unstable(feature = "slice_index_methods", issue = "none")]
3067     #[track_caller]
3068     fn index(self, slice: &T) -> &Self::Output;
3069
3070     /// Returns a mutable reference to the output at this location, panicking
3071     /// if out of bounds.
3072     #[unstable(feature = "slice_index_methods", issue = "none")]
3073     #[track_caller]
3074     fn index_mut(self, slice: &mut T) -> &mut Self::Output;
3075 }
3076
3077 #[stable(feature = "slice_get_slice_impls", since = "1.15.0")]
3078 unsafe impl<T> SliceIndex<[T]> for usize {
3079     type Output = T;
3080
3081     #[inline]
3082     fn get(self, slice: &[T]) -> Option<&T> {
3083         if self < slice.len() { unsafe { Some(&*self.get_unchecked(slice)) } } else { None }
3084     }
3085
3086     #[inline]
3087     fn get_mut(self, slice: &mut [T]) -> Option<&mut T> {
3088         if self < slice.len() { unsafe { Some(&mut *self.get_unchecked_mut(slice)) } } else { None }
3089     }
3090
3091     #[inline]
3092     unsafe fn get_unchecked(self, slice: *const [T]) -> *const T {
3093         // SAFETY: the caller guarantees that `slice` is not dangling, so it
3094         // cannot be longer than `isize::MAX`. They also guarantee that
3095         // `self` is in bounds of `slice` so `self` cannot overflow an `isize`,
3096         // so the call to `add` is safe.
3097         unsafe { slice.as_ptr().add(self) }
3098     }
3099
3100     #[inline]
3101     unsafe fn get_unchecked_mut(self, slice: *mut [T]) -> *mut T {
3102         // SAFETY: see comments for `get_unchecked` above.
3103         unsafe { slice.as_mut_ptr().add(self) }
3104     }
3105
3106     #[inline]
3107     fn index(self, slice: &[T]) -> &T {
3108         // N.B., use intrinsic indexing
3109         &(*slice)[self]
3110     }
3111
3112     #[inline]
3113     fn index_mut(self, slice: &mut [T]) -> &mut T {
3114         // N.B., use intrinsic indexing
3115         &mut (*slice)[self]
3116     }
3117 }
3118
3119 #[stable(feature = "slice_get_slice_impls", since = "1.15.0")]
3120 unsafe impl<T> SliceIndex<[T]> for ops::Range<usize> {
3121     type Output = [T];
3122
3123     #[inline]
3124     fn get(self, slice: &[T]) -> Option<&[T]> {
3125         if self.start > self.end || self.end > slice.len() {
3126             None
3127         } else {
3128             unsafe { Some(&*self.get_unchecked(slice)) }
3129         }
3130     }
3131
3132     #[inline]
3133     fn get_mut(self, slice: &mut [T]) -> Option<&mut [T]> {
3134         if self.start > self.end || self.end > slice.len() {
3135             None
3136         } else {
3137             unsafe { Some(&mut *self.get_unchecked_mut(slice)) }
3138         }
3139     }
3140
3141     #[inline]
3142     unsafe fn get_unchecked(self, slice: *const [T]) -> *const [T] {
3143         // SAFETY: the caller guarantees that `slice` is not dangling, so it
3144         // cannot be longer than `isize::MAX`. They also guarantee that
3145         // `self` is in bounds of `slice` so `self` cannot overflow an `isize`,
3146         // so the call to `add` is safe.
3147         unsafe { ptr::slice_from_raw_parts(slice.as_ptr().add(self.start), self.end - self.start) }
3148     }
3149
3150     #[inline]
3151     unsafe fn get_unchecked_mut(self, slice: *mut [T]) -> *mut [T] {
3152         // SAFETY: see comments for `get_unchecked` above.
3153         unsafe {
3154             ptr::slice_from_raw_parts_mut(slice.as_mut_ptr().add(self.start), self.end - self.start)
3155         }
3156     }
3157
3158     #[inline]
3159     fn index(self, slice: &[T]) -> &[T] {
3160         if self.start > self.end {
3161             slice_index_order_fail(self.start, self.end);
3162         } else if self.end > slice.len() {
3163             slice_index_len_fail(self.end, slice.len());
3164         }
3165         unsafe { &*self.get_unchecked(slice) }
3166     }
3167
3168     #[inline]
3169     fn index_mut(self, slice: &mut [T]) -> &mut [T] {
3170         if self.start > self.end {
3171             slice_index_order_fail(self.start, self.end);
3172         } else if self.end > slice.len() {
3173             slice_index_len_fail(self.end, slice.len());
3174         }
3175         unsafe { &mut *self.get_unchecked_mut(slice) }
3176     }
3177 }
3178
3179 #[stable(feature = "slice_get_slice_impls", since = "1.15.0")]
3180 unsafe impl<T> SliceIndex<[T]> for ops::RangeTo<usize> {
3181     type Output = [T];
3182
3183     #[inline]
3184     fn get(self, slice: &[T]) -> Option<&[T]> {
3185         (0..self.end).get(slice)
3186     }
3187
3188     #[inline]
3189     fn get_mut(self, slice: &mut [T]) -> Option<&mut [T]> {
3190         (0..self.end).get_mut(slice)
3191     }
3192
3193     #[inline]
3194     unsafe fn get_unchecked(self, slice: *const [T]) -> *const [T] {
3195         // SAFETY: the caller has to uphold the safety contract for `get_unchecked`.
3196         unsafe { (0..self.end).get_unchecked(slice) }
3197     }
3198
3199     #[inline]
3200     unsafe fn get_unchecked_mut(self, slice: *mut [T]) -> *mut [T] {
3201         // SAFETY: the caller has to uphold the safety contract for `get_unchecked_mut`.
3202         unsafe { (0..self.end).get_unchecked_mut(slice) }
3203     }
3204
3205     #[inline]
3206     fn index(self, slice: &[T]) -> &[T] {
3207         (0..self.end).index(slice)
3208     }
3209
3210     #[inline]
3211     fn index_mut(self, slice: &mut [T]) -> &mut [T] {
3212         (0..self.end).index_mut(slice)
3213     }
3214 }
3215
3216 #[stable(feature = "slice_get_slice_impls", since = "1.15.0")]
3217 unsafe impl<T> SliceIndex<[T]> for ops::RangeFrom<usize> {
3218     type Output = [T];
3219
3220     #[inline]
3221     fn get(self, slice: &[T]) -> Option<&[T]> {
3222         (self.start..slice.len()).get(slice)
3223     }
3224
3225     #[inline]
3226     fn get_mut(self, slice: &mut [T]) -> Option<&mut [T]> {
3227         (self.start..slice.len()).get_mut(slice)
3228     }
3229
3230     #[inline]
3231     unsafe fn get_unchecked(self, slice: *const [T]) -> *const [T] {
3232         // SAFETY: the caller has to uphold the safety contract for `get_unchecked`.
3233         unsafe { (self.start..slice.len()).get_unchecked(slice) }
3234     }
3235
3236     #[inline]
3237     unsafe fn get_unchecked_mut(self, slice: *mut [T]) -> *mut [T] {
3238         // SAFETY: the caller has to uphold the safety contract for `get_unchecked_mut`.
3239         unsafe { (self.start..slice.len()).get_unchecked_mut(slice) }
3240     }
3241
3242     #[inline]
3243     fn index(self, slice: &[T]) -> &[T] {
3244         (self.start..slice.len()).index(slice)
3245     }
3246
3247     #[inline]
3248     fn index_mut(self, slice: &mut [T]) -> &mut [T] {
3249         (self.start..slice.len()).index_mut(slice)
3250     }
3251 }
3252
3253 #[stable(feature = "slice_get_slice_impls", since = "1.15.0")]
3254 unsafe impl<T> SliceIndex<[T]> for ops::RangeFull {
3255     type Output = [T];
3256
3257     #[inline]
3258     fn get(self, slice: &[T]) -> Option<&[T]> {
3259         Some(slice)
3260     }
3261
3262     #[inline]
3263     fn get_mut(self, slice: &mut [T]) -> Option<&mut [T]> {
3264         Some(slice)
3265     }
3266
3267     #[inline]
3268     unsafe fn get_unchecked(self, slice: *const [T]) -> *const [T] {
3269         slice
3270     }
3271
3272     #[inline]
3273     unsafe fn get_unchecked_mut(self, slice: *mut [T]) -> *mut [T] {
3274         slice
3275     }
3276
3277     #[inline]
3278     fn index(self, slice: &[T]) -> &[T] {
3279         slice
3280     }
3281
3282     #[inline]
3283     fn index_mut(self, slice: &mut [T]) -> &mut [T] {
3284         slice
3285     }
3286 }
3287
3288 #[stable(feature = "inclusive_range", since = "1.26.0")]
3289 unsafe impl<T> SliceIndex<[T]> for ops::RangeInclusive<usize> {
3290     type Output = [T];
3291
3292     #[inline]
3293     fn get(self, slice: &[T]) -> Option<&[T]> {
3294         if *self.end() == usize::MAX { None } else { (*self.start()..self.end() + 1).get(slice) }
3295     }
3296
3297     #[inline]
3298     fn get_mut(self, slice: &mut [T]) -> Option<&mut [T]> {
3299         if *self.end() == usize::MAX {
3300             None
3301         } else {
3302             (*self.start()..self.end() + 1).get_mut(slice)
3303         }
3304     }
3305
3306     #[inline]
3307     unsafe fn get_unchecked(self, slice: *const [T]) -> *const [T] {
3308         // SAFETY: the caller has to uphold the safety contract for `get_unchecked`.
3309         unsafe { (*self.start()..self.end() + 1).get_unchecked(slice) }
3310     }
3311
3312     #[inline]
3313     unsafe fn get_unchecked_mut(self, slice: *mut [T]) -> *mut [T] {
3314         // SAFETY: the caller has to uphold the safety contract for `get_unchecked_mut`.
3315         unsafe { (*self.start()..self.end() + 1).get_unchecked_mut(slice) }
3316     }
3317
3318     #[inline]
3319     fn index(self, slice: &[T]) -> &[T] {
3320         if *self.end() == usize::MAX {
3321             slice_index_overflow_fail();
3322         }
3323         (*self.start()..self.end() + 1).index(slice)
3324     }
3325
3326     #[inline]
3327     fn index_mut(self, slice: &mut [T]) -> &mut [T] {
3328         if *self.end() == usize::MAX {
3329             slice_index_overflow_fail();
3330         }
3331         (*self.start()..self.end() + 1).index_mut(slice)
3332     }
3333 }
3334
3335 #[stable(feature = "inclusive_range", since = "1.26.0")]
3336 unsafe impl<T> SliceIndex<[T]> for ops::RangeToInclusive<usize> {
3337     type Output = [T];
3338
3339     #[inline]
3340     fn get(self, slice: &[T]) -> Option<&[T]> {
3341         (0..=self.end).get(slice)
3342     }
3343
3344     #[inline]
3345     fn get_mut(self, slice: &mut [T]) -> Option<&mut [T]> {
3346         (0..=self.end).get_mut(slice)
3347     }
3348
3349     #[inline]
3350     unsafe fn get_unchecked(self, slice: *const [T]) -> *const [T] {
3351         // SAFETY: the caller has to uphold the safety contract for `get_unchecked`.
3352         unsafe { (0..=self.end).get_unchecked(slice) }
3353     }
3354
3355     #[inline]
3356     unsafe fn get_unchecked_mut(self, slice: *mut [T]) -> *mut [T] {
3357         // SAFETY: the caller has to uphold the safety contract for `get_unchecked_mut`.
3358         unsafe { (0..=self.end).get_unchecked_mut(slice) }
3359     }
3360
3361     #[inline]
3362     fn index(self, slice: &[T]) -> &[T] {
3363         (0..=self.end).index(slice)
3364     }
3365
3366     #[inline]
3367     fn index_mut(self, slice: &mut [T]) -> &mut [T] {
3368         (0..=self.end).index_mut(slice)
3369     }
3370 }
3371
3372 ////////////////////////////////////////////////////////////////////////////////
3373 // Common traits
3374 ////////////////////////////////////////////////////////////////////////////////
3375
3376 #[stable(feature = "rust1", since = "1.0.0")]
3377 impl<T> Default for &[T] {
3378     /// Creates an empty slice.
3379     fn default() -> Self {
3380         &[]
3381     }
3382 }
3383
3384 #[stable(feature = "mut_slice_default", since = "1.5.0")]
3385 impl<T> Default for &mut [T] {
3386     /// Creates a mutable empty slice.
3387     fn default() -> Self {
3388         &mut []
3389     }
3390 }
3391
3392 //
3393 // Iterators
3394 //
3395
3396 #[stable(feature = "rust1", since = "1.0.0")]
3397 impl<'a, T> IntoIterator for &'a [T] {
3398     type Item = &'a T;
3399     type IntoIter = Iter<'a, T>;
3400
3401     fn into_iter(self) -> Iter<'a, T> {
3402         self.iter()
3403     }
3404 }
3405
3406 #[stable(feature = "rust1", since = "1.0.0")]
3407 impl<'a, T> IntoIterator for &'a mut [T] {
3408     type Item = &'a mut T;
3409     type IntoIter = IterMut<'a, T>;
3410
3411     fn into_iter(self) -> IterMut<'a, T> {
3412         self.iter_mut()
3413     }
3414 }
3415
3416 // Macro helper functions
3417 #[inline(always)]
3418 fn size_from_ptr<T>(_: *const T) -> usize {
3419     mem::size_of::<T>()
3420 }
3421
3422 // Inlining is_empty and len makes a huge performance difference
3423 macro_rules! is_empty {
3424     // The way we encode the length of a ZST iterator, this works both for ZST
3425     // and non-ZST.
3426     ($self: ident) => {
3427         $self.ptr.as_ptr() as *const T == $self.end
3428     };
3429 }
3430
3431 // To get rid of some bounds checks (see `position`), we compute the length in a somewhat
3432 // unexpected way. (Tested by `codegen/slice-position-bounds-check`.)
3433 macro_rules! len {
3434     ($self: ident) => {{
3435         #![allow(unused_unsafe)] // we're sometimes used within an unsafe block
3436
3437         let start = $self.ptr;
3438         let size = size_from_ptr(start.as_ptr());
3439         if size == 0 {
3440             // This _cannot_ use `unchecked_sub` because we depend on wrapping
3441             // to represent the length of long ZST slice iterators.
3442             ($self.end as usize).wrapping_sub(start.as_ptr() as usize)
3443         } else {
3444             // We know that `start <= end`, so can do better than `offset_from`,
3445             // which needs to deal in signed.  By setting appropriate flags here
3446             // we can tell LLVM this, which helps it remove bounds checks.
3447             // SAFETY: By the type invariant, `start <= end`
3448             let diff = unsafe { unchecked_sub($self.end as usize, start.as_ptr() as usize) };
3449             // By also telling LLVM that the pointers are apart by an exact
3450             // multiple of the type size, it can optimize `len() == 0` down to
3451             // `start == end` instead of `(end - start) < size`.
3452             // SAFETY: By the type invariant, the pointers are aligned so the
3453             //         distance between them must be a multiple of pointee size
3454             unsafe { exact_div(diff, size) }
3455         }
3456     }};
3457 }
3458
3459 // The shared definition of the `Iter` and `IterMut` iterators
3460 macro_rules! iterator {
3461     (
3462         struct $name:ident -> $ptr:ty,
3463         $elem:ty,
3464         $raw_mut:tt,
3465         {$( $mut_:tt )*},
3466         {$($extra:tt)*}
3467     ) => {
3468         // Returns the first element and moves the start of the iterator forwards by 1.
3469         // Greatly improves performance compared to an inlined function. The iterator
3470         // must not be empty.
3471         macro_rules! next_unchecked {
3472             ($self: ident) => {& $( $mut_ )* *$self.post_inc_start(1)}
3473         }
3474
3475         // Returns the last element and moves the end of the iterator backwards by 1.
3476         // Greatly improves performance compared to an inlined function. The iterator
3477         // must not be empty.
3478         macro_rules! next_back_unchecked {
3479             ($self: ident) => {& $( $mut_ )* *$self.pre_dec_end(1)}
3480         }
3481
3482         // Shrinks the iterator when T is a ZST, by moving the end of the iterator
3483         // backwards by `n`. `n` must not exceed `self.len()`.
3484         macro_rules! zst_shrink {
3485             ($self: ident, $n: ident) => {
3486                 $self.end = ($self.end as * $raw_mut u8).wrapping_offset(-$n) as * $raw_mut T;
3487             }
3488         }
3489
3490         impl<'a, T> $name<'a, T> {
3491             // Helper function for creating a slice from the iterator.
3492             #[inline(always)]
3493             fn make_slice(&self) -> &'a [T] {
3494                 unsafe { from_raw_parts(self.ptr.as_ptr(), len!(self)) }
3495             }
3496
3497             // Helper function for moving the start of the iterator forwards by `offset` elements,
3498             // returning the old start.
3499             // Unsafe because the offset must not exceed `self.len()`.
3500             #[inline(always)]
3501             unsafe fn post_inc_start(&mut self, offset: isize) -> * $raw_mut T {
3502                 if mem::size_of::<T>() == 0 {
3503                     zst_shrink!(self, offset);
3504                     self.ptr.as_ptr()
3505                 } else {
3506                     let old = self.ptr.as_ptr();
3507                     // SAFETY: the caller guarantees that `offset` doesn't exceed `self.len()`,
3508                     // so this new pointer is inside `self` and thus guaranteed to be non-null.
3509                     self.ptr = unsafe { NonNull::new_unchecked(self.ptr.as_ptr().offset(offset)) };
3510                     old
3511                 }
3512             }
3513
3514             // Helper function for moving the end of the iterator backwards by `offset` elements,
3515             // returning the new end.
3516             // Unsafe because the offset must not exceed `self.len()`.
3517             #[inline(always)]
3518             unsafe fn pre_dec_end(&mut self, offset: isize) -> * $raw_mut T {
3519                 if mem::size_of::<T>() == 0 {
3520                     zst_shrink!(self, offset);
3521                     self.ptr.as_ptr()
3522                 } else {
3523                     // SAFETY: the caller guarantees that `offset` doesn't exceed `self.len()`,
3524                     // which is guaranteed to not overflow an `isize`. Also, the resulting pointer
3525                     // is in bounds of `slice`, which fulfills the other requirements for `offset`.
3526                     self.end = unsafe { self.end.offset(-offset) };
3527                     self.end
3528                 }
3529             }
3530         }
3531
3532         #[stable(feature = "rust1", since = "1.0.0")]
3533         impl<T> ExactSizeIterator for $name<'_, T> {
3534             #[inline(always)]
3535             fn len(&self) -> usize {
3536                 len!(self)
3537             }
3538
3539             #[inline(always)]
3540             fn is_empty(&self) -> bool {
3541                 is_empty!(self)
3542             }
3543         }
3544
3545         #[stable(feature = "rust1", since = "1.0.0")]
3546         impl<'a, T> Iterator for $name<'a, T> {
3547             type Item = $elem;
3548
3549             #[inline]
3550             fn next(&mut self) -> Option<$elem> {
3551                 // could be implemented with slices, but this avoids bounds checks
3552                 unsafe {
3553                     assume(!self.ptr.as_ptr().is_null());
3554                     if mem::size_of::<T>() != 0 {
3555                         assume(!self.end.is_null());
3556                     }
3557                     if is_empty!(self) {
3558                         None
3559                     } else {
3560                         Some(next_unchecked!(self))
3561                     }
3562                 }
3563             }
3564
3565             #[inline]
3566             fn size_hint(&self) -> (usize, Option<usize>) {
3567                 let exact = len!(self);
3568                 (exact, Some(exact))
3569             }
3570
3571             #[inline]
3572             fn count(self) -> usize {
3573                 len!(self)
3574             }
3575
3576             #[inline]
3577             fn nth(&mut self, n: usize) -> Option<$elem> {
3578                 if n >= len!(self) {
3579                     // This iterator is now empty.
3580                     if mem::size_of::<T>() == 0 {
3581                         // We have to do it this way as `ptr` may never be 0, but `end`
3582                         // could be (due to wrapping).
3583                         self.end = self.ptr.as_ptr();
3584                     } else {
3585                         unsafe {
3586                             // End can't be 0 if T isn't ZST because ptr isn't 0 and end >= ptr
3587                             self.ptr = NonNull::new_unchecked(self.end as *mut T);
3588                         }
3589                     }
3590                     return None;
3591                 }
3592                 // We are in bounds. `post_inc_start` does the right thing even for ZSTs.
3593                 unsafe {
3594                     self.post_inc_start(n as isize);
3595                     Some(next_unchecked!(self))
3596                 }
3597             }
3598
3599             #[inline]
3600             fn last(mut self) -> Option<$elem> {
3601                 self.next_back()
3602             }
3603
3604             // We override the default implementation, which uses `try_fold`,
3605             // because this simple implementation generates less LLVM IR and is
3606             // faster to compile.
3607             #[inline]
3608             fn for_each<F>(mut self, mut f: F)
3609             where
3610                 Self: Sized,
3611                 F: FnMut(Self::Item),
3612             {
3613                 while let Some(x) = self.next() {
3614                     f(x);
3615                 }
3616             }
3617
3618             // We override the default implementation, which uses `try_fold`,
3619             // because this simple implementation generates less LLVM IR and is
3620             // faster to compile.
3621             #[inline]
3622             fn all<F>(&mut self, mut f: F) -> bool
3623             where
3624                 Self: Sized,
3625                 F: FnMut(Self::Item) -> bool,
3626             {
3627                 while let Some(x) = self.next() {
3628                     if !f(x) {
3629                         return false;
3630                     }
3631                 }
3632                 true
3633             }
3634
3635             // We override the default implementation, which uses `try_fold`,
3636             // because this simple implementation generates less LLVM IR and is
3637             // faster to compile.
3638             #[inline]
3639             fn any<F>(&mut self, mut f: F) -> bool
3640             where
3641                 Self: Sized,
3642                 F: FnMut(Self::Item) -> bool,
3643             {
3644                 while let Some(x) = self.next() {
3645                     if f(x) {
3646                         return true;
3647                     }
3648                 }
3649                 false
3650             }
3651
3652             // We override the default implementation, which uses `try_fold`,
3653             // because this simple implementation generates less LLVM IR and is
3654             // faster to compile.
3655             #[inline]
3656             fn find<P>(&mut self, mut predicate: P) -> Option<Self::Item>
3657             where
3658                 Self: Sized,
3659                 P: FnMut(&Self::Item) -> bool,
3660             {
3661                 while let Some(x) = self.next() {
3662                     if predicate(&x) {
3663                         return Some(x);
3664                     }
3665                 }
3666                 None
3667             }
3668
3669             // We override the default implementation, which uses `try_fold`,
3670             // because this simple implementation generates less LLVM IR and is
3671             // faster to compile.
3672             #[inline]
3673             fn find_map<B, F>(&mut self, mut f: F) -> Option<B>
3674             where
3675                 Self: Sized,
3676                 F: FnMut(Self::Item) -> Option<B>,
3677             {
3678                 while let Some(x) = self.next() {
3679                     if let Some(y) = f(x) {
3680                         return Some(y);
3681                     }
3682                 }
3683                 None
3684             }
3685
3686             // We override the default implementation, which uses `try_fold`,
3687             // because this simple implementation generates less LLVM IR and is
3688             // faster to compile. Also, the `assume` avoids a bounds check.
3689             #[inline]
3690             #[rustc_inherit_overflow_checks]
3691             fn position<P>(&mut self, mut predicate: P) -> Option<usize> where
3692                 Self: Sized,
3693                 P: FnMut(Self::Item) -> bool,
3694             {
3695                 let n = len!(self);
3696                 let mut i = 0;
3697                 while let Some(x) = self.next() {
3698                     if predicate(x) {
3699                         unsafe { assume(i < n) };
3700                         return Some(i);
3701                     }
3702                     i += 1;
3703                 }
3704                 None
3705             }
3706
3707             // We override the default implementation, which uses `try_fold`,
3708             // because this simple implementation generates less LLVM IR and is
3709             // faster to compile. Also, the `assume` avoids a bounds check.
3710             #[inline]
3711             fn rposition<P>(&mut self, mut predicate: P) -> Option<usize> where
3712                 P: FnMut(Self::Item) -> bool,
3713                 Self: Sized + ExactSizeIterator + DoubleEndedIterator
3714             {
3715                 let n = len!(self);
3716                 let mut i = n;
3717                 while let Some(x) = self.next_back() {
3718                     i -= 1;
3719                     if predicate(x) {
3720                         unsafe { assume(i < n) };
3721                         return Some(i);
3722                     }
3723                 }
3724                 None
3725             }
3726
3727             $($extra)*
3728         }
3729
3730         #[stable(feature = "rust1", since = "1.0.0")]
3731         impl<'a, T> DoubleEndedIterator for $name<'a, T> {
3732             #[inline]
3733             fn next_back(&mut self) -> Option<$elem> {
3734                 // could be implemented with slices, but this avoids bounds checks
3735                 unsafe {
3736                     assume(!self.ptr.as_ptr().is_null());
3737                     if mem::size_of::<T>() != 0 {
3738                         assume(!self.end.is_null());
3739                     }
3740                     if is_empty!(self) {
3741                         None
3742                     } else {
3743                         Some(next_back_unchecked!(self))
3744                     }
3745                 }
3746             }
3747
3748             #[inline]
3749             fn nth_back(&mut self, n: usize) -> Option<$elem> {
3750                 if n >= len!(self) {
3751                     // This iterator is now empty.
3752                     self.end = self.ptr.as_ptr();
3753                     return None;
3754                 }
3755                 // We are in bounds. `pre_dec_end` does the right thing even for ZSTs.
3756                 unsafe {
3757                     self.pre_dec_end(n as isize);
3758                     Some(next_back_unchecked!(self))
3759                 }
3760             }
3761         }
3762
3763         #[stable(feature = "fused", since = "1.26.0")]
3764         impl<T> FusedIterator for $name<'_, T> {}
3765
3766         #[unstable(feature = "trusted_len", issue = "37572")]
3767         unsafe impl<T> TrustedLen for $name<'_, T> {}
3768     }
3769 }
3770
3771 /// Immutable slice iterator
3772 ///
3773 /// This struct is created by the [`iter`] method on [slices].
3774 ///
3775 /// # Examples
3776 ///
3777 /// Basic usage:
3778 ///
3779 /// ```
3780 /// // First, we declare a type which has `iter` method to get the `Iter` struct (&[usize here]):
3781 /// let slice = &[1, 2, 3];
3782 ///
3783 /// // Then, we iterate over it:
3784 /// for element in slice.iter() {
3785 ///     println!("{}", element);
3786 /// }
3787 /// ```
3788 ///
3789 /// [`iter`]: ../../std/primitive.slice.html#method.iter
3790 /// [slices]: ../../std/primitive.slice.html
3791 #[stable(feature = "rust1", since = "1.0.0")]
3792 pub struct Iter<'a, T: 'a> {
3793     ptr: NonNull<T>,
3794     end: *const T, // If T is a ZST, this is actually ptr+len.  This encoding is picked so that
3795     // ptr == end is a quick test for the Iterator being empty, that works
3796     // for both ZST and non-ZST.
3797     _marker: marker::PhantomData<&'a T>,
3798 }
3799
3800 #[stable(feature = "core_impl_debug", since = "1.9.0")]
3801 impl<T: fmt::Debug> fmt::Debug for Iter<'_, T> {
3802     fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
3803         f.debug_tuple("Iter").field(&self.as_slice()).finish()
3804     }
3805 }
3806
3807 #[stable(feature = "rust1", since = "1.0.0")]
3808 unsafe impl<T: Sync> Sync for Iter<'_, T> {}
3809 #[stable(feature = "rust1", since = "1.0.0")]
3810 unsafe impl<T: Sync> Send for Iter<'_, T> {}
3811
3812 impl<'a, T> Iter<'a, T> {
3813     /// Views the underlying data as a subslice of the original data.
3814     ///
3815     /// This has the same lifetime as the original slice, and so the
3816     /// iterator can continue to be used while this exists.
3817     ///
3818     /// # Examples
3819     ///
3820     /// Basic usage:
3821     ///
3822     /// ```
3823     /// // First, we declare a type which has the `iter` method to get the `Iter`
3824     /// // struct (&[usize here]):
3825     /// let slice = &[1, 2, 3];
3826     ///
3827     /// // Then, we get the iterator:
3828     /// let mut iter = slice.iter();
3829     /// // So if we print what `as_slice` method returns here, we have "[1, 2, 3]":
3830     /// println!("{:?}", iter.as_slice());
3831     ///
3832     /// // Next, we move to the second element of the slice:
3833     /// iter.next();
3834     /// // Now `as_slice` returns "[2, 3]":
3835     /// println!("{:?}", iter.as_slice());
3836     /// ```
3837     #[stable(feature = "iter_to_slice", since = "1.4.0")]
3838     pub fn as_slice(&self) -> &'a [T] {
3839         self.make_slice()
3840     }
3841 }
3842
3843 iterator! {struct Iter -> *const T, &'a T, const, {/* no mut */}, {
3844     fn is_sorted_by<F>(self, mut compare: F) -> bool
3845     where
3846         Self: Sized,
3847         F: FnMut(&Self::Item, &Self::Item) -> Option<Ordering>,
3848     {
3849         self.as_slice().windows(2).all(|w| {
3850             compare(&&w[0], &&w[1]).map(|o| o != Ordering::Greater).unwrap_or(false)
3851         })
3852     }
3853 }}
3854
3855 #[stable(feature = "rust1", since = "1.0.0")]
3856 impl<T> Clone for Iter<'_, T> {
3857     fn clone(&self) -> Self {
3858         Iter { ptr: self.ptr, end: self.end, _marker: self._marker }
3859     }
3860 }
3861
3862 #[stable(feature = "slice_iter_as_ref", since = "1.13.0")]
3863 impl<T> AsRef<[T]> for Iter<'_, T> {
3864     fn as_ref(&self) -> &[T] {
3865         self.as_slice()
3866     }
3867 }
3868
3869 /// Mutable slice iterator.
3870 ///
3871 /// This struct is created by the [`iter_mut`] method on [slices].
3872 ///
3873 /// # Examples
3874 ///
3875 /// Basic usage:
3876 ///
3877 /// ```
3878 /// // First, we declare a type which has `iter_mut` method to get the `IterMut`
3879 /// // struct (&[usize here]):
3880 /// let mut slice = &mut [1, 2, 3];
3881 ///
3882 /// // Then, we iterate over it and increment each element value:
3883 /// for element in slice.iter_mut() {
3884 ///     *element += 1;
3885 /// }
3886 ///
3887 /// // We now have "[2, 3, 4]":
3888 /// println!("{:?}", slice);
3889 /// ```
3890 ///
3891 /// [`iter_mut`]: ../../std/primitive.slice.html#method.iter_mut
3892 /// [slices]: ../../std/primitive.slice.html
3893 #[stable(feature = "rust1", since = "1.0.0")]
3894 pub struct IterMut<'a, T: 'a> {
3895     ptr: NonNull<T>,
3896     end: *mut T, // If T is a ZST, this is actually ptr+len.  This encoding is picked so that
3897     // ptr == end is a quick test for the Iterator being empty, that works
3898     // for both ZST and non-ZST.
3899     _marker: marker::PhantomData<&'a mut T>,
3900 }
3901
3902 #[stable(feature = "core_impl_debug", since = "1.9.0")]
3903 impl<T: fmt::Debug> fmt::Debug for IterMut<'_, T> {
3904     fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
3905         f.debug_tuple("IterMut").field(&self.make_slice()).finish()
3906     }
3907 }
3908
3909 #[stable(feature = "rust1", since = "1.0.0")]
3910 unsafe impl<T: Sync> Sync for IterMut<'_, T> {}
3911 #[stable(feature = "rust1", since = "1.0.0")]
3912 unsafe impl<T: Send> Send for IterMut<'_, T> {}
3913
3914 impl<'a, T> IterMut<'a, T> {
3915     /// Views the underlying data as a subslice of the original data.
3916     ///
3917     /// To avoid creating `&mut` references that alias, this is forced
3918     /// to consume the iterator.
3919     ///
3920     /// # Examples
3921     ///
3922     /// Basic usage:
3923     ///
3924     /// ```
3925     /// // First, we declare a type which has `iter_mut` method to get the `IterMut`
3926     /// // struct (&[usize here]):
3927     /// let mut slice = &mut [1, 2, 3];
3928     ///
3929     /// {
3930     ///     // Then, we get the iterator:
3931     ///     let mut iter = slice.iter_mut();
3932     ///     // We move to next element:
3933     ///     iter.next();
3934     ///     // So if we print what `into_slice` method returns here, we have "[2, 3]":
3935     ///     println!("{:?}", iter.into_slice());
3936     /// }
3937     ///
3938     /// // Now let's modify a value of the slice:
3939     /// {
3940     ///     // First we get back the iterator:
3941     ///     let mut iter = slice.iter_mut();
3942     ///     // We change the value of the first element of the slice returned by the `next` method:
3943     ///     *iter.next().unwrap() += 1;
3944     /// }
3945     /// // Now slice is "[2, 2, 3]":
3946     /// println!("{:?}", slice);
3947     /// ```
3948     #[stable(feature = "iter_to_slice", since = "1.4.0")]
3949     pub fn into_slice(self) -> &'a mut [T] {
3950         unsafe { from_raw_parts_mut(self.ptr.as_ptr(), len!(self)) }
3951     }
3952
3953     /// Views the underlying data as a subslice of the original data.
3954     ///
3955     /// To avoid creating `&mut [T]` references that alias, the returned slice
3956     /// borrows its lifetime from the iterator the method is applied on.
3957     ///
3958     /// # Examples
3959     ///
3960     /// Basic usage:
3961     ///
3962     /// ```
3963     /// # #![feature(slice_iter_mut_as_slice)]
3964     /// let mut slice: &mut [usize] = &mut [1, 2, 3];
3965     ///
3966     /// // First, we get the iterator:
3967     /// let mut iter = slice.iter_mut();
3968     /// // So if we check what the `as_slice` method returns here, we have "[1, 2, 3]":
3969     /// assert_eq!(iter.as_slice(), &[1, 2, 3]);
3970     ///
3971     /// // Next, we move to the second element of the slice:
3972     /// iter.next();
3973     /// // Now `as_slice` returns "[2, 3]":
3974     /// assert_eq!(iter.as_slice(), &[2, 3]);
3975     /// ```
3976     #[unstable(feature = "slice_iter_mut_as_slice", reason = "recently added", issue = "58957")]
3977     pub fn as_slice(&self) -> &[T] {
3978         self.make_slice()
3979     }
3980 }
3981
3982 iterator! {struct IterMut -> *mut T, &'a mut T, mut, {mut}, {}}
3983
3984 /// An internal abstraction over the splitting iterators, so that
3985 /// splitn, splitn_mut etc can be implemented once.
3986 #[doc(hidden)]
3987 trait SplitIter: DoubleEndedIterator {
3988     /// Marks the underlying iterator as complete, extracting the remaining
3989     /// portion of the slice.
3990     fn finish(&mut self) -> Option<Self::Item>;
3991 }
3992
3993 /// An iterator over subslices separated by elements that match a predicate
3994 /// function.
3995 ///
3996 /// This struct is created by the [`split`] method on [slices].
3997 ///
3998 /// [`split`]: ../../std/primitive.slice.html#method.split
3999 /// [slices]: ../../std/primitive.slice.html
4000 #[stable(feature = "rust1", since = "1.0.0")]
4001 pub struct Split<'a, T: 'a, P>
4002 where
4003     P: FnMut(&T) -> bool,
4004 {
4005     v: &'a [T],
4006     pred: P,
4007     finished: bool,
4008 }
4009
4010 #[stable(feature = "core_impl_debug", since = "1.9.0")]
4011 impl<T: fmt::Debug, P> fmt::Debug for Split<'_, T, P>
4012 where
4013     P: FnMut(&T) -> bool,
4014 {
4015     fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
4016         f.debug_struct("Split").field("v", &self.v).field("finished", &self.finished).finish()
4017     }
4018 }
4019
4020 // FIXME(#26925) Remove in favor of `#[derive(Clone)]`
4021 #[stable(feature = "rust1", since = "1.0.0")]
4022 impl<T, P> Clone for Split<'_, T, P>
4023 where
4024     P: Clone + FnMut(&T) -> bool,
4025 {
4026     fn clone(&self) -> Self {
4027         Split { v: self.v, pred: self.pred.clone(), finished: self.finished }
4028     }
4029 }
4030
4031 #[stable(feature = "rust1", since = "1.0.0")]
4032 impl<'a, T, P> Iterator for Split<'a, T, P>
4033 where
4034     P: FnMut(&T) -> bool,
4035 {
4036     type Item = &'a [T];
4037
4038     #[inline]
4039     fn next(&mut self) -> Option<&'a [T]> {
4040         if self.finished {
4041             return None;
4042         }
4043
4044         match self.v.iter().position(|x| (self.pred)(x)) {
4045             None => self.finish(),
4046             Some(idx) => {
4047                 let ret = Some(&self.v[..idx]);
4048                 self.v = &self.v[idx + 1..];
4049                 ret
4050             }
4051         }
4052     }
4053
4054     #[inline]
4055     fn size_hint(&self) -> (usize, Option<usize>) {
4056         if self.finished { (0, Some(0)) } else { (1, Some(self.v.len() + 1)) }
4057     }
4058 }
4059
4060 #[stable(feature = "rust1", since = "1.0.0")]
4061 impl<'a, T, P> DoubleEndedIterator for Split<'a, T, P>
4062 where
4063     P: FnMut(&T) -> bool,
4064 {
4065     #[inline]
4066     fn next_back(&mut self) -> Option<&'a [T]> {
4067         if self.finished {
4068             return None;
4069         }
4070
4071         match self.v.iter().rposition(|x| (self.pred)(x)) {
4072             None => self.finish(),
4073             Some(idx) => {
4074                 let ret = Some(&self.v[idx + 1..]);
4075                 self.v = &self.v[..idx];
4076                 ret
4077             }
4078         }
4079     }
4080 }
4081
4082 impl<'a, T, P> SplitIter for Split<'a, T, P>
4083 where
4084     P: FnMut(&T) -> bool,
4085 {
4086     #[inline]
4087     fn finish(&mut self) -> Option<&'a [T]> {
4088         if self.finished {
4089             None
4090         } else {
4091             self.finished = true;
4092             Some(self.v)
4093         }
4094     }
4095 }
4096
4097 #[stable(feature = "fused", since = "1.26.0")]
4098 impl<T, P> FusedIterator for Split<'_, T, P> where P: FnMut(&T) -> bool {}
4099
4100 /// An iterator over subslices separated by elements that match a predicate
4101 /// function. Unlike `Split`, it contains the matched part as a terminator
4102 /// of the subslice.
4103 ///
4104 /// This struct is created by the [`split_inclusive`] method on [slices].
4105 ///
4106 /// [`split_inclusive`]: ../../std/primitive.slice.html#method.split_inclusive
4107 /// [slices]: ../../std/primitive.slice.html
4108 #[unstable(feature = "split_inclusive", issue = "72360")]
4109 pub struct SplitInclusive<'a, T: 'a, P>
4110 where
4111     P: FnMut(&T) -> bool,
4112 {
4113     v: &'a [T],
4114     pred: P,
4115     finished: bool,
4116 }
4117
4118 #[unstable(feature = "split_inclusive", issue = "72360")]
4119 impl<T: fmt::Debug, P> fmt::Debug for SplitInclusive<'_, T, P>
4120 where
4121     P: FnMut(&T) -> bool,
4122 {
4123     fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
4124         f.debug_struct("SplitInclusive")
4125             .field("v", &self.v)
4126             .field("finished", &self.finished)
4127             .finish()
4128     }
4129 }
4130
4131 // FIXME(#26925) Remove in favor of `#[derive(Clone)]`
4132 #[unstable(feature = "split_inclusive", issue = "72360")]
4133 impl<T, P> Clone for SplitInclusive<'_, T, P>
4134 where
4135     P: Clone + FnMut(&T) -> bool,
4136 {
4137     fn clone(&self) -> Self {
4138         SplitInclusive { v: self.v, pred: self.pred.clone(), finished: self.finished }
4139     }
4140 }
4141
4142 #[unstable(feature = "split_inclusive", issue = "72360")]
4143 impl<'a, T, P> Iterator for SplitInclusive<'a, T, P>
4144 where
4145     P: FnMut(&T) -> bool,
4146 {
4147     type Item = &'a [T];
4148
4149     #[inline]
4150     fn next(&mut self) -> Option<&'a [T]> {
4151         if self.finished {
4152             return None;
4153         }
4154
4155         let idx =
4156             self.v.iter().position(|x| (self.pred)(x)).map(|idx| idx + 1).unwrap_or(self.v.len());
4157         if idx == self.v.len() {
4158             self.finished = true;
4159         }
4160         let ret = Some(&self.v[..idx]);
4161         self.v = &self.v[idx..];
4162         ret
4163     }
4164
4165     #[inline]
4166     fn size_hint(&self) -> (usize, Option<usize>) {
4167         if self.finished { (0, Some(0)) } else { (1, Some(self.v.len() + 1)) }
4168     }
4169 }
4170
4171 #[unstable(feature = "split_inclusive", issue = "72360")]
4172 impl<'a, T, P> DoubleEndedIterator for SplitInclusive<'a, T, P>
4173 where
4174     P: FnMut(&T) -> bool,
4175 {
4176     #[inline]
4177     fn next_back(&mut self) -> Option<&'a [T]> {
4178         if self.finished {
4179             return None;
4180         }
4181
4182         // The last index of self.v is already checked and found to match
4183         // by the last iteration, so we start searching a new match
4184         // one index to the left.
4185         let remainder = if self.v.is_empty() { &[] } else { &self.v[..(self.v.len() - 1)] };
4186         let idx = remainder.iter().rposition(|x| (self.pred)(x)).map(|idx| idx + 1).unwrap_or(0);
4187         if idx == 0 {
4188             self.finished = true;
4189         }
4190         let ret = Some(&self.v[idx..]);
4191         self.v = &self.v[..idx];
4192         ret
4193     }
4194 }
4195
4196 #[unstable(feature = "split_inclusive", issue = "72360")]
4197 impl<T, P> FusedIterator for SplitInclusive<'_, T, P> where P: FnMut(&T) -> bool {}
4198
4199 /// An iterator over the mutable subslices of the vector which are separated
4200 /// by elements that match `pred`.
4201 ///
4202 /// This struct is created by the [`split_mut`] method on [slices].
4203 ///
4204 /// [`split_mut`]: ../../std/primitive.slice.html#method.split_mut
4205 /// [slices]: ../../std/primitive.slice.html
4206 #[stable(feature = "rust1", since = "1.0.0")]
4207 pub struct SplitMut<'a, T: 'a, P>
4208 where
4209     P: FnMut(&T) -> bool,
4210 {
4211     v: &'a mut [T],
4212     pred: P,
4213     finished: bool,
4214 }
4215
4216 #[stable(feature = "core_impl_debug", since = "1.9.0")]
4217 impl<T: fmt::Debug, P> fmt::Debug for SplitMut<'_, T, P>
4218 where
4219     P: FnMut(&T) -> bool,
4220 {
4221     fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
4222         f.debug_struct("SplitMut").field("v", &self.v).field("finished", &self.finished).finish()
4223     }
4224 }
4225
4226 impl<'a, T, P> SplitIter for SplitMut<'a, T, P>
4227 where
4228     P: FnMut(&T) -> bool,
4229 {
4230     #[inline]
4231     fn finish(&mut self) -> Option<&'a mut [T]> {
4232         if self.finished {
4233             None
4234         } else {
4235             self.finished = true;
4236             Some(mem::replace(&mut self.v, &mut []))
4237         }
4238     }
4239 }
4240
4241 #[stable(feature = "rust1", since = "1.0.0")]
4242 impl<'a, T, P> Iterator for SplitMut<'a, T, P>
4243 where
4244     P: FnMut(&T) -> bool,
4245 {
4246     type Item = &'a mut [T];
4247
4248     #[inline]
4249     fn next(&mut self) -> Option<&'a mut [T]> {
4250         if self.finished {
4251             return None;
4252         }
4253
4254         let idx_opt = {
4255             // work around borrowck limitations
4256             let pred = &mut self.pred;
4257             self.v.iter().position(|x| (*pred)(x))
4258         };
4259         match idx_opt {
4260             None => self.finish(),
4261             Some(idx) => {
4262                 let tmp = mem::replace(&mut self.v, &mut []);
4263                 let (head, tail) = tmp.split_at_mut(idx);
4264                 self.v = &mut tail[1..];
4265                 Some(head)
4266             }
4267         }
4268     }
4269
4270     #[inline]
4271     fn size_hint(&self) -> (usize, Option<usize>) {
4272         if self.finished {
4273             (0, Some(0))
4274         } else {
4275             // if the predicate doesn't match anything, we yield one slice
4276             // if it matches every element, we yield len+1 empty slices.
4277             (1, Some(self.v.len() + 1))
4278         }
4279     }
4280 }
4281
4282 #[stable(feature = "rust1", since = "1.0.0")]
4283 impl<'a, T, P> DoubleEndedIterator for SplitMut<'a, T, P>
4284 where
4285     P: FnMut(&T) -> bool,
4286 {
4287     #[inline]
4288     fn next_back(&mut self) -> Option<&'a mut [T]> {
4289         if self.finished {
4290             return None;
4291         }
4292
4293         let idx_opt = {
4294             // work around borrowck limitations
4295             let pred = &mut self.pred;
4296             self.v.iter().rposition(|x| (*pred)(x))
4297         };
4298         match idx_opt {
4299             None => self.finish(),
4300             Some(idx) => {
4301                 let tmp = mem::replace(&mut self.v, &mut []);
4302                 let (head, tail) = tmp.split_at_mut(idx);
4303                 self.v = head;
4304                 Some(&mut tail[1..])
4305             }
4306         }
4307     }
4308 }
4309
4310 #[stable(feature = "fused", since = "1.26.0")]
4311 impl<T, P> FusedIterator for SplitMut<'_, T, P> where P: FnMut(&T) -> bool {}
4312
4313 /// An iterator over the mutable subslices of the vector which are separated
4314 /// by elements that match `pred`. Unlike `SplitMut`, it contains the matched
4315 /// parts in the ends of the subslices.
4316 ///
4317 /// This struct is created by the [`split_inclusive_mut`] method on [slices].
4318 ///
4319 /// [`split_inclusive_mut`]: ../../std/primitive.slice.html#method.split_inclusive_mut
4320 /// [slices]: ../../std/primitive.slice.html
4321 #[unstable(feature = "split_inclusive", issue = "72360")]
4322 pub struct SplitInclusiveMut<'a, T: 'a, P>
4323 where
4324     P: FnMut(&T) -> bool,
4325 {
4326     v: &'a mut [T],
4327     pred: P,
4328     finished: bool,
4329 }
4330
4331 #[unstable(feature = "split_inclusive", issue = "72360")]
4332 impl<T: fmt::Debug, P> fmt::Debug for SplitInclusiveMut<'_, T, P>
4333 where
4334     P: FnMut(&T) -> bool,
4335 {
4336     fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
4337         f.debug_struct("SplitInclusiveMut")
4338             .field("v", &self.v)
4339             .field("finished", &self.finished)
4340             .finish()
4341     }
4342 }
4343
4344 #[unstable(feature = "split_inclusive", issue = "72360")]
4345 impl<'a, T, P> Iterator for SplitInclusiveMut<'a, T, P>
4346 where
4347     P: FnMut(&T) -> bool,
4348 {
4349     type Item = &'a mut [T];
4350
4351     #[inline]
4352     fn next(&mut self) -> Option<&'a mut [T]> {
4353         if self.finished {
4354             return None;
4355         }
4356
4357         let idx_opt = {
4358             // work around borrowck limitations
4359             let pred = &mut self.pred;
4360             self.v.iter().position(|x| (*pred)(x))
4361         };
4362         let idx = idx_opt.map(|idx| idx + 1).unwrap_or(self.v.len());
4363         if idx == self.v.len() {
4364             self.finished = true;
4365         }
4366         let tmp = mem::replace(&mut self.v, &mut []);
4367         let (head, tail) = tmp.split_at_mut(idx);
4368         self.v = tail;
4369         Some(head)
4370     }
4371
4372     #[inline]
4373     fn size_hint(&self) -> (usize, Option<usize>) {
4374         if self.finished {
4375             (0, Some(0))
4376         } else {
4377             // if the predicate doesn't match anything, we yield one slice
4378             // if it matches every element, we yield len+1 empty slices.
4379             (1, Some(self.v.len() + 1))
4380         }
4381     }
4382 }
4383
4384 #[unstable(feature = "split_inclusive", issue = "72360")]
4385 impl<'a, T, P> DoubleEndedIterator for SplitInclusiveMut<'a, T, P>
4386 where
4387     P: FnMut(&T) -> bool,
4388 {
4389     #[inline]
4390     fn next_back(&mut self) -> Option<&'a mut [T]> {
4391         if self.finished {
4392             return None;
4393         }
4394
4395         let idx_opt = if self.v.is_empty() {
4396             None
4397         } else {
4398             // work around borrowck limitations
4399             let pred = &mut self.pred;
4400
4401             // The last index of self.v is already checked and found to match
4402             // by the last iteration, so we start searching a new match
4403             // one index to the left.
4404             let remainder = &self.v[..(self.v.len() - 1)];
4405             remainder.iter().rposition(|x| (*pred)(x))
4406         };
4407         let idx = idx_opt.map(|idx| idx + 1).unwrap_or(0);
4408         if idx == 0 {
4409             self.finished = true;
4410         }
4411         let tmp = mem::replace(&mut self.v, &mut []);
4412         let (head, tail) = tmp.split_at_mut(idx);
4413         self.v = head;
4414         Some(tail)
4415     }
4416 }
4417
4418 #[unstable(feature = "split_inclusive", issue = "72360")]
4419 impl<T, P> FusedIterator for SplitInclusiveMut<'_, T, P> where P: FnMut(&T) -> bool {}
4420
4421 /// An iterator over subslices separated by elements that match a predicate
4422 /// function, starting from the end of the slice.
4423 ///
4424 /// This struct is created by the [`rsplit`] method on [slices].
4425 ///
4426 /// [`rsplit`]: ../../std/primitive.slice.html#method.rsplit
4427 /// [slices]: ../../std/primitive.slice.html
4428 #[stable(feature = "slice_rsplit", since = "1.27.0")]
4429 #[derive(Clone)] // Is this correct, or does it incorrectly require `T: Clone`?
4430 pub struct RSplit<'a, T: 'a, P>
4431 where
4432     P: FnMut(&T) -> bool,
4433 {
4434     inner: Split<'a, T, P>,
4435 }
4436
4437 #[stable(feature = "slice_rsplit", since = "1.27.0")]
4438 impl<T: fmt::Debug, P> fmt::Debug for RSplit<'_, T, P>
4439 where
4440     P: FnMut(&T) -> bool,
4441 {
4442     fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
4443         f.debug_struct("RSplit")
4444             .field("v", &self.inner.v)
4445             .field("finished", &self.inner.finished)
4446             .finish()
4447     }
4448 }
4449
4450 #[stable(feature = "slice_rsplit", since = "1.27.0")]
4451 impl<'a, T, P> Iterator for RSplit<'a, T, P>
4452 where
4453     P: FnMut(&T) -> bool,
4454 {
4455     type Item = &'a [T];
4456
4457     #[inline]
4458     fn next(&mut self) -> Option<&'a [T]> {
4459         self.inner.next_back()
4460     }
4461
4462     #[inline]
4463     fn size_hint(&self) -> (usize, Option<usize>) {
4464         self.inner.size_hint()
4465     }
4466 }
4467
4468 #[stable(feature = "slice_rsplit", since = "1.27.0")]
4469 impl<'a, T, P> DoubleEndedIterator for RSplit<'a, T, P>
4470 where
4471     P: FnMut(&T) -> bool,
4472 {
4473     #[inline]
4474     fn next_back(&mut self) -> Option<&'a [T]> {
4475         self.inner.next()
4476     }
4477 }
4478
4479 #[stable(feature = "slice_rsplit", since = "1.27.0")]
4480 impl<'a, T, P> SplitIter for RSplit<'a, T, P>
4481 where
4482     P: FnMut(&T) -> bool,
4483 {
4484     #[inline]
4485     fn finish(&mut self) -> Option<&'a [T]> {
4486         self.inner.finish()
4487     }
4488 }
4489
4490 #[stable(feature = "slice_rsplit", since = "1.27.0")]
4491 impl<T, P> FusedIterator for RSplit<'_, T, P> where P: FnMut(&T) -> bool {}
4492
4493 /// An iterator over the subslices of the vector which are separated
4494 /// by elements that match `pred`, starting from the end of the slice.
4495 ///
4496 /// This struct is created by the [`rsplit_mut`] method on [slices].
4497 ///
4498 /// [`rsplit_mut`]: ../../std/primitive.slice.html#method.rsplit_mut
4499 /// [slices]: ../../std/primitive.slice.html
4500 #[stable(feature = "slice_rsplit", since = "1.27.0")]
4501 pub struct RSplitMut<'a, T: 'a, P>
4502 where
4503     P: FnMut(&T) -> bool,
4504 {
4505     inner: SplitMut<'a, T, P>,
4506 }
4507
4508 #[stable(feature = "slice_rsplit", since = "1.27.0")]
4509 impl<T: fmt::Debug, P> fmt::Debug for RSplitMut<'_, T, P>
4510 where
4511     P: FnMut(&T) -> bool,
4512 {
4513     fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
4514         f.debug_struct("RSplitMut")
4515             .field("v", &self.inner.v)
4516             .field("finished", &self.inner.finished)
4517             .finish()
4518     }
4519 }
4520
4521 #[stable(feature = "slice_rsplit", since = "1.27.0")]
4522 impl<'a, T, P> SplitIter for RSplitMut<'a, T, P>
4523 where
4524     P: FnMut(&T) -> bool,
4525 {
4526     #[inline]
4527     fn finish(&mut self) -> Option<&'a mut [T]> {
4528         self.inner.finish()
4529     }
4530 }
4531
4532 #[stable(feature = "slice_rsplit", since = "1.27.0")]
4533 impl<'a, T, P> Iterator for RSplitMut<'a, T, P>
4534 where
4535     P: FnMut(&T) -> bool,
4536 {
4537     type Item = &'a mut [T];
4538
4539     #[inline]
4540     fn next(&mut self) -> Option<&'a mut [T]> {
4541         self.inner.next_back()
4542     }
4543
4544     #[inline]
4545     fn size_hint(&self) -> (usize, Option<usize>) {
4546         self.inner.size_hint()
4547     }
4548 }
4549
4550 #[stable(feature = "slice_rsplit", since = "1.27.0")]
4551 impl<'a, T, P> DoubleEndedIterator for RSplitMut<'a, T, P>
4552 where
4553     P: FnMut(&T) -> bool,
4554 {
4555     #[inline]
4556     fn next_back(&mut self) -> Option<&'a mut [T]> {
4557         self.inner.next()
4558     }
4559 }
4560
4561 #[stable(feature = "slice_rsplit", since = "1.27.0")]
4562 impl<T, P> FusedIterator for RSplitMut<'_, T, P> where P: FnMut(&T) -> bool {}
4563
4564 /// An private iterator over subslices separated by elements that
4565 /// match a predicate function, splitting at most a fixed number of
4566 /// times.
4567 #[derive(Debug)]
4568 struct GenericSplitN<I> {
4569     iter: I,
4570     count: usize,
4571 }
4572
4573 impl<T, I: SplitIter<Item = T>> Iterator for GenericSplitN<I> {
4574     type Item = T;
4575
4576     #[inline]
4577     fn next(&mut self) -> Option<T> {
4578         match self.count {
4579             0 => None,
4580             1 => {
4581                 self.count -= 1;
4582                 self.iter.finish()
4583             }
4584             _ => {
4585                 self.count -= 1;
4586                 self.iter.next()
4587             }
4588         }
4589     }
4590
4591     #[inline]
4592     fn size_hint(&self) -> (usize, Option<usize>) {
4593         let (lower, upper_opt) = self.iter.size_hint();
4594         (lower, upper_opt.map(|upper| cmp::min(self.count, upper)))
4595     }
4596 }
4597
4598 /// An iterator over subslices separated by elements that match a predicate
4599 /// function, limited to a given number of splits.
4600 ///
4601 /// This struct is created by the [`splitn`] method on [slices].
4602 ///
4603 /// [`splitn`]: ../../std/primitive.slice.html#method.splitn
4604 /// [slices]: ../../std/primitive.slice.html
4605 #[stable(feature = "rust1", since = "1.0.0")]
4606 pub struct SplitN<'a, T: 'a, P>
4607 where
4608     P: FnMut(&T) -> bool,
4609 {
4610     inner: GenericSplitN<Split<'a, T, P>>,
4611 }
4612
4613 #[stable(feature = "core_impl_debug", since = "1.9.0")]
4614 impl<T: fmt::Debug, P> fmt::Debug for SplitN<'_, T, P>
4615 where
4616     P: FnMut(&T) -> bool,
4617 {
4618     fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
4619         f.debug_struct("SplitN").field("inner", &self.inner).finish()
4620     }
4621 }
4622
4623 /// An iterator over subslices separated by elements that match a
4624 /// predicate function, limited to a given number of splits, starting
4625 /// from the end of the slice.
4626 ///
4627 /// This struct is created by the [`rsplitn`] method on [slices].
4628 ///
4629 /// [`rsplitn`]: ../../std/primitive.slice.html#method.rsplitn
4630 /// [slices]: ../../std/primitive.slice.html
4631 #[stable(feature = "rust1", since = "1.0.0")]
4632 pub struct RSplitN<'a, T: 'a, P>
4633 where
4634     P: FnMut(&T) -> bool,
4635 {
4636     inner: GenericSplitN<RSplit<'a, T, P>>,
4637 }
4638
4639 #[stable(feature = "core_impl_debug", since = "1.9.0")]
4640 impl<T: fmt::Debug, P> fmt::Debug for RSplitN<'_, T, P>
4641 where
4642     P: FnMut(&T) -> bool,
4643 {
4644     fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
4645         f.debug_struct("RSplitN").field("inner", &self.inner).finish()
4646     }
4647 }
4648
4649 /// An iterator over subslices separated by elements that match a predicate
4650 /// function, limited to a given number of splits.
4651 ///
4652 /// This struct is created by the [`splitn_mut`] method on [slices].
4653 ///
4654 /// [`splitn_mut`]: ../../std/primitive.slice.html#method.splitn_mut
4655 /// [slices]: ../../std/primitive.slice.html
4656 #[stable(feature = "rust1", since = "1.0.0")]
4657 pub struct SplitNMut<'a, T: 'a, P>
4658 where
4659     P: FnMut(&T) -> bool,
4660 {
4661     inner: GenericSplitN<SplitMut<'a, T, P>>,
4662 }
4663
4664 #[stable(feature = "core_impl_debug", since = "1.9.0")]
4665 impl<T: fmt::Debug, P> fmt::Debug for SplitNMut<'_, T, P>
4666 where
4667     P: FnMut(&T) -> bool,
4668 {
4669     fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
4670         f.debug_struct("SplitNMut").field("inner", &self.inner).finish()
4671     }
4672 }
4673
4674 /// An iterator over subslices separated by elements that match a
4675 /// predicate function, limited to a given number of splits, starting
4676 /// from the end of the slice.
4677 ///
4678 /// This struct is created by the [`rsplitn_mut`] method on [slices].
4679 ///
4680 /// [`rsplitn_mut`]: ../../std/primitive.slice.html#method.rsplitn_mut
4681 /// [slices]: ../../std/primitive.slice.html
4682 #[stable(feature = "rust1", since = "1.0.0")]
4683 pub struct RSplitNMut<'a, T: 'a, P>
4684 where
4685     P: FnMut(&T) -> bool,
4686 {
4687     inner: GenericSplitN<RSplitMut<'a, T, P>>,
4688 }
4689
4690 #[stable(feature = "core_impl_debug", since = "1.9.0")]
4691 impl<T: fmt::Debug, P> fmt::Debug for RSplitNMut<'_, T, P>
4692 where
4693     P: FnMut(&T) -> bool,
4694 {
4695     fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
4696         f.debug_struct("RSplitNMut").field("inner", &self.inner).finish()
4697     }
4698 }
4699
4700 macro_rules! forward_iterator {
4701     ($name:ident: $elem:ident, $iter_of:ty) => {
4702         #[stable(feature = "rust1", since = "1.0.0")]
4703         impl<'a, $elem, P> Iterator for $name<'a, $elem, P>
4704         where
4705             P: FnMut(&T) -> bool,
4706         {
4707             type Item = $iter_of;
4708
4709             #[inline]
4710             fn next(&mut self) -> Option<$iter_of> {
4711                 self.inner.next()
4712             }
4713
4714             #[inline]
4715             fn size_hint(&self) -> (usize, Option<usize>) {
4716                 self.inner.size_hint()
4717             }
4718         }
4719
4720         #[stable(feature = "fused", since = "1.26.0")]
4721         impl<'a, $elem, P> FusedIterator for $name<'a, $elem, P> where P: FnMut(&T) -> bool {}
4722     };
4723 }
4724
4725 forward_iterator! { SplitN: T, &'a [T] }
4726 forward_iterator! { RSplitN: T, &'a [T] }
4727 forward_iterator! { SplitNMut: T, &'a mut [T] }
4728 forward_iterator! { RSplitNMut: T, &'a mut [T] }
4729
4730 /// An iterator over overlapping subslices of length `size`.
4731 ///
4732 /// This struct is created by the [`windows`] method on [slices].
4733 ///
4734 /// [`windows`]: ../../std/primitive.slice.html#method.windows
4735 /// [slices]: ../../std/primitive.slice.html
4736 #[derive(Debug)]
4737 #[stable(feature = "rust1", since = "1.0.0")]
4738 pub struct Windows<'a, T: 'a> {
4739     v: &'a [T],
4740     size: usize,
4741 }
4742
4743 // FIXME(#26925) Remove in favor of `#[derive(Clone)]`
4744 #[stable(feature = "rust1", since = "1.0.0")]
4745 impl<T> Clone for Windows<'_, T> {
4746     fn clone(&self) -> Self {
4747         Windows { v: self.v, size: self.size }
4748     }
4749 }
4750
4751 #[stable(feature = "rust1", since = "1.0.0")]
4752 impl<'a, T> Iterator for Windows<'a, T> {
4753     type Item = &'a [T];
4754
4755     #[inline]
4756     fn next(&mut self) -> Option<&'a [T]> {
4757         if self.size > self.v.len() {
4758             None
4759         } else {
4760             let ret = Some(&self.v[..self.size]);
4761             self.v = &self.v[1..];
4762             ret
4763         }
4764     }
4765
4766     #[inline]
4767     fn size_hint(&self) -> (usize, Option<usize>) {
4768         if self.size > self.v.len() {
4769             (0, Some(0))
4770         } else {
4771             let size = self.v.len() - self.size + 1;
4772             (size, Some(size))
4773         }
4774     }
4775
4776     #[inline]
4777     fn count(self) -> usize {
4778         self.len()
4779     }
4780
4781     #[inline]
4782     fn nth(&mut self, n: usize) -> Option<Self::Item> {
4783         let (end, overflow) = self.size.overflowing_add(n);
4784         if end > self.v.len() || overflow {
4785             self.v = &[];
4786             None
4787         } else {
4788             let nth = &self.v[n..end];
4789             self.v = &self.v[n + 1..];
4790             Some(nth)
4791         }
4792     }
4793
4794     #[inline]
4795     fn last(self) -> Option<Self::Item> {
4796         if self.size > self.v.len() {
4797             None
4798         } else {
4799             let start = self.v.len() - self.size;
4800             Some(&self.v[start..])
4801         }
4802     }
4803 }
4804
4805 #[stable(feature = "rust1", since = "1.0.0")]
4806 impl<'a, T> DoubleEndedIterator for Windows<'a, T> {
4807     #[inline]
4808     fn next_back(&mut self) -> Option<&'a [T]> {
4809         if self.size > self.v.len() {
4810             None
4811         } else {
4812             let ret = Some(&self.v[self.v.len() - self.size..]);
4813             self.v = &self.v[..self.v.len() - 1];
4814             ret
4815         }
4816     }
4817
4818     #[inline]
4819     fn nth_back(&mut self, n: usize) -> Option<Self::Item> {
4820         let (end, overflow) = self.v.len().overflowing_sub(n);
4821         if end < self.size || overflow {
4822             self.v = &[];
4823             None
4824         } else {
4825             let ret = &self.v[end - self.size..end];
4826             self.v = &self.v[..end - 1];
4827             Some(ret)
4828         }
4829     }
4830 }
4831
4832 #[stable(feature = "rust1", since = "1.0.0")]
4833 impl<T> ExactSizeIterator for Windows<'_, T> {}
4834
4835 #[unstable(feature = "trusted_len", issue = "37572")]
4836 unsafe impl<T> TrustedLen for Windows<'_, T> {}
4837
4838 #[stable(feature = "fused", since = "1.26.0")]
4839 impl<T> FusedIterator for Windows<'_, T> {}
4840
4841 #[doc(hidden)]
4842 unsafe impl<'a, T> TrustedRandomAccess for Windows<'a, T> {
4843     unsafe fn get_unchecked(&mut self, i: usize) -> &'a [T] {
4844         // SAFETY: since the caller guarantees that `i` is in bounds,
4845         // which means that `i` cannot overflow an `isize`, and the
4846         // slice created by `from_raw_parts` is a subslice of `self.v`
4847         // thus is guaranteed to be valid for the lifetime `'a` of `self.v`.
4848         unsafe { from_raw_parts(self.v.as_ptr().add(i), self.size) }
4849     }
4850     fn may_have_side_effect() -> bool {
4851         false
4852     }
4853 }
4854
4855 /// An iterator over a slice in (non-overlapping) chunks (`chunk_size` elements at a
4856 /// time), starting at the beginning of the slice.
4857 ///
4858 /// When the slice len is not evenly divided by the chunk size, the last slice
4859 /// of the iteration will be the remainder.
4860 ///
4861 /// This struct is created by the [`chunks`] method on [slices].
4862 ///
4863 /// [`chunks`]: ../../std/primitive.slice.html#method.chunks
4864 /// [slices]: ../../std/primitive.slice.html
4865 #[derive(Debug)]
4866 #[stable(feature = "rust1", since = "1.0.0")]
4867 pub struct Chunks<'a, T: 'a> {
4868     v: &'a [T],
4869     chunk_size: usize,
4870 }
4871
4872 // FIXME(#26925) Remove in favor of `#[derive(Clone)]`
4873 #[stable(feature = "rust1", since = "1.0.0")]
4874 impl<T> Clone for Chunks<'_, T> {
4875     fn clone(&self) -> Self {
4876         Chunks { v: self.v, chunk_size: self.chunk_size }
4877     }
4878 }
4879
4880 #[stable(feature = "rust1", since = "1.0.0")]
4881 impl<'a, T> Iterator for Chunks<'a, T> {
4882     type Item = &'a [T];
4883
4884     #[inline]
4885     fn next(&mut self) -> Option<&'a [T]> {
4886         if self.v.is_empty() {
4887             None
4888         } else {
4889             let chunksz = cmp::min(self.v.len(), self.chunk_size);
4890             let (fst, snd) = self.v.split_at(chunksz);
4891             self.v = snd;
4892             Some(fst)
4893         }
4894     }
4895
4896     #[inline]
4897     fn size_hint(&self) -> (usize, Option<usize>) {
4898         if self.v.is_empty() {
4899             (0, Some(0))
4900         } else {
4901             let n = self.v.len() / self.chunk_size;
4902             let rem = self.v.len() % self.chunk_size;
4903             let n = if rem > 0 { n + 1 } else { n };
4904             (n, Some(n))
4905         }
4906     }
4907
4908     #[inline]
4909     fn count(self) -> usize {
4910         self.len()
4911     }
4912
4913     #[inline]
4914     fn nth(&mut self, n: usize) -> Option<Self::Item> {
4915         let (start, overflow) = n.overflowing_mul(self.chunk_size);
4916         if start >= self.v.len() || overflow {
4917             self.v = &[];
4918             None
4919         } else {
4920             let end = match start.checked_add(self.chunk_size) {
4921                 Some(sum) => cmp::min(self.v.len(), sum),
4922                 None => self.v.len(),
4923             };
4924             let nth = &self.v[start..end];
4925             self.v = &self.v[end..];
4926             Some(nth)
4927         }
4928     }
4929
4930     #[inline]
4931     fn last(self) -> Option<Self::Item> {
4932         if self.v.is_empty() {
4933             None
4934         } else {
4935             let start = (self.v.len() - 1) / self.chunk_size * self.chunk_size;
4936             Some(&self.v[start..])
4937         }
4938     }
4939 }
4940
4941 #[stable(feature = "rust1", since = "1.0.0")]
4942 impl<'a, T> DoubleEndedIterator for Chunks<'a, T> {
4943     #[inline]
4944     fn next_back(&mut self) -> Option<&'a [T]> {
4945         if self.v.is_empty() {
4946             None
4947         } else {
4948             let remainder = self.v.len() % self.chunk_size;
4949             let chunksz = if remainder != 0 { remainder } else { self.chunk_size };
4950             let (fst, snd) = self.v.split_at(self.v.len() - chunksz);
4951             self.v = fst;
4952             Some(snd)
4953         }
4954     }
4955
4956     #[inline]
4957     fn nth_back(&mut self, n: usize) -> Option<Self::Item> {
4958         let len = self.len();
4959         if n >= len {
4960             self.v = &[];
4961             None
4962         } else {
4963             let start = (len - 1 - n) * self.chunk_size;
4964             let end = match start.checked_add(self.chunk_size) {
4965                 Some(res) => cmp::min(res, self.v.len()),
4966                 None => self.v.len(),
4967             };
4968             let nth_back = &self.v[start..end];
4969             self.v = &self.v[..start];
4970             Some(nth_back)
4971         }
4972     }
4973 }
4974
4975 #[stable(feature = "rust1", since = "1.0.0")]
4976 impl<T> ExactSizeIterator for Chunks<'_, T> {}
4977
4978 #[unstable(feature = "trusted_len", issue = "37572")]
4979 unsafe impl<T> TrustedLen for Chunks<'_, T> {}
4980
4981 #[stable(feature = "fused", since = "1.26.0")]
4982 impl<T> FusedIterator for Chunks<'_, T> {}
4983
4984 #[doc(hidden)]
4985 unsafe impl<'a, T> TrustedRandomAccess for Chunks<'a, T> {
4986     unsafe fn get_unchecked(&mut self, i: usize) -> &'a [T] {
4987         let start = i * self.chunk_size;
4988         let end = match start.checked_add(self.chunk_size) {
4989             None => self.v.len(),
4990             Some(end) => cmp::min(end, self.v.len()),
4991         };
4992         // SAFETY: the caller guarantees that `i` is in bounds,
4993         // which means that `start` must be in bounds of the
4994         // underlying `self.v` slice, and we made sure that `end`
4995         // is also in bounds of `self.v`. Thus, `start` cannot overflow
4996         // an `isize`, and the slice constructed by `from_raw_parts`
4997         // is a subslice of `self.v` which is guaranteed to be valid
4998         // for the lifetime `'a` of `self.v`.
4999         unsafe { from_raw_parts(self.v.as_ptr().add(start), end - start) }
5000     }
5001     fn may_have_side_effect() -> bool {
5002         false
5003     }
5004 }
5005
5006 /// An iterator over a slice in (non-overlapping) mutable chunks (`chunk_size`
5007 /// elements at a time), starting at the beginning of the slice.
5008 ///
5009 /// When the slice len is not evenly divided by the chunk size, the last slice
5010 /// of the iteration will be the remainder.
5011 ///
5012 /// This struct is created by the [`chunks_mut`] method on [slices].
5013 ///
5014 /// [`chunks_mut`]: ../../std/primitive.slice.html#method.chunks_mut
5015 /// [slices]: ../../std/primitive.slice.html
5016 #[derive(Debug)]
5017 #[stable(feature = "rust1", since = "1.0.0")]
5018 pub struct ChunksMut<'a, T: 'a> {
5019     v: &'a mut [T],
5020     chunk_size: usize,
5021 }
5022
5023 #[stable(feature = "rust1", since = "1.0.0")]
5024 impl<'a, T> Iterator for ChunksMut<'a, T> {
5025     type Item = &'a mut [T];
5026
5027     #[inline]
5028     fn next(&mut self) -> Option<&'a mut [T]> {
5029         if self.v.is_empty() {
5030             None
5031         } else {
5032             let sz = cmp::min(self.v.len(), self.chunk_size);
5033             let tmp = mem::replace(&mut self.v, &mut []);
5034             let (head, tail) = tmp.split_at_mut(sz);
5035             self.v = tail;
5036             Some(head)
5037         }
5038     }
5039
5040     #[inline]
5041     fn size_hint(&self) -> (usize, Option<usize>) {
5042         if self.v.is_empty() {
5043             (0, Some(0))
5044         } else {
5045             let n = self.v.len() / self.chunk_size;
5046             let rem = self.v.len() % self.chunk_size;
5047             let n = if rem > 0 { n + 1 } else { n };
5048             (n, Some(n))
5049         }
5050     }
5051
5052     #[inline]
5053     fn count(self) -> usize {
5054         self.len()
5055     }
5056
5057     #[inline]
5058     fn nth(&mut self, n: usize) -> Option<&'a mut [T]> {
5059         let (start, overflow) = n.overflowing_mul(self.chunk_size);
5060         if start >= self.v.len() || overflow {
5061             self.v = &mut [];
5062             None
5063         } else {
5064             let end = match start.checked_add(self.chunk_size) {
5065                 Some(sum) => cmp::min(self.v.len(), sum),
5066                 None => self.v.len(),
5067             };
5068             let tmp = mem::replace(&mut self.v, &mut []);
5069             let (head, tail) = tmp.split_at_mut(end);
5070             let (_, nth) = head.split_at_mut(start);
5071             self.v = tail;
5072             Some(nth)
5073         }
5074     }
5075
5076     #[inline]
5077     fn last(self) -> Option<Self::Item> {
5078         if self.v.is_empty() {
5079             None
5080         } else {
5081             let start = (self.v.len() - 1) / self.chunk_size * self.chunk_size;
5082             Some(&mut self.v[start..])
5083         }
5084     }
5085 }
5086
5087 #[stable(feature = "rust1", since = "1.0.0")]
5088 impl<'a, T> DoubleEndedIterator for ChunksMut<'a, T> {
5089     #[inline]
5090     fn next_back(&mut self) -> Option<&'a mut [T]> {
5091         if self.v.is_empty() {
5092             None
5093         } else {
5094             let remainder = self.v.len() % self.chunk_size;
5095             let sz = if remainder != 0 { remainder } else { self.chunk_size };
5096             let tmp = mem::replace(&mut self.v, &mut []);
5097             let tmp_len = tmp.len();
5098             let (head, tail) = tmp.split_at_mut(tmp_len - sz);
5099             self.v = head;
5100             Some(tail)
5101         }
5102     }
5103
5104     #[inline]
5105     fn nth_back(&mut self, n: usize) -> Option<Self::Item> {
5106         let len = self.len();
5107         if n >= len {
5108             self.v = &mut [];
5109             None
5110         } else {
5111             let start = (len - 1 - n) * self.chunk_size;
5112             let end = match start.checked_add(self.chunk_size) {
5113                 Some(res) => cmp::min(res, self.v.len()),
5114                 None => self.v.len(),
5115             };
5116             let (temp, _tail) = mem::replace(&mut self.v, &mut []).split_at_mut(end);
5117             let (head, nth_back) = temp.split_at_mut(start);
5118             self.v = head;
5119             Some(nth_back)
5120         }
5121     }
5122 }
5123
5124 #[stable(feature = "rust1", since = "1.0.0")]
5125 impl<T> ExactSizeIterator for ChunksMut<'_, T> {}
5126
5127 #[unstable(feature = "trusted_len", issue = "37572")]
5128 unsafe impl<T> TrustedLen for ChunksMut<'_, T> {}
5129
5130 #[stable(feature = "fused", since = "1.26.0")]
5131 impl<T> FusedIterator for ChunksMut<'_, T> {}
5132
5133 #[doc(hidden)]
5134 unsafe impl<'a, T> TrustedRandomAccess for ChunksMut<'a, T> {
5135     unsafe fn get_unchecked(&mut self, i: usize) -> &'a mut [T] {
5136         let start = i * self.chunk_size;
5137         let end = match start.checked_add(self.chunk_size) {
5138             None => self.v.len(),
5139             Some(end) => cmp::min(end, self.v.len()),
5140         };
5141         // SAFETY: see comments for `Chunks::get_unchecked`.
5142         unsafe { from_raw_parts_mut(self.v.as_mut_ptr().add(start), end - start) }
5143     }
5144     fn may_have_side_effect() -> bool {
5145         false
5146     }
5147 }
5148
5149 /// An iterator over a slice in (non-overlapping) chunks (`chunk_size` elements at a
5150 /// time), starting at the beginning of the slice.
5151 ///
5152 /// When the slice len is not evenly divided by the chunk size, the last
5153 /// up to `chunk_size-1` elements will be omitted but can be retrieved from
5154 /// the [`remainder`] function from the iterator.
5155 ///
5156 /// This struct is created by the [`chunks_exact`] method on [slices].
5157 ///
5158 /// [`chunks_exact`]: ../../std/primitive.slice.html#method.chunks_exact
5159 /// [`remainder`]: ../../std/slice/struct.ChunksExact.html#method.remainder
5160 /// [slices]: ../../std/primitive.slice.html
5161 #[derive(Debug)]
5162 #[stable(feature = "chunks_exact", since = "1.31.0")]
5163 pub struct ChunksExact<'a, T: 'a> {
5164     v: &'a [T],
5165     rem: &'a [T],
5166     chunk_size: usize,
5167 }
5168
5169 impl<'a, T> ChunksExact<'a, T> {
5170     /// Returns the remainder of the original slice that is not going to be
5171     /// returned by the iterator. The returned slice has at most `chunk_size-1`
5172     /// elements.
5173     #[stable(feature = "chunks_exact", since = "1.31.0")]
5174     pub fn remainder(&self) -> &'a [T] {
5175         self.rem
5176     }
5177 }
5178
5179 // FIXME(#26925) Remove in favor of `#[derive(Clone)]`
5180 #[stable(feature = "chunks_exact", since = "1.31.0")]
5181 impl<T> Clone for ChunksExact<'_, T> {
5182     fn clone(&self) -> Self {
5183         ChunksExact { v: self.v, rem: self.rem, chunk_size: self.chunk_size }
5184     }
5185 }
5186
5187 #[stable(feature = "chunks_exact", since = "1.31.0")]
5188 impl<'a, T> Iterator for ChunksExact<'a, T> {
5189     type Item = &'a [T];
5190
5191     #[inline]
5192     fn next(&mut self) -> Option<&'a [T]> {
5193         if self.v.len() < self.chunk_size {
5194             None
5195         } else {
5196             let (fst, snd) = self.v.split_at(self.chunk_size);
5197             self.v = snd;
5198             Some(fst)
5199         }
5200     }
5201
5202     #[inline]
5203     fn size_hint(&self) -> (usize, Option<usize>) {
5204         let n = self.v.len() / self.chunk_size;
5205         (n, Some(n))
5206     }
5207
5208     #[inline]
5209     fn count(self) -> usize {
5210         self.len()
5211     }
5212
5213     #[inline]
5214     fn nth(&mut self, n: usize) -> Option<Self::Item> {
5215         let (start, overflow) = n.overflowing_mul(self.chunk_size);
5216         if start >= self.v.len() || overflow {
5217             self.v = &[];
5218             None
5219         } else {
5220             let (_, snd) = self.v.split_at(start);
5221             self.v = snd;
5222             self.next()
5223         }
5224     }
5225
5226     #[inline]
5227     fn last(mut self) -> Option<Self::Item> {
5228         self.next_back()
5229     }
5230 }
5231
5232 #[stable(feature = "chunks_exact", since = "1.31.0")]
5233 impl<'a, T> DoubleEndedIterator for ChunksExact<'a, T> {
5234     #[inline]
5235     fn next_back(&mut self) -> Option<&'a [T]> {
5236         if self.v.len() < self.chunk_size {
5237             None
5238         } else {
5239             let (fst, snd) = self.v.split_at(self.v.len() - self.chunk_size);
5240             self.v = fst;
5241             Some(snd)
5242         }
5243     }
5244
5245     #[inline]
5246     fn nth_back(&mut self, n: usize) -> Option<Self::Item> {
5247         let len = self.len();
5248         if n >= len {
5249             self.v = &[];
5250             None
5251         } else {
5252             let start = (len - 1 - n) * self.chunk_size;
5253             let end = start + self.chunk_size;
5254             let nth_back = &self.v[start..end];
5255             self.v = &self.v[..start];
5256             Some(nth_back)
5257         }
5258     }
5259 }
5260
5261 #[stable(feature = "chunks_exact", since = "1.31.0")]
5262 impl<T> ExactSizeIterator for ChunksExact<'_, T> {
5263     fn is_empty(&self) -> bool {
5264         self.v.is_empty()
5265     }
5266 }
5267
5268 #[unstable(feature = "trusted_len", issue = "37572")]
5269 unsafe impl<T> TrustedLen for ChunksExact<'_, T> {}
5270
5271 #[stable(feature = "chunks_exact", since = "1.31.0")]
5272 impl<T> FusedIterator for ChunksExact<'_, T> {}
5273
5274 #[doc(hidden)]
5275 #[stable(feature = "chunks_exact", since = "1.31.0")]
5276 unsafe impl<'a, T> TrustedRandomAccess for ChunksExact<'a, T> {
5277     unsafe fn get_unchecked(&mut self, i: usize) -> &'a [T] {
5278         let start = i * self.chunk_size;
5279         // SAFETY: mostly identical to `Chunks::get_unchecked`.
5280         unsafe { from_raw_parts(self.v.as_ptr().add(start), self.chunk_size) }
5281     }
5282     fn may_have_side_effect() -> bool {
5283         false
5284     }
5285 }
5286
5287 /// An iterator over a slice in (non-overlapping) mutable chunks (`chunk_size`
5288 /// elements at a time), starting at the beginning of the slice.
5289 ///
5290 /// When the slice len is not evenly divided by the chunk size, the last up to
5291 /// `chunk_size-1` elements will be omitted but can be retrieved from the
5292 /// [`into_remainder`] function from the iterator.
5293 ///
5294 /// This struct is created by the [`chunks_exact_mut`] method on [slices].
5295 ///
5296 /// [`chunks_exact_mut`]: ../../std/primitive.slice.html#method.chunks_exact_mut
5297 /// [`into_remainder`]: ../../std/slice/struct.ChunksExactMut.html#method.into_remainder
5298 /// [slices]: ../../std/primitive.slice.html
5299 #[derive(Debug)]
5300 #[stable(feature = "chunks_exact", since = "1.31.0")]
5301 pub struct ChunksExactMut<'a, T: 'a> {
5302     v: &'a mut [T],
5303     rem: &'a mut [T],
5304     chunk_size: usize,
5305 }
5306
5307 impl<'a, T> ChunksExactMut<'a, T> {
5308     /// Returns the remainder of the original slice that is not going to be
5309     /// returned by the iterator. The returned slice has at most `chunk_size-1`
5310     /// elements.
5311     #[stable(feature = "chunks_exact", since = "1.31.0")]
5312     pub fn into_remainder(self) -> &'a mut [T] {
5313         self.rem
5314     }
5315 }
5316
5317 #[stable(feature = "chunks_exact", since = "1.31.0")]
5318 impl<'a, T> Iterator for ChunksExactMut<'a, T> {
5319     type Item = &'a mut [T];
5320
5321     #[inline]
5322     fn next(&mut self) -> Option<&'a mut [T]> {
5323         if self.v.len() < self.chunk_size {
5324             None
5325         } else {
5326             let tmp = mem::replace(&mut self.v, &mut []);
5327             let (head, tail) = tmp.split_at_mut(self.chunk_size);
5328             self.v = tail;
5329             Some(head)
5330         }
5331     }
5332
5333     #[inline]
5334     fn size_hint(&self) -> (usize, Option<usize>) {
5335         let n = self.v.len() / self.chunk_size;
5336         (n, Some(n))
5337     }
5338
5339     #[inline]
5340     fn count(self) -> usize {
5341         self.len()
5342     }
5343
5344     #[inline]
5345     fn nth(&mut self, n: usize) -> Option<&'a mut [T]> {
5346         let (start, overflow) = n.overflowing_mul(self.chunk_size);
5347         if start >= self.v.len() || overflow {
5348             self.v = &mut [];
5349             None
5350         } else {
5351             let tmp = mem::replace(&mut self.v, &mut []);
5352             let (_, snd) = tmp.split_at_mut(start);
5353             self.v = snd;
5354             self.next()
5355         }
5356     }
5357
5358     #[inline]
5359     fn last(mut self) -> Option<Self::Item> {
5360         self.next_back()
5361     }
5362 }
5363
5364 #[stable(feature = "chunks_exact", since = "1.31.0")]
5365 impl<'a, T> DoubleEndedIterator for ChunksExactMut<'a, T> {
5366     #[inline]
5367     fn next_back(&mut self) -> Option<&'a mut [T]> {
5368         if self.v.len() < self.chunk_size {
5369             None
5370         } else {
5371             let tmp = mem::replace(&mut self.v, &mut []);
5372             let tmp_len = tmp.len();
5373             let (head, tail) = tmp.split_at_mut(tmp_len - self.chunk_size);
5374             self.v = head;
5375             Some(tail)
5376         }
5377     }
5378
5379     #[inline]
5380     fn nth_back(&mut self, n: usize) -> Option<Self::Item> {
5381         let len = self.len();
5382         if n >= len {
5383             self.v = &mut [];
5384             None
5385         } else {
5386             let start = (len - 1 - n) * self.chunk_size;
5387             let end = start + self.chunk_size;
5388             let (temp, _tail) = mem::replace(&mut self.v, &mut []).split_at_mut(end);
5389             let (head, nth_back) = temp.split_at_mut(start);
5390             self.v = head;
5391             Some(nth_back)
5392         }
5393     }
5394 }
5395
5396 #[stable(feature = "chunks_exact", since = "1.31.0")]
5397 impl<T> ExactSizeIterator for ChunksExactMut<'_, T> {
5398     fn is_empty(&self) -> bool {
5399         self.v.is_empty()
5400     }
5401 }
5402
5403 #[unstable(feature = "trusted_len", issue = "37572")]
5404 unsafe impl<T> TrustedLen for ChunksExactMut<'_, T> {}
5405
5406 #[stable(feature = "chunks_exact", since = "1.31.0")]
5407 impl<T> FusedIterator for ChunksExactMut<'_, T> {}
5408
5409 #[doc(hidden)]
5410 #[stable(feature = "chunks_exact", since = "1.31.0")]
5411 unsafe impl<'a, T> TrustedRandomAccess for ChunksExactMut<'a, T> {
5412     unsafe fn get_unchecked(&mut self, i: usize) -> &'a mut [T] {
5413         let start = i * self.chunk_size;
5414         // SAFETY: see comments for `ChunksExactMut::get_unchecked`.
5415         unsafe { from_raw_parts_mut(self.v.as_mut_ptr().add(start), self.chunk_size) }
5416     }
5417     fn may_have_side_effect() -> bool {
5418         false
5419     }
5420 }
5421
5422 /// An iterator over a slice in (non-overlapping) chunks (`chunk_size` elements at a
5423 /// time), starting at the end of the slice.
5424 ///
5425 /// When the slice len is not evenly divided by the chunk size, the last slice
5426 /// of the iteration will be the remainder.
5427 ///
5428 /// This struct is created by the [`rchunks`] method on [slices].
5429 ///
5430 /// [`rchunks`]: ../../std/primitive.slice.html#method.rchunks
5431 /// [slices]: ../../std/primitive.slice.html
5432 #[derive(Debug)]
5433 #[stable(feature = "rchunks", since = "1.31.0")]
5434 pub struct RChunks<'a, T: 'a> {
5435     v: &'a [T],
5436     chunk_size: usize,
5437 }
5438
5439 // FIXME(#26925) Remove in favor of `#[derive(Clone)]`
5440 #[stable(feature = "rchunks", since = "1.31.0")]
5441 impl<T> Clone for RChunks<'_, T> {
5442     fn clone(&self) -> Self {
5443         RChunks { v: self.v, chunk_size: self.chunk_size }
5444     }
5445 }
5446
5447 #[stable(feature = "rchunks", since = "1.31.0")]
5448 impl<'a, T> Iterator for RChunks<'a, T> {
5449     type Item = &'a [T];
5450
5451     #[inline]
5452     fn next(&mut self) -> Option<&'a [T]> {
5453         if self.v.is_empty() {
5454             None
5455         } else {
5456             let chunksz = cmp::min(self.v.len(), self.chunk_size);
5457             let (fst, snd) = self.v.split_at(self.v.len() - chunksz);
5458             self.v = fst;
5459             Some(snd)
5460         }
5461     }
5462
5463     #[inline]
5464     fn size_hint(&self) -> (usize, Option<usize>) {
5465         if self.v.is_empty() {
5466             (0, Some(0))
5467         } else {
5468             let n = self.v.len() / self.chunk_size;
5469             let rem = self.v.len() % self.chunk_size;
5470             let n = if rem > 0 { n + 1 } else { n };
5471             (n, Some(n))
5472         }
5473     }
5474
5475     #[inline]
5476     fn count(self) -> usize {
5477         self.len()
5478     }
5479
5480     #[inline]
5481     fn nth(&mut self, n: usize) -> Option<Self::Item> {
5482         let (end, overflow) = n.overflowing_mul(self.chunk_size);
5483         if end >= self.v.len() || overflow {
5484             self.v = &[];
5485             None
5486         } else {
5487             // Can't underflow because of the check above
5488             let end = self.v.len() - end;
5489             let start = match end.checked_sub(self.chunk_size) {
5490                 Some(sum) => sum,
5491                 None => 0,
5492             };
5493             let nth = &self.v[start..end];
5494             self.v = &self.v[0..start];
5495             Some(nth)
5496         }
5497     }
5498
5499     #[inline]
5500     fn last(self) -> Option<Self::Item> {
5501         if self.v.is_empty() {
5502             None
5503         } else {
5504             let rem = self.v.len() % self.chunk_size;
5505             let end = if rem == 0 { self.chunk_size } else { rem };
5506             Some(&self.v[0..end])
5507         }
5508     }
5509 }
5510
5511 #[stable(feature = "rchunks", since = "1.31.0")]
5512 impl<'a, T> DoubleEndedIterator for RChunks<'a, T> {
5513     #[inline]
5514     fn next_back(&mut self) -> Option<&'a [T]> {
5515         if self.v.is_empty() {
5516             None
5517         } else {
5518             let remainder = self.v.len() % self.chunk_size;
5519             let chunksz = if remainder != 0 { remainder } else { self.chunk_size };
5520             let (fst, snd) = self.v.split_at(chunksz);
5521             self.v = snd;
5522             Some(fst)
5523         }
5524     }
5525
5526     #[inline]
5527     fn nth_back(&mut self, n: usize) -> Option<Self::Item> {
5528         let len = self.len();
5529         if n >= len {
5530             self.v = &[];
5531             None
5532         } else {
5533             // can't underflow because `n < len`
5534             let offset_from_end = (len - 1 - n) * self.chunk_size;
5535             let end = self.v.len() - offset_from_end;
5536             let start = end.saturating_sub(self.chunk_size);
5537             let nth_back = &self.v[start..end];
5538             self.v = &self.v[end..];
5539             Some(nth_back)
5540         }
5541     }
5542 }
5543
5544 #[stable(feature = "rchunks", since = "1.31.0")]
5545 impl<T> ExactSizeIterator for RChunks<'_, T> {}
5546
5547 #[unstable(feature = "trusted_len", issue = "37572")]
5548 unsafe impl<T> TrustedLen for RChunks<'_, T> {}
5549
5550 #[stable(feature = "rchunks", since = "1.31.0")]
5551 impl<T> FusedIterator for RChunks<'_, T> {}
5552
5553 #[doc(hidden)]
5554 #[stable(feature = "rchunks", since = "1.31.0")]
5555 unsafe impl<'a, T> TrustedRandomAccess for RChunks<'a, T> {
5556     unsafe fn get_unchecked(&mut self, i: usize) -> &'a [T] {
5557         let end = self.v.len() - i * self.chunk_size;
5558         let start = match end.checked_sub(self.chunk_size) {
5559             None => 0,
5560             Some(start) => start,
5561         };
5562         // SAFETY: mostly identical to `Chunks::get_unchecked`.
5563         unsafe { from_raw_parts(self.v.as_ptr().add(start), end - start) }
5564     }
5565     fn may_have_side_effect() -> bool {
5566         false
5567     }
5568 }
5569
5570 /// An iterator over a slice in (non-overlapping) mutable chunks (`chunk_size`
5571 /// elements at a time), starting at the end of the slice.
5572 ///
5573 /// When the slice len is not evenly divided by the chunk size, the last slice
5574 /// of the iteration will be the remainder.
5575 ///
5576 /// This struct is created by the [`rchunks_mut`] method on [slices].
5577 ///
5578 /// [`rchunks_mut`]: ../../std/primitive.slice.html#method.rchunks_mut
5579 /// [slices]: ../../std/primitive.slice.html
5580 #[derive(Debug)]
5581 #[stable(feature = "rchunks", since = "1.31.0")]
5582 pub struct RChunksMut<'a, T: 'a> {
5583     v: &'a mut [T],
5584     chunk_size: usize,
5585 }
5586
5587 #[stable(feature = "rchunks", since = "1.31.0")]
5588 impl<'a, T> Iterator for RChunksMut<'a, T> {
5589     type Item = &'a mut [T];
5590
5591     #[inline]
5592     fn next(&mut self) -> Option<&'a mut [T]> {
5593         if self.v.is_empty() {
5594             None
5595         } else {
5596             let sz = cmp::min(self.v.len(), self.chunk_size);
5597             let tmp = mem::replace(&mut self.v, &mut []);
5598             let tmp_len = tmp.len();
5599             let (head, tail) = tmp.split_at_mut(tmp_len - sz);
5600             self.v = head;
5601             Some(tail)
5602         }
5603     }
5604
5605     #[inline]
5606     fn size_hint(&self) -> (usize, Option<usize>) {
5607         if self.v.is_empty() {
5608             (0, Some(0))
5609         } else {
5610             let n = self.v.len() / self.chunk_size;
5611             let rem = self.v.len() % self.chunk_size;
5612             let n = if rem > 0 { n + 1 } else { n };
5613             (n, Some(n))
5614         }
5615     }
5616
5617     #[inline]
5618     fn count(self) -> usize {
5619         self.len()
5620     }
5621
5622     #[inline]
5623     fn nth(&mut self, n: usize) -> Option<&'a mut [T]> {
5624         let (end, overflow) = n.overflowing_mul(self.chunk_size);
5625         if end >= self.v.len() || overflow {
5626             self.v = &mut [];
5627             None
5628         } else {
5629             // Can't underflow because of the check above
5630             let end = self.v.len() - end;
5631             let start = match end.checked_sub(self.chunk_size) {
5632                 Some(sum) => sum,
5633                 None => 0,
5634             };
5635             let tmp = mem::replace(&mut self.v, &mut []);
5636             let (head, tail) = tmp.split_at_mut(start);
5637             let (nth, _) = tail.split_at_mut(end - start);
5638             self.v = head;
5639             Some(nth)
5640         }
5641     }
5642
5643     #[inline]
5644     fn last(self) -> Option<Self::Item> {
5645         if self.v.is_empty() {
5646             None
5647         } else {
5648             let rem = self.v.len() % self.chunk_size;
5649             let end = if rem == 0 { self.chunk_size } else { rem };
5650             Some(&mut self.v[0..end])
5651         }
5652     }
5653 }
5654
5655 #[stable(feature = "rchunks", since = "1.31.0")]
5656 impl<'a, T> DoubleEndedIterator for RChunksMut<'a, T> {
5657     #[inline]
5658     fn next_back(&mut self) -> Option<&'a mut [T]> {
5659         if self.v.is_empty() {
5660             None
5661         } else {
5662             let remainder = self.v.len() % self.chunk_size;
5663             let sz = if remainder != 0 { remainder } else { self.chunk_size };
5664             let tmp = mem::replace(&mut self.v, &mut []);
5665             let (head, tail) = tmp.split_at_mut(sz);
5666             self.v = tail;
5667             Some(head)
5668         }
5669     }
5670
5671     #[inline]
5672     fn nth_back(&mut self, n: usize) -> Option<Self::Item> {
5673         let len = self.len();
5674         if n >= len {
5675             self.v = &mut [];
5676             None
5677         } else {
5678             // can't underflow because `n < len`
5679             let offset_from_end = (len - 1 - n) * self.chunk_size;
5680             let end = self.v.len() - offset_from_end;
5681             let start = end.saturating_sub(self.chunk_size);
5682             let (tmp, tail) = mem::replace(&mut self.v, &mut []).split_at_mut(end);
5683             let (_, nth_back) = tmp.split_at_mut(start);
5684             self.v = tail;
5685             Some(nth_back)
5686         }
5687     }
5688 }
5689
5690 #[stable(feature = "rchunks", since = "1.31.0")]
5691 impl<T> ExactSizeIterator for RChunksMut<'_, T> {}
5692
5693 #[unstable(feature = "trusted_len", issue = "37572")]
5694 unsafe impl<T> TrustedLen for RChunksMut<'_, T> {}
5695
5696 #[stable(feature = "rchunks", since = "1.31.0")]
5697 impl<T> FusedIterator for RChunksMut<'_, T> {}
5698
5699 #[doc(hidden)]
5700 #[stable(feature = "rchunks", since = "1.31.0")]
5701 unsafe impl<'a, T> TrustedRandomAccess for RChunksMut<'a, T> {
5702     unsafe fn get_unchecked(&mut self, i: usize) -> &'a mut [T] {
5703         let end = self.v.len() - i * self.chunk_size;
5704         let start = match end.checked_sub(self.chunk_size) {
5705             None => 0,
5706             Some(start) => start,
5707         };
5708         // SAFETY: see comments for `RChunks::get_unchecked`.
5709         unsafe { from_raw_parts_mut(self.v.as_mut_ptr().add(start), end - start) }
5710     }
5711     fn may_have_side_effect() -> bool {
5712         false
5713     }
5714 }
5715
5716 /// An iterator over a slice in (non-overlapping) chunks (`chunk_size` elements at a
5717 /// time), starting at the end of the slice.
5718 ///
5719 /// When the slice len is not evenly divided by the chunk size, the last
5720 /// up to `chunk_size-1` elements will be omitted but can be retrieved from
5721 /// the [`remainder`] function from the iterator.
5722 ///
5723 /// This struct is created by the [`rchunks_exact`] method on [slices].
5724 ///
5725 /// [`rchunks_exact`]: ../../std/primitive.slice.html#method.rchunks_exact
5726 /// [`remainder`]: ../../std/slice/struct.ChunksExact.html#method.remainder
5727 /// [slices]: ../../std/primitive.slice.html
5728 #[derive(Debug)]
5729 #[stable(feature = "rchunks", since = "1.31.0")]
5730 pub struct RChunksExact<'a, T: 'a> {
5731     v: &'a [T],
5732     rem: &'a [T],
5733     chunk_size: usize,
5734 }
5735
5736 impl<'a, T> RChunksExact<'a, T> {
5737     /// Returns the remainder of the original slice that is not going to be
5738     /// returned by the iterator. The returned slice has at most `chunk_size-1`
5739     /// elements.
5740     #[stable(feature = "rchunks", since = "1.31.0")]
5741     pub fn remainder(&self) -> &'a [T] {
5742         self.rem
5743     }
5744 }
5745
5746 // FIXME(#26925) Remove in favor of `#[derive(Clone)]`
5747 #[stable(feature = "rchunks", since = "1.31.0")]
5748 impl<'a, T> Clone for RChunksExact<'a, T> {
5749     fn clone(&self) -> RChunksExact<'a, T> {
5750         RChunksExact { v: self.v, rem: self.rem, chunk_size: self.chunk_size }
5751     }
5752 }
5753
5754 #[stable(feature = "rchunks", since = "1.31.0")]
5755 impl<'a, T> Iterator for RChunksExact<'a, T> {
5756     type Item = &'a [T];
5757
5758     #[inline]
5759     fn next(&mut self) -> Option<&'a [T]> {
5760         if self.v.len() < self.chunk_size {
5761             None
5762         } else {
5763             let (fst, snd) = self.v.split_at(self.v.len() - self.chunk_size);
5764             self.v = fst;
5765             Some(snd)
5766         }
5767     }
5768
5769     #[inline]
5770     fn size_hint(&self) -> (usize, Option<usize>) {
5771         let n = self.v.len() / self.chunk_size;
5772         (n, Some(n))
5773     }
5774
5775     #[inline]
5776     fn count(self) -> usize {
5777         self.len()
5778     }
5779
5780     #[inline]
5781     fn nth(&mut self, n: usize) -> Option<Self::Item> {
5782         let (end, overflow) = n.overflowing_mul(self.chunk_size);
5783         if end >= self.v.len() || overflow {
5784             self.v = &[];
5785             None
5786         } else {
5787             let (fst, _) = self.v.split_at(self.v.len() - end);
5788             self.v = fst;
5789             self.next()
5790         }
5791     }
5792
5793     #[inline]
5794     fn last(mut self) -> Option<Self::Item> {
5795         self.next_back()
5796     }
5797 }
5798
5799 #[stable(feature = "rchunks", since = "1.31.0")]
5800 impl<'a, T> DoubleEndedIterator for RChunksExact<'a, T> {
5801     #[inline]
5802     fn next_back(&mut self) -> Option<&'a [T]> {
5803         if self.v.len() < self.chunk_size {
5804             None
5805         } else {
5806             let (fst, snd) = self.v.split_at(self.chunk_size);
5807             self.v = snd;
5808             Some(fst)
5809         }
5810     }
5811
5812     #[inline]
5813     fn nth_back(&mut self, n: usize) -> Option<Self::Item> {
5814         let len = self.len();
5815         if n >= len {
5816             self.v = &[];
5817             None
5818         } else {
5819             // now that we know that `n` corresponds to a chunk,
5820             // none of these operations can underflow/overflow
5821             let offset = (len - n) * self.chunk_size;
5822             let start = self.v.len() - offset;
5823             let end = start + self.chunk_size;
5824             let nth_back = &self.v[start..end];
5825             self.v = &self.v[end..];
5826             Some(nth_back)
5827         }
5828     }
5829 }
5830
5831 #[stable(feature = "rchunks", since = "1.31.0")]
5832 impl<'a, T> ExactSizeIterator for RChunksExact<'a, T> {
5833     fn is_empty(&self) -> bool {
5834         self.v.is_empty()
5835     }
5836 }
5837
5838 #[unstable(feature = "trusted_len", issue = "37572")]
5839 unsafe impl<T> TrustedLen for RChunksExact<'_, T> {}
5840
5841 #[stable(feature = "rchunks", since = "1.31.0")]
5842 impl<T> FusedIterator for RChunksExact<'_, T> {}
5843
5844 #[doc(hidden)]
5845 #[stable(feature = "rchunks", since = "1.31.0")]
5846 unsafe impl<'a, T> TrustedRandomAccess for RChunksExact<'a, T> {
5847     unsafe fn get_unchecked(&mut self, i: usize) -> &'a [T] {
5848         let end = self.v.len() - i * self.chunk_size;
5849         let start = end - self.chunk_size;
5850         // SAFETY: mostmy identical to `Chunks::get_unchecked`.
5851         unsafe { from_raw_parts(self.v.as_ptr().add(start), self.chunk_size) }
5852     }
5853     fn may_have_side_effect() -> bool {
5854         false
5855     }
5856 }
5857
5858 /// An iterator over a slice in (non-overlapping) mutable chunks (`chunk_size`
5859 /// elements at a time), starting at the end of the slice.
5860 ///
5861 /// When the slice len is not evenly divided by the chunk size, the last up to
5862 /// `chunk_size-1` elements will be omitted but can be retrieved from the
5863 /// [`into_remainder`] function from the iterator.
5864 ///
5865 /// This struct is created by the [`rchunks_exact_mut`] method on [slices].
5866 ///
5867 /// [`rchunks_exact_mut`]: ../../std/primitive.slice.html#method.rchunks_exact_mut
5868 /// [`into_remainder`]: ../../std/slice/struct.ChunksExactMut.html#method.into_remainder
5869 /// [slices]: ../../std/primitive.slice.html
5870 #[derive(Debug)]
5871 #[stable(feature = "rchunks", since = "1.31.0")]
5872 pub struct RChunksExactMut<'a, T: 'a> {
5873     v: &'a mut [T],
5874     rem: &'a mut [T],
5875     chunk_size: usize,
5876 }
5877
5878 impl<'a, T> RChunksExactMut<'a, T> {
5879     /// Returns the remainder of the original slice that is not going to be
5880     /// returned by the iterator. The returned slice has at most `chunk_size-1`
5881     /// elements.
5882     #[stable(feature = "rchunks", since = "1.31.0")]
5883     pub fn into_remainder(self) -> &'a mut [T] {
5884         self.rem
5885     }
5886 }
5887
5888 #[stable(feature = "rchunks", since = "1.31.0")]
5889 impl<'a, T> Iterator for RChunksExactMut<'a, T> {
5890     type Item = &'a mut [T];
5891
5892     #[inline]
5893     fn next(&mut self) -> Option<&'a mut [T]> {
5894         if self.v.len() < self.chunk_size {
5895             None
5896         } else {
5897             let tmp = mem::replace(&mut self.v, &mut []);
5898             let tmp_len = tmp.len();
5899             let (head, tail) = tmp.split_at_mut(tmp_len - self.chunk_size);
5900             self.v = head;
5901             Some(tail)
5902         }
5903     }
5904
5905     #[inline]
5906     fn size_hint(&self) -> (usize, Option<usize>) {
5907         let n = self.v.len() / self.chunk_size;
5908         (n, Some(n))
5909     }
5910
5911     #[inline]
5912     fn count(self) -> usize {
5913         self.len()
5914     }
5915
5916     #[inline]
5917     fn nth(&mut self, n: usize) -> Option<&'a mut [T]> {
5918         let (end, overflow) = n.overflowing_mul(self.chunk_size);
5919         if end >= self.v.len() || overflow {
5920             self.v = &mut [];
5921             None
5922         } else {
5923             let tmp = mem::replace(&mut self.v, &mut []);
5924             let tmp_len = tmp.len();
5925             let (fst, _) = tmp.split_at_mut(tmp_len - end);
5926             self.v = fst;
5927             self.next()
5928         }
5929     }
5930
5931     #[inline]
5932     fn last(mut self) -> Option<Self::Item> {
5933         self.next_back()
5934     }
5935 }
5936
5937 #[stable(feature = "rchunks", since = "1.31.0")]
5938 impl<'a, T> DoubleEndedIterator for RChunksExactMut<'a, T> {
5939     #[inline]
5940     fn next_back(&mut self) -> Option<&'a mut [T]> {
5941         if self.v.len() < self.chunk_size {
5942             None
5943         } else {
5944             let tmp = mem::replace(&mut self.v, &mut []);
5945             let (head, tail) = tmp.split_at_mut(self.chunk_size);
5946             self.v = tail;
5947             Some(head)
5948         }
5949     }
5950
5951     #[inline]
5952     fn nth_back(&mut self, n: usize) -> Option<Self::Item> {
5953         let len = self.len();
5954         if n >= len {
5955             self.v = &mut [];
5956             None
5957         } else {
5958             // now that we know that `n` corresponds to a chunk,
5959             // none of these operations can underflow/overflow
5960             let offset = (len - n) * self.chunk_size;
5961             let start = self.v.len() - offset;
5962             let end = start + self.chunk_size;
5963             let (tmp, tail) = mem::replace(&mut self.v, &mut []).split_at_mut(end);
5964             let (_, nth_back) = tmp.split_at_mut(start);
5965             self.v = tail;
5966             Some(nth_back)
5967         }
5968     }
5969 }
5970
5971 #[stable(feature = "rchunks", since = "1.31.0")]
5972 impl<T> ExactSizeIterator for RChunksExactMut<'_, T> {
5973     fn is_empty(&self) -> bool {
5974         self.v.is_empty()
5975     }
5976 }
5977
5978 #[unstable(feature = "trusted_len", issue = "37572")]
5979 unsafe impl<T> TrustedLen for RChunksExactMut<'_, T> {}
5980
5981 #[stable(feature = "rchunks", since = "1.31.0")]
5982 impl<T> FusedIterator for RChunksExactMut<'_, T> {}
5983
5984 #[doc(hidden)]
5985 #[stable(feature = "rchunks", since = "1.31.0")]
5986 unsafe impl<'a, T> TrustedRandomAccess for RChunksExactMut<'a, T> {
5987     unsafe fn get_unchecked(&mut self, i: usize) -> &'a mut [T] {
5988         let end = self.v.len() - i * self.chunk_size;
5989         let start = end - self.chunk_size;
5990         // SAFETY: see comments for `RChunksExact::get_unchecked`.
5991         unsafe { from_raw_parts_mut(self.v.as_mut_ptr().add(start), self.chunk_size) }
5992     }
5993     fn may_have_side_effect() -> bool {
5994         false
5995     }
5996 }
5997
5998 //
5999 // Free functions
6000 //
6001
6002 /// Forms a slice from a pointer and a length.
6003 ///
6004 /// The `len` argument is the number of **elements**, not the number of bytes.
6005 ///
6006 /// # Safety
6007 ///
6008 /// Behavior is undefined if any of the following conditions are violated:
6009 ///
6010 /// * `data` must be [valid] for reads for `len * mem::size_of::<T>()` many bytes,
6011 ///   and it must be properly aligned. This means in particular:
6012 ///
6013 ///     * The entire memory range of this slice must be contained within a single allocated object!
6014 ///       Slices can never span across multiple allocated objects. See [below](#incorrect-usage)
6015 ///       for an example incorrectly not taking this into account.
6016 ///     * `data` must be non-null and aligned even for zero-length slices. One
6017 ///       reason for this is that enum layout optimizations may rely on references
6018 ///       (including slices of any length) being aligned and non-null to distinguish
6019 ///       them from other data. You can obtain a pointer that is usable as `data`
6020 ///       for zero-length slices using [`NonNull::dangling()`].
6021 ///
6022 /// * The memory referenced by the returned slice must not be mutated for the duration
6023 ///   of lifetime `'a`, except inside an `UnsafeCell`.
6024 ///
6025 /// * The total size `len * mem::size_of::<T>()` of the slice must be no larger than `isize::MAX`.
6026 ///   See the safety documentation of [`pointer::offset`].
6027 ///
6028 /// # Caveat
6029 ///
6030 /// The lifetime for the returned slice is inferred from its usage. To
6031 /// prevent accidental misuse, it's suggested to tie the lifetime to whichever
6032 /// source lifetime is safe in the context, such as by providing a helper
6033 /// function taking the lifetime of a host value for the slice, or by explicit
6034 /// annotation.
6035 ///
6036 /// # Examples
6037 ///
6038 /// ```
6039 /// use std::slice;
6040 ///
6041 /// // manifest a slice for a single element
6042 /// let x = 42;
6043 /// let ptr = &x as *const _;
6044 /// let slice = unsafe { slice::from_raw_parts(ptr, 1) };
6045 /// assert_eq!(slice[0], 42);
6046 /// ```
6047 ///
6048 /// ### Incorrect usage
6049 ///
6050 /// The following `join_slices` function is **unsound** ⚠️
6051 ///
6052 /// ```rust,no_run
6053 /// use std::slice;
6054 ///
6055 /// fn join_slices<'a, T>(fst: &'a [T], snd: &'a [T]) -> &'a [T] {
6056 ///     let fst_end = fst.as_ptr().wrapping_add(fst.len());
6057 ///     let snd_start = snd.as_ptr();
6058 ///     assert_eq!(fst_end, snd_start, "Slices must be contiguous!");
6059 ///     unsafe {
6060 ///         // The assertion above ensures `fst` and `snd` are contiguous, but they might
6061 ///         // still be contained within _different allocated objects_, in which case
6062 ///         // creating this slice is undefined behavior.
6063 ///         slice::from_raw_parts(fst.as_ptr(), fst.len() + snd.len())
6064 ///     }
6065 /// }
6066 ///
6067 /// fn main() {
6068 ///     // `a` and `b` are different allocated objects...
6069 ///     let a = 42;
6070 ///     let b = 27;
6071 ///     // ... which may nevertheless be laid out contiguously in memory: | a | b |
6072 ///     let _ = join_slices(slice::from_ref(&a), slice::from_ref(&b)); // UB
6073 /// }
6074 /// ```
6075 ///
6076 /// [valid]: ../../std/ptr/index.html#safety
6077 /// [`NonNull::dangling()`]: ../../std/ptr/struct.NonNull.html#method.dangling
6078 /// [`pointer::offset`]: ../../std/primitive.pointer.html#method.offset
6079 #[inline]
6080 #[stable(feature = "rust1", since = "1.0.0")]
6081 pub unsafe fn from_raw_parts<'a, T>(data: *const T, len: usize) -> &'a [T] {
6082     debug_assert!(is_aligned_and_not_null(data), "attempt to create unaligned or null slice");
6083     debug_assert!(
6084         mem::size_of::<T>().saturating_mul(len) <= isize::MAX as usize,
6085         "attempt to create slice covering at least half the address space"
6086     );
6087     // SAFETY: the caller must uphold the safety contract for `from_raw_parts`.
6088     unsafe { &*ptr::slice_from_raw_parts(data, len) }
6089 }
6090
6091 /// Performs the same functionality as [`from_raw_parts`], except that a
6092 /// mutable slice is returned.
6093 ///
6094 /// # Safety
6095 ///
6096 /// Behavior is undefined if any of the following conditions are violated:
6097 ///
6098 /// * `data` must be [valid] for boths reads and writes for `len * mem::size_of::<T>()` many bytes,
6099 ///   and it must be properly aligned. This means in particular:
6100 ///
6101 ///     * The entire memory range of this slice must be contained within a single allocated object!
6102 ///       Slices can never span across multiple allocated objects.
6103 ///     * `data` must be non-null and aligned even for zero-length slices. One
6104 ///       reason for this is that enum layout optimizations may rely on references
6105 ///       (including slices of any length) being aligned and non-null to distinguish
6106 ///       them from other data. You can obtain a pointer that is usable as `data`
6107 ///       for zero-length slices using [`NonNull::dangling()`].
6108 ///
6109 /// * The memory referenced by the returned slice must not be accessed through any other pointer
6110 ///   (not derived from the return value) for the duration of lifetime `'a`.
6111 ///   Both read and write accesses are forbidden.
6112 ///
6113 /// * The total size `len * mem::size_of::<T>()` of the slice must be no larger than `isize::MAX`.
6114 ///   See the safety documentation of [`pointer::offset`].
6115 ///
6116 /// [valid]: ../../std/ptr/index.html#safety
6117 /// [`NonNull::dangling()`]: ../../std/ptr/struct.NonNull.html#method.dangling
6118 /// [`pointer::offset`]: ../../std/primitive.pointer.html#method.offset
6119 /// [`from_raw_parts`]: ../../std/slice/fn.from_raw_parts.html
6120 #[inline]
6121 #[stable(feature = "rust1", since = "1.0.0")]
6122 pub unsafe fn from_raw_parts_mut<'a, T>(data: *mut T, len: usize) -> &'a mut [T] {
6123     debug_assert!(is_aligned_and_not_null(data), "attempt to create unaligned or null slice");
6124     debug_assert!(
6125         mem::size_of::<T>().saturating_mul(len) <= isize::MAX as usize,
6126         "attempt to create slice covering at least half the address space"
6127     );
6128     // SAFETY: the caller must uphold the safety contract for `from_raw_parts_mut`.
6129     unsafe { &mut *ptr::slice_from_raw_parts_mut(data, len) }
6130 }
6131
6132 /// Converts a reference to T into a slice of length 1 (without copying).
6133 #[stable(feature = "from_ref", since = "1.28.0")]
6134 pub fn from_ref<T>(s: &T) -> &[T] {
6135     unsafe { from_raw_parts(s, 1) }
6136 }
6137
6138 /// Converts a reference to T into a slice of length 1 (without copying).
6139 #[stable(feature = "from_ref", since = "1.28.0")]
6140 pub fn from_mut<T>(s: &mut T) -> &mut [T] {
6141     unsafe { from_raw_parts_mut(s, 1) }
6142 }
6143
6144 // This function is public only because there is no other way to unit test heapsort.
6145 #[unstable(feature = "sort_internals", reason = "internal to sort module", issue = "none")]
6146 #[doc(hidden)]
6147 pub fn heapsort<T, F>(v: &mut [T], mut is_less: F)
6148 where
6149     F: FnMut(&T, &T) -> bool,
6150 {
6151     sort::heapsort(v, &mut is_less);
6152 }
6153
6154 //
6155 // Comparison traits
6156 //
6157
6158 extern "C" {
6159     /// Calls implementation provided memcmp.
6160     ///
6161     /// Interprets the data as u8.
6162     ///
6163     /// Returns 0 for equal, < 0 for less than and > 0 for greater
6164     /// than.
6165     // FIXME(#32610): Return type should be c_int
6166     fn memcmp(s1: *const u8, s2: *const u8, n: usize) -> i32;
6167 }
6168
6169 #[stable(feature = "rust1", since = "1.0.0")]
6170 impl<A, B> PartialEq<[B]> for [A]
6171 where
6172     A: PartialEq<B>,
6173 {
6174     fn eq(&self, other: &[B]) -> bool {
6175         SlicePartialEq::equal(self, other)
6176     }
6177
6178     fn ne(&self, other: &[B]) -> bool {
6179         SlicePartialEq::not_equal(self, other)
6180     }
6181 }
6182
6183 #[stable(feature = "rust1", since = "1.0.0")]
6184 impl<T: Eq> Eq for [T] {}
6185
6186 /// Implements comparison of vectors lexicographically.
6187 #[stable(feature = "rust1", since = "1.0.0")]
6188 impl<T: Ord> Ord for [T] {
6189     fn cmp(&self, other: &[T]) -> Ordering {
6190         SliceOrd::compare(self, other)
6191     }
6192 }
6193
6194 /// Implements comparison of vectors lexicographically.
6195 #[stable(feature = "rust1", since = "1.0.0")]
6196 impl<T: PartialOrd> PartialOrd for [T] {
6197     fn partial_cmp(&self, other: &[T]) -> Option<Ordering> {
6198         SlicePartialOrd::partial_compare(self, other)
6199     }
6200 }
6201
6202 #[doc(hidden)]
6203 // intermediate trait for specialization of slice's PartialEq
6204 trait SlicePartialEq<B> {
6205     fn equal(&self, other: &[B]) -> bool;
6206
6207     fn not_equal(&self, other: &[B]) -> bool {
6208         !self.equal(other)
6209     }
6210 }
6211
6212 // Generic slice equality
6213 impl<A, B> SlicePartialEq<B> for [A]
6214 where
6215     A: PartialEq<B>,
6216 {
6217     default fn equal(&self, other: &[B]) -> bool {
6218         if self.len() != other.len() {
6219             return false;
6220         }
6221
6222         self.iter().zip(other.iter()).all(|(x, y)| x == y)
6223     }
6224 }
6225
6226 // Use an equal-pointer optimization when types are `Eq`
6227 impl<A> SlicePartialEq<A> for [A]
6228 where
6229     A: PartialEq<A> + Eq,
6230 {
6231     default fn equal(&self, other: &[A]) -> bool {
6232         if self.len() != other.len() {
6233             return false;
6234         }
6235
6236         // While performance would suffer if `guaranteed_eq` just returned `false`
6237         // for all arguments, correctness and return value of this function are not affected.
6238         if self.as_ptr().guaranteed_eq(other.as_ptr()) {
6239             return true;
6240         }
6241
6242         self.iter().zip(other.iter()).all(|(x, y)| x == y)
6243     }
6244 }
6245
6246 // Use memcmp for bytewise equality when the types allow
6247 impl<A> SlicePartialEq<A> for [A]
6248 where
6249     A: PartialEq<A> + BytewiseEquality,
6250 {
6251     fn equal(&self, other: &[A]) -> bool {
6252         if self.len() != other.len() {
6253             return false;
6254         }
6255
6256         // While performance would suffer if `guaranteed_eq` just returned `false`
6257         // for all arguments, correctness and return value of this function are not affected.
6258         if self.as_ptr().guaranteed_eq(other.as_ptr()) {
6259             return true;
6260         }
6261         unsafe {
6262             let size = mem::size_of_val(self);
6263             memcmp(self.as_ptr() as *const u8, other.as_ptr() as *const u8, size) == 0
6264         }
6265     }
6266 }
6267
6268 #[doc(hidden)]
6269 // intermediate trait for specialization of slice's PartialOrd
6270 trait SlicePartialOrd: Sized {
6271     fn partial_compare(left: &[Self], right: &[Self]) -> Option<Ordering>;
6272 }
6273
6274 impl<A: PartialOrd> SlicePartialOrd for A {
6275     default fn partial_compare(left: &[A], right: &[A]) -> Option<Ordering> {
6276         let l = cmp::min(left.len(), right.len());
6277
6278         // Slice to the loop iteration range to enable bound check
6279         // elimination in the compiler
6280         let lhs = &left[..l];
6281         let rhs = &right[..l];
6282
6283         for i in 0..l {
6284             match lhs[i].partial_cmp(&rhs[i]) {
6285                 Some(Ordering::Equal) => (),
6286                 non_eq => return non_eq,
6287             }
6288         }
6289
6290         left.len().partial_cmp(&right.len())
6291     }
6292 }
6293
6294 // This is the impl that we would like to have. Unfortunately it's not sound.
6295 // See `partial_ord_slice.rs`.
6296 /*
6297 impl<A> SlicePartialOrd for A
6298 where
6299     A: Ord,
6300 {
6301     default fn partial_compare(left: &[A], right: &[A]) -> Option<Ordering> {
6302         Some(SliceOrd::compare(left, right))
6303     }
6304 }
6305 */
6306
6307 impl<A: AlwaysApplicableOrd> SlicePartialOrd for A {
6308     fn partial_compare(left: &[A], right: &[A]) -> Option<Ordering> {
6309         Some(SliceOrd::compare(left, right))
6310     }
6311 }
6312
6313 trait AlwaysApplicableOrd: SliceOrd + Ord {}
6314
6315 macro_rules! always_applicable_ord {
6316     ($([$($p:tt)*] $t:ty,)*) => {
6317         $(impl<$($p)*> AlwaysApplicableOrd for $t {})*
6318     }
6319 }
6320
6321 always_applicable_ord! {
6322     [] u8, [] u16, [] u32, [] u64, [] u128, [] usize,
6323     [] i8, [] i16, [] i32, [] i64, [] i128, [] isize,
6324     [] bool, [] char,
6325     [T: ?Sized] *const T, [T: ?Sized] *mut T,
6326     [T: AlwaysApplicableOrd] &T,
6327     [T: AlwaysApplicableOrd] &mut T,
6328     [T: AlwaysApplicableOrd] Option<T>,
6329 }
6330
6331 #[doc(hidden)]
6332 // intermediate trait for specialization of slice's Ord
6333 trait SliceOrd: Sized {
6334     fn compare(left: &[Self], right: &[Self]) -> Ordering;
6335 }
6336
6337 impl<A: Ord> SliceOrd for A {
6338     default fn compare(left: &[Self], right: &[Self]) -> Ordering {
6339         let l = cmp::min(left.len(), right.len());
6340
6341         // Slice to the loop iteration range to enable bound check
6342         // elimination in the compiler
6343         let lhs = &left[..l];
6344         let rhs = &right[..l];
6345
6346         for i in 0..l {
6347             match lhs[i].cmp(&rhs[i]) {
6348                 Ordering::Equal => (),
6349                 non_eq => return non_eq,
6350             }
6351         }
6352
6353         left.len().cmp(&right.len())
6354     }
6355 }
6356
6357 // memcmp compares a sequence of unsigned bytes lexicographically.
6358 // this matches the order we want for [u8], but no others (not even [i8]).
6359 impl SliceOrd for u8 {
6360     #[inline]
6361     fn compare(left: &[Self], right: &[Self]) -> Ordering {
6362         let order =
6363             unsafe { memcmp(left.as_ptr(), right.as_ptr(), cmp::min(left.len(), right.len())) };
6364         if order == 0 {
6365             left.len().cmp(&right.len())
6366         } else if order < 0 {
6367             Less
6368         } else {
6369             Greater
6370         }
6371     }
6372 }
6373
6374 #[doc(hidden)]
6375 /// Trait implemented for types that can be compared for equality using
6376 /// their bytewise representation
6377 trait BytewiseEquality: Eq + Copy {}
6378
6379 macro_rules! impl_marker_for {
6380     ($traitname:ident, $($ty:ty)*) => {
6381         $(
6382             impl $traitname for $ty { }
6383         )*
6384     }
6385 }
6386
6387 impl_marker_for!(BytewiseEquality,
6388                  u8 i8 u16 i16 u32 i32 u64 i64 u128 i128 usize isize char bool);
6389
6390 #[doc(hidden)]
6391 unsafe impl<'a, T> TrustedRandomAccess for Iter<'a, T> {
6392     unsafe fn get_unchecked(&mut self, i: usize) -> &'a T {
6393         // SAFETY: the caller must guarantee that `i` is in bounds
6394         // of the underlying slice, so `i` cannot overflow an `isize`,
6395         // and the returned references is guaranteed to refer to an element
6396         // of the slice and thus guaranteed to be valid.
6397         unsafe { &*self.ptr.as_ptr().add(i) }
6398     }
6399     fn may_have_side_effect() -> bool {
6400         false
6401     }
6402 }
6403
6404 #[doc(hidden)]
6405 unsafe impl<'a, T> TrustedRandomAccess for IterMut<'a, T> {
6406     unsafe fn get_unchecked(&mut self, i: usize) -> &'a mut T {
6407         // SAFETY: see comments for `Iter::get_unchecked`.
6408         unsafe { &mut *self.ptr.as_ptr().add(i) }
6409     }
6410     fn may_have_side_effect() -> bool {
6411         false
6412     }
6413 }
6414
6415 trait SliceContains: Sized {
6416     fn slice_contains(&self, x: &[Self]) -> bool;
6417 }
6418
6419 impl<T> SliceContains for T
6420 where
6421     T: PartialEq,
6422 {
6423     default fn slice_contains(&self, x: &[Self]) -> bool {
6424         x.iter().any(|y| *y == *self)
6425     }
6426 }
6427
6428 impl SliceContains for u8 {
6429     fn slice_contains(&self, x: &[Self]) -> bool {
6430         memchr::memchr(*self, x).is_some()
6431     }
6432 }
6433
6434 impl SliceContains for i8 {
6435     fn slice_contains(&self, x: &[Self]) -> bool {
6436         let byte = *self as u8;
6437         let bytes: &[u8] = unsafe { from_raw_parts(x.as_ptr() as *const u8, x.len()) };
6438         memchr::memchr(byte, bytes).is_some()
6439     }
6440 }