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