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