]> git.lizzy.rs Git - rust.git/blob - src/libcore/slice/mod.rs
Rollup merge of #60376 - lzutao:stabilize-option_xor, r=SimonSapin
[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     /// # #![feature(copy_within)]
2150     /// let mut bytes = *b"Hello, World!";
2151     ///
2152     /// bytes.copy_within(1..5, 8);
2153     ///
2154     /// assert_eq!(&bytes, b"Hello, Wello!");
2155     /// ```
2156     #[unstable(feature = "copy_within", issue = "54236")]
2157     pub fn copy_within<R: ops::RangeBounds<usize>>(&mut self, src: R, dest: usize)
2158     where
2159         T: Copy,
2160     {
2161         let src_start = match src.start_bound() {
2162             ops::Bound::Included(&n) => n,
2163             ops::Bound::Excluded(&n) => n
2164                 .checked_add(1)
2165                 .unwrap_or_else(|| slice_index_overflow_fail()),
2166             ops::Bound::Unbounded => 0,
2167         };
2168         let src_end = match src.end_bound() {
2169             ops::Bound::Included(&n) => n
2170                 .checked_add(1)
2171                 .unwrap_or_else(|| slice_index_overflow_fail()),
2172             ops::Bound::Excluded(&n) => n,
2173             ops::Bound::Unbounded => self.len(),
2174         };
2175         assert!(src_start <= src_end, "src end is before src start");
2176         assert!(src_end <= self.len(), "src is out of bounds");
2177         let count = src_end - src_start;
2178         assert!(dest <= self.len() - count, "dest is out of bounds");
2179         unsafe {
2180             ptr::copy(
2181                 self.get_unchecked(src_start),
2182                 self.get_unchecked_mut(dest),
2183                 count,
2184             );
2185         }
2186     }
2187
2188     /// Swaps all elements in `self` with those in `other`.
2189     ///
2190     /// The length of `other` must be the same as `self`.
2191     ///
2192     /// # Panics
2193     ///
2194     /// This function will panic if the two slices have different lengths.
2195     ///
2196     /// # Example
2197     ///
2198     /// Swapping two elements across slices:
2199     ///
2200     /// ```
2201     /// let mut slice1 = [0, 0];
2202     /// let mut slice2 = [1, 2, 3, 4];
2203     ///
2204     /// slice1.swap_with_slice(&mut slice2[2..]);
2205     ///
2206     /// assert_eq!(slice1, [3, 4]);
2207     /// assert_eq!(slice2, [1, 2, 0, 0]);
2208     /// ```
2209     ///
2210     /// Rust enforces that there can only be one mutable reference to a
2211     /// particular piece of data in a particular scope. Because of this,
2212     /// attempting to use `swap_with_slice` on a single slice will result in
2213     /// a compile failure:
2214     ///
2215     /// ```compile_fail
2216     /// let mut slice = [1, 2, 3, 4, 5];
2217     /// slice[..2].swap_with_slice(&mut slice[3..]); // compile fail!
2218     /// ```
2219     ///
2220     /// To work around this, we can use [`split_at_mut`] to create two distinct
2221     /// mutable sub-slices from a slice:
2222     ///
2223     /// ```
2224     /// let mut slice = [1, 2, 3, 4, 5];
2225     ///
2226     /// {
2227     ///     let (left, right) = slice.split_at_mut(2);
2228     ///     left.swap_with_slice(&mut right[1..]);
2229     /// }
2230     ///
2231     /// assert_eq!(slice, [4, 5, 3, 1, 2]);
2232     /// ```
2233     ///
2234     /// [`split_at_mut`]: #method.split_at_mut
2235     #[stable(feature = "swap_with_slice", since = "1.27.0")]
2236     pub fn swap_with_slice(&mut self, other: &mut [T]) {
2237         assert!(self.len() == other.len(),
2238                 "destination and source slices have different lengths");
2239         unsafe {
2240             ptr::swap_nonoverlapping(
2241                 self.as_mut_ptr(), other.as_mut_ptr(), self.len());
2242         }
2243     }
2244
2245     /// Function to calculate lengths of the middle and trailing slice for `align_to{,_mut}`.
2246     fn align_to_offsets<U>(&self) -> (usize, usize) {
2247         // What we gonna do about `rest` is figure out what multiple of `U`s we can put in a
2248         // lowest number of `T`s. And how many `T`s we need for each such "multiple".
2249         //
2250         // Consider for example T=u8 U=u16. Then we can put 1 U in 2 Ts. Simple. Now, consider
2251         // for example a case where size_of::<T> = 16, size_of::<U> = 24. We can put 2 Us in
2252         // place of every 3 Ts in the `rest` slice. A bit more complicated.
2253         //
2254         // Formula to calculate this is:
2255         //
2256         // Us = lcm(size_of::<T>, size_of::<U>) / size_of::<U>
2257         // Ts = lcm(size_of::<T>, size_of::<U>) / size_of::<T>
2258         //
2259         // Expanded and simplified:
2260         //
2261         // Us = size_of::<T> / gcd(size_of::<T>, size_of::<U>)
2262         // Ts = size_of::<U> / gcd(size_of::<T>, size_of::<U>)
2263         //
2264         // Luckily since all this is constant-evaluated... performance here matters not!
2265         #[inline]
2266         fn gcd(a: usize, b: usize) -> usize {
2267             use crate::intrinsics;
2268             // iterative stein’s algorithm
2269             // We should still make this `const fn` (and revert to recursive algorithm if we do)
2270             // because relying on llvm to consteval all this is… well, it makes me uncomfortable.
2271             let (ctz_a, mut ctz_b) = unsafe {
2272                 if a == 0 { return b; }
2273                 if b == 0 { return a; }
2274                 (intrinsics::cttz_nonzero(a), intrinsics::cttz_nonzero(b))
2275             };
2276             let k = ctz_a.min(ctz_b);
2277             let mut a = a >> ctz_a;
2278             let mut b = b;
2279             loop {
2280                 // remove all factors of 2 from b
2281                 b >>= ctz_b;
2282                 if a > b {
2283                     mem::swap(&mut a, &mut b);
2284                 }
2285                 b = b - a;
2286                 unsafe {
2287                     if b == 0 {
2288                         break;
2289                     }
2290                     ctz_b = intrinsics::cttz_nonzero(b);
2291                 }
2292             }
2293             a << k
2294         }
2295         let gcd: usize = gcd(mem::size_of::<T>(), mem::size_of::<U>());
2296         let ts: usize = mem::size_of::<U>() / gcd;
2297         let us: usize = mem::size_of::<T>() / gcd;
2298
2299         // Armed with this knowledge, we can find how many `U`s we can fit!
2300         let us_len = self.len() / ts * us;
2301         // And how many `T`s will be in the trailing slice!
2302         let ts_len = self.len() % ts;
2303         (us_len, ts_len)
2304     }
2305
2306     /// Transmute the slice to a slice of another type, ensuring alignment of the types is
2307     /// maintained.
2308     ///
2309     /// This method splits the slice into three distinct slices: prefix, correctly aligned middle
2310     /// slice of a new type, and the suffix slice. The method does a best effort to make the
2311     /// middle slice the greatest length possible for a given type and input slice, but only
2312     /// your algorithm's performance should depend on that, not its correctness.
2313     ///
2314     /// This method has no purpose when either input element `T` or output element `U` are
2315     /// zero-sized and will return the original slice without splitting anything.
2316     ///
2317     /// # Safety
2318     ///
2319     /// This method is essentially a `transmute` with respect to the elements in the returned
2320     /// middle slice, so all the usual caveats pertaining to `transmute::<T, U>` also apply here.
2321     ///
2322     /// # Examples
2323     ///
2324     /// Basic usage:
2325     ///
2326     /// ```
2327     /// unsafe {
2328     ///     let bytes: [u8; 7] = [1, 2, 3, 4, 5, 6, 7];
2329     ///     let (prefix, shorts, suffix) = bytes.align_to::<u16>();
2330     ///     // less_efficient_algorithm_for_bytes(prefix);
2331     ///     // more_efficient_algorithm_for_aligned_shorts(shorts);
2332     ///     // less_efficient_algorithm_for_bytes(suffix);
2333     /// }
2334     /// ```
2335     #[stable(feature = "slice_align_to", since = "1.30.0")]
2336     pub unsafe fn align_to<U>(&self) -> (&[T], &[U], &[T]) {
2337         // Note that most of this function will be constant-evaluated,
2338         if mem::size_of::<U>() == 0 || mem::size_of::<T>() == 0 {
2339             // handle ZSTs specially, which is â€“ don't handle them at all.
2340             return (self, &[], &[]);
2341         }
2342
2343         // First, find at what point do we split between the first and 2nd slice. Easy with
2344         // ptr.align_offset.
2345         let ptr = self.as_ptr();
2346         let offset = crate::ptr::align_offset(ptr, mem::align_of::<U>());
2347         if offset > self.len() {
2348             (self, &[], &[])
2349         } else {
2350             let (left, rest) = self.split_at(offset);
2351             // now `rest` is definitely aligned, so `from_raw_parts_mut` below is okay
2352             let (us_len, ts_len) = rest.align_to_offsets::<U>();
2353             (left,
2354              from_raw_parts(rest.as_ptr() as *const U, us_len),
2355              from_raw_parts(rest.as_ptr().add(rest.len() - ts_len), ts_len))
2356         }
2357     }
2358
2359     /// Transmute the slice to a slice of another type, ensuring alignment of the types is
2360     /// maintained.
2361     ///
2362     /// This method splits the slice into three distinct slices: prefix, correctly aligned middle
2363     /// slice of a new type, and the suffix slice. The method does a best effort to make the
2364     /// middle slice the greatest length possible for a given type and input slice, but only
2365     /// your algorithm's performance should depend on that, not its correctness.
2366     ///
2367     /// This method has no purpose when either input element `T` or output element `U` are
2368     /// zero-sized and will return the original slice without splitting anything.
2369     ///
2370     /// # Safety
2371     ///
2372     /// This method is essentially a `transmute` with respect to the elements in the returned
2373     /// middle slice, so all the usual caveats pertaining to `transmute::<T, U>` also apply here.
2374     ///
2375     /// # Examples
2376     ///
2377     /// Basic usage:
2378     ///
2379     /// ```
2380     /// unsafe {
2381     ///     let mut bytes: [u8; 7] = [1, 2, 3, 4, 5, 6, 7];
2382     ///     let (prefix, shorts, suffix) = bytes.align_to_mut::<u16>();
2383     ///     // less_efficient_algorithm_for_bytes(prefix);
2384     ///     // more_efficient_algorithm_for_aligned_shorts(shorts);
2385     ///     // less_efficient_algorithm_for_bytes(suffix);
2386     /// }
2387     /// ```
2388     #[stable(feature = "slice_align_to", since = "1.30.0")]
2389     pub unsafe fn align_to_mut<U>(&mut self) -> (&mut [T], &mut [U], &mut [T]) {
2390         // Note that most of this function will be constant-evaluated,
2391         if mem::size_of::<U>() == 0 || mem::size_of::<T>() == 0 {
2392             // handle ZSTs specially, which is â€“ don't handle them at all.
2393             return (self, &mut [], &mut []);
2394         }
2395
2396         // First, find at what point do we split between the first and 2nd slice. Easy with
2397         // ptr.align_offset.
2398         let ptr = self.as_ptr();
2399         let offset = crate::ptr::align_offset(ptr, mem::align_of::<U>());
2400         if offset > self.len() {
2401             (self, &mut [], &mut [])
2402         } else {
2403             let (left, rest) = self.split_at_mut(offset);
2404             // now `rest` is definitely aligned, so `from_raw_parts_mut` below is okay
2405             let (us_len, ts_len) = rest.align_to_offsets::<U>();
2406             let mut_ptr = rest.as_mut_ptr();
2407             (left,
2408              from_raw_parts_mut(mut_ptr as *mut U, us_len),
2409              from_raw_parts_mut(mut_ptr.add(rest.len() - ts_len), ts_len))
2410         }
2411     }
2412
2413     /// Checks if the elements of this slice are sorted.
2414     ///
2415     /// That is, for each element `a` and its following element `b`, `a <= b` must hold. If the
2416     /// slice yields exactly zero or one element, `true` is returned.
2417     ///
2418     /// Note that if `Self::Item` is only `PartialOrd`, but not `Ord`, the above definition
2419     /// implies that this function returns `false` if any two consecutive items are not
2420     /// comparable.
2421     ///
2422     /// # Examples
2423     ///
2424     /// ```
2425     /// #![feature(is_sorted)]
2426     /// let empty: [i32; 0] = [];
2427     ///
2428     /// assert!([1, 2, 2, 9].is_sorted());
2429     /// assert!(![1, 3, 2, 4].is_sorted());
2430     /// assert!([0].is_sorted());
2431     /// assert!(empty.is_sorted());
2432     /// assert!(![0.0, 1.0, std::f32::NAN].is_sorted());
2433     /// ```
2434     #[inline]
2435     #[unstable(feature = "is_sorted", reason = "new API", issue = "53485")]
2436     pub fn is_sorted(&self) -> bool
2437     where
2438         T: PartialOrd,
2439     {
2440         self.is_sorted_by(|a, b| a.partial_cmp(b))
2441     }
2442
2443     /// Checks if the elements of this slice are sorted using the given comparator function.
2444     ///
2445     /// Instead of using `PartialOrd::partial_cmp`, this function uses the given `compare`
2446     /// function to determine the ordering of two elements. Apart from that, it's equivalent to
2447     /// [`is_sorted`]; see its documentation for more information.
2448     ///
2449     /// [`is_sorted`]: #method.is_sorted
2450     #[unstable(feature = "is_sorted", reason = "new API", issue = "53485")]
2451     pub fn is_sorted_by<F>(&self, mut compare: F) -> bool
2452     where
2453         F: FnMut(&T, &T) -> Option<Ordering>
2454     {
2455         self.iter().is_sorted_by(|a, b| compare(*a, *b))
2456     }
2457
2458     /// Checks if the elements of this slice are sorted using the given key extraction function.
2459     ///
2460     /// Instead of comparing the slice's elements directly, this function compares the keys of the
2461     /// elements, as determined by `f`. Apart from that, it's equivalent to [`is_sorted`]; see its
2462     /// documentation for more information.
2463     ///
2464     /// [`is_sorted`]: #method.is_sorted
2465     ///
2466     /// # Examples
2467     ///
2468     /// ```
2469     /// #![feature(is_sorted)]
2470     ///
2471     /// assert!(["c", "bb", "aaa"].is_sorted_by_key(|s| s.len()));
2472     /// assert!(![-2i32, -1, 0, 3].is_sorted_by_key(|n| n.abs()));
2473     /// ```
2474     #[inline]
2475     #[unstable(feature = "is_sorted", reason = "new API", issue = "53485")]
2476     pub fn is_sorted_by_key<F, K>(&self, mut f: F) -> bool
2477     where
2478         F: FnMut(&T) -> K,
2479         K: PartialOrd
2480     {
2481         self.is_sorted_by(|a, b| f(a).partial_cmp(&f(b)))
2482     }
2483 }
2484
2485 #[lang = "slice_u8"]
2486 #[cfg(not(test))]
2487 impl [u8] {
2488     /// Checks if all bytes in this slice are within the ASCII range.
2489     #[stable(feature = "ascii_methods_on_intrinsics", since = "1.23.0")]
2490     #[inline]
2491     pub fn is_ascii(&self) -> bool {
2492         self.iter().all(|b| b.is_ascii())
2493     }
2494
2495     /// Checks that two slices are an ASCII case-insensitive match.
2496     ///
2497     /// Same as `to_ascii_lowercase(a) == to_ascii_lowercase(b)`,
2498     /// but without allocating and copying temporaries.
2499     #[stable(feature = "ascii_methods_on_intrinsics", since = "1.23.0")]
2500     #[inline]
2501     pub fn eq_ignore_ascii_case(&self, other: &[u8]) -> bool {
2502         self.len() == other.len() &&
2503             self.iter().zip(other).all(|(a, b)| {
2504                 a.eq_ignore_ascii_case(b)
2505             })
2506     }
2507
2508     /// Converts this slice to its ASCII upper case equivalent in-place.
2509     ///
2510     /// ASCII letters 'a' to 'z' are mapped to 'A' to 'Z',
2511     /// but non-ASCII letters are unchanged.
2512     ///
2513     /// To return a new uppercased value without modifying the existing one, use
2514     /// [`to_ascii_uppercase`].
2515     ///
2516     /// [`to_ascii_uppercase`]: #method.to_ascii_uppercase
2517     #[stable(feature = "ascii_methods_on_intrinsics", since = "1.23.0")]
2518     #[inline]
2519     pub fn make_ascii_uppercase(&mut self) {
2520         for byte in self {
2521             byte.make_ascii_uppercase();
2522         }
2523     }
2524
2525     /// Converts this slice to its ASCII lower case equivalent in-place.
2526     ///
2527     /// ASCII letters 'A' to 'Z' are mapped to 'a' to 'z',
2528     /// but non-ASCII letters are unchanged.
2529     ///
2530     /// To return a new lowercased value without modifying the existing one, use
2531     /// [`to_ascii_lowercase`].
2532     ///
2533     /// [`to_ascii_lowercase`]: #method.to_ascii_lowercase
2534     #[stable(feature = "ascii_methods_on_intrinsics", since = "1.23.0")]
2535     #[inline]
2536     pub fn make_ascii_lowercase(&mut self) {
2537         for byte in self {
2538             byte.make_ascii_lowercase();
2539         }
2540     }
2541
2542 }
2543
2544 #[stable(feature = "rust1", since = "1.0.0")]
2545 impl<T, I> ops::Index<I> for [T]
2546     where I: SliceIndex<[T]>
2547 {
2548     type Output = I::Output;
2549
2550     #[inline]
2551     fn index(&self, index: I) -> &I::Output {
2552         index.index(self)
2553     }
2554 }
2555
2556 #[stable(feature = "rust1", since = "1.0.0")]
2557 impl<T, I> ops::IndexMut<I> for [T]
2558     where I: SliceIndex<[T]>
2559 {
2560     #[inline]
2561     fn index_mut(&mut self, index: I) -> &mut I::Output {
2562         index.index_mut(self)
2563     }
2564 }
2565
2566 #[inline(never)]
2567 #[cold]
2568 fn slice_index_len_fail(index: usize, len: usize) -> ! {
2569     panic!("index {} out of range for slice of length {}", index, len);
2570 }
2571
2572 #[inline(never)]
2573 #[cold]
2574 fn slice_index_order_fail(index: usize, end: usize) -> ! {
2575     panic!("slice index starts at {} but ends at {}", index, end);
2576 }
2577
2578 #[inline(never)]
2579 #[cold]
2580 fn slice_index_overflow_fail() -> ! {
2581     panic!("attempted to index slice up to maximum usize");
2582 }
2583
2584 mod private_slice_index {
2585     use super::ops;
2586     #[stable(feature = "slice_get_slice", since = "1.28.0")]
2587     pub trait Sealed {}
2588
2589     #[stable(feature = "slice_get_slice", since = "1.28.0")]
2590     impl Sealed for usize {}
2591     #[stable(feature = "slice_get_slice", since = "1.28.0")]
2592     impl Sealed for ops::Range<usize> {}
2593     #[stable(feature = "slice_get_slice", since = "1.28.0")]
2594     impl Sealed for ops::RangeTo<usize> {}
2595     #[stable(feature = "slice_get_slice", since = "1.28.0")]
2596     impl Sealed for ops::RangeFrom<usize> {}
2597     #[stable(feature = "slice_get_slice", since = "1.28.0")]
2598     impl Sealed for ops::RangeFull {}
2599     #[stable(feature = "slice_get_slice", since = "1.28.0")]
2600     impl Sealed for ops::RangeInclusive<usize> {}
2601     #[stable(feature = "slice_get_slice", since = "1.28.0")]
2602     impl Sealed for ops::RangeToInclusive<usize> {}
2603 }
2604
2605 /// A helper trait used for indexing operations.
2606 #[stable(feature = "slice_get_slice", since = "1.28.0")]
2607 #[rustc_on_unimplemented(
2608     on(
2609         T = "str",
2610         label = "string indices are ranges of `usize`",
2611     ),
2612     on(
2613         all(any(T = "str", T = "&str", T = "std::string::String"), _Self="{integer}"),
2614         note="you can use `.chars().nth()` or `.bytes().nth()`
2615 see chapter in The Book <https://doc.rust-lang.org/book/ch08-02-strings.html#indexing-into-strings>"
2616     ),
2617     message = "the type `{T}` cannot be indexed by `{Self}`",
2618     label = "slice indices are of type `usize` or ranges of `usize`",
2619 )]
2620 pub trait SliceIndex<T: ?Sized>: private_slice_index::Sealed {
2621     /// The output type returned by methods.
2622     #[stable(feature = "slice_get_slice", since = "1.28.0")]
2623     type Output: ?Sized;
2624
2625     /// Returns a shared reference to the output at this location, if in
2626     /// bounds.
2627     #[unstable(feature = "slice_index_methods", issue = "0")]
2628     fn get(self, slice: &T) -> Option<&Self::Output>;
2629
2630     /// Returns a mutable reference to the output at this location, if in
2631     /// bounds.
2632     #[unstable(feature = "slice_index_methods", issue = "0")]
2633     fn get_mut(self, slice: &mut T) -> Option<&mut Self::Output>;
2634
2635     /// Returns a shared reference to the output at this location, without
2636     /// performing any bounds checking.
2637     #[unstable(feature = "slice_index_methods", issue = "0")]
2638     unsafe fn get_unchecked(self, slice: &T) -> &Self::Output;
2639
2640     /// Returns a mutable reference to the output at this location, without
2641     /// performing any bounds checking.
2642     #[unstable(feature = "slice_index_methods", issue = "0")]
2643     unsafe fn get_unchecked_mut(self, slice: &mut T) -> &mut Self::Output;
2644
2645     /// Returns a shared reference to the output at this location, panicking
2646     /// if out of bounds.
2647     #[unstable(feature = "slice_index_methods", issue = "0")]
2648     fn index(self, slice: &T) -> &Self::Output;
2649
2650     /// Returns a mutable reference to the output at this location, panicking
2651     /// if out of bounds.
2652     #[unstable(feature = "slice_index_methods", issue = "0")]
2653     fn index_mut(self, slice: &mut T) -> &mut Self::Output;
2654 }
2655
2656 #[stable(feature = "slice_get_slice_impls", since = "1.15.0")]
2657 impl<T> SliceIndex<[T]> for usize {
2658     type Output = T;
2659
2660     #[inline]
2661     fn get(self, slice: &[T]) -> Option<&T> {
2662         if self < slice.len() {
2663             unsafe {
2664                 Some(self.get_unchecked(slice))
2665             }
2666         } else {
2667             None
2668         }
2669     }
2670
2671     #[inline]
2672     fn get_mut(self, slice: &mut [T]) -> Option<&mut T> {
2673         if self < slice.len() {
2674             unsafe {
2675                 Some(self.get_unchecked_mut(slice))
2676             }
2677         } else {
2678             None
2679         }
2680     }
2681
2682     #[inline]
2683     unsafe fn get_unchecked(self, slice: &[T]) -> &T {
2684         &*slice.as_ptr().add(self)
2685     }
2686
2687     #[inline]
2688     unsafe fn get_unchecked_mut(self, slice: &mut [T]) -> &mut T {
2689         &mut *slice.as_mut_ptr().add(self)
2690     }
2691
2692     #[inline]
2693     fn index(self, slice: &[T]) -> &T {
2694         // N.B., use intrinsic indexing
2695         &(*slice)[self]
2696     }
2697
2698     #[inline]
2699     fn index_mut(self, slice: &mut [T]) -> &mut T {
2700         // N.B., use intrinsic indexing
2701         &mut (*slice)[self]
2702     }
2703 }
2704
2705 #[stable(feature = "slice_get_slice_impls", since = "1.15.0")]
2706 impl<T> SliceIndex<[T]> for  ops::Range<usize> {
2707     type Output = [T];
2708
2709     #[inline]
2710     fn get(self, slice: &[T]) -> Option<&[T]> {
2711         if self.start > self.end || self.end > slice.len() {
2712             None
2713         } else {
2714             unsafe {
2715                 Some(self.get_unchecked(slice))
2716             }
2717         }
2718     }
2719
2720     #[inline]
2721     fn get_mut(self, slice: &mut [T]) -> Option<&mut [T]> {
2722         if self.start > self.end || self.end > slice.len() {
2723             None
2724         } else {
2725             unsafe {
2726                 Some(self.get_unchecked_mut(slice))
2727             }
2728         }
2729     }
2730
2731     #[inline]
2732     unsafe fn get_unchecked(self, slice: &[T]) -> &[T] {
2733         from_raw_parts(slice.as_ptr().add(self.start), self.end - self.start)
2734     }
2735
2736     #[inline]
2737     unsafe fn get_unchecked_mut(self, slice: &mut [T]) -> &mut [T] {
2738         from_raw_parts_mut(slice.as_mut_ptr().add(self.start), self.end - self.start)
2739     }
2740
2741     #[inline]
2742     fn index(self, slice: &[T]) -> &[T] {
2743         if self.start > self.end {
2744             slice_index_order_fail(self.start, self.end);
2745         } else if self.end > slice.len() {
2746             slice_index_len_fail(self.end, slice.len());
2747         }
2748         unsafe {
2749             self.get_unchecked(slice)
2750         }
2751     }
2752
2753     #[inline]
2754     fn index_mut(self, slice: &mut [T]) -> &mut [T] {
2755         if self.start > self.end {
2756             slice_index_order_fail(self.start, self.end);
2757         } else if self.end > slice.len() {
2758             slice_index_len_fail(self.end, slice.len());
2759         }
2760         unsafe {
2761             self.get_unchecked_mut(slice)
2762         }
2763     }
2764 }
2765
2766 #[stable(feature = "slice_get_slice_impls", since = "1.15.0")]
2767 impl<T> SliceIndex<[T]> for ops::RangeTo<usize> {
2768     type Output = [T];
2769
2770     #[inline]
2771     fn get(self, slice: &[T]) -> Option<&[T]> {
2772         (0..self.end).get(slice)
2773     }
2774
2775     #[inline]
2776     fn get_mut(self, slice: &mut [T]) -> Option<&mut [T]> {
2777         (0..self.end).get_mut(slice)
2778     }
2779
2780     #[inline]
2781     unsafe fn get_unchecked(self, slice: &[T]) -> &[T] {
2782         (0..self.end).get_unchecked(slice)
2783     }
2784
2785     #[inline]
2786     unsafe fn get_unchecked_mut(self, slice: &mut [T]) -> &mut [T] {
2787         (0..self.end).get_unchecked_mut(slice)
2788     }
2789
2790     #[inline]
2791     fn index(self, slice: &[T]) -> &[T] {
2792         (0..self.end).index(slice)
2793     }
2794
2795     #[inline]
2796     fn index_mut(self, slice: &mut [T]) -> &mut [T] {
2797         (0..self.end).index_mut(slice)
2798     }
2799 }
2800
2801 #[stable(feature = "slice_get_slice_impls", since = "1.15.0")]
2802 impl<T> SliceIndex<[T]> for ops::RangeFrom<usize> {
2803     type Output = [T];
2804
2805     #[inline]
2806     fn get(self, slice: &[T]) -> Option<&[T]> {
2807         (self.start..slice.len()).get(slice)
2808     }
2809
2810     #[inline]
2811     fn get_mut(self, slice: &mut [T]) -> Option<&mut [T]> {
2812         (self.start..slice.len()).get_mut(slice)
2813     }
2814
2815     #[inline]
2816     unsafe fn get_unchecked(self, slice: &[T]) -> &[T] {
2817         (self.start..slice.len()).get_unchecked(slice)
2818     }
2819
2820     #[inline]
2821     unsafe fn get_unchecked_mut(self, slice: &mut [T]) -> &mut [T] {
2822         (self.start..slice.len()).get_unchecked_mut(slice)
2823     }
2824
2825     #[inline]
2826     fn index(self, slice: &[T]) -> &[T] {
2827         (self.start..slice.len()).index(slice)
2828     }
2829
2830     #[inline]
2831     fn index_mut(self, slice: &mut [T]) -> &mut [T] {
2832         (self.start..slice.len()).index_mut(slice)
2833     }
2834 }
2835
2836 #[stable(feature = "slice_get_slice_impls", since = "1.15.0")]
2837 impl<T> SliceIndex<[T]> for ops::RangeFull {
2838     type Output = [T];
2839
2840     #[inline]
2841     fn get(self, slice: &[T]) -> Option<&[T]> {
2842         Some(slice)
2843     }
2844
2845     #[inline]
2846     fn get_mut(self, slice: &mut [T]) -> Option<&mut [T]> {
2847         Some(slice)
2848     }
2849
2850     #[inline]
2851     unsafe fn get_unchecked(self, slice: &[T]) -> &[T] {
2852         slice
2853     }
2854
2855     #[inline]
2856     unsafe fn get_unchecked_mut(self, slice: &mut [T]) -> &mut [T] {
2857         slice
2858     }
2859
2860     #[inline]
2861     fn index(self, slice: &[T]) -> &[T] {
2862         slice
2863     }
2864
2865     #[inline]
2866     fn index_mut(self, slice: &mut [T]) -> &mut [T] {
2867         slice
2868     }
2869 }
2870
2871
2872 #[stable(feature = "inclusive_range", since = "1.26.0")]
2873 impl<T> SliceIndex<[T]> for ops::RangeInclusive<usize> {
2874     type Output = [T];
2875
2876     #[inline]
2877     fn get(self, slice: &[T]) -> Option<&[T]> {
2878         if *self.end() == usize::max_value() { None }
2879         else { (*self.start()..self.end() + 1).get(slice) }
2880     }
2881
2882     #[inline]
2883     fn get_mut(self, slice: &mut [T]) -> Option<&mut [T]> {
2884         if *self.end() == usize::max_value() { None }
2885         else { (*self.start()..self.end() + 1).get_mut(slice) }
2886     }
2887
2888     #[inline]
2889     unsafe fn get_unchecked(self, slice: &[T]) -> &[T] {
2890         (*self.start()..self.end() + 1).get_unchecked(slice)
2891     }
2892
2893     #[inline]
2894     unsafe fn get_unchecked_mut(self, slice: &mut [T]) -> &mut [T] {
2895         (*self.start()..self.end() + 1).get_unchecked_mut(slice)
2896     }
2897
2898     #[inline]
2899     fn index(self, slice: &[T]) -> &[T] {
2900         if *self.end() == usize::max_value() { slice_index_overflow_fail(); }
2901         (*self.start()..self.end() + 1).index(slice)
2902     }
2903
2904     #[inline]
2905     fn index_mut(self, slice: &mut [T]) -> &mut [T] {
2906         if *self.end() == usize::max_value() { slice_index_overflow_fail(); }
2907         (*self.start()..self.end() + 1).index_mut(slice)
2908     }
2909 }
2910
2911 #[stable(feature = "inclusive_range", since = "1.26.0")]
2912 impl<T> SliceIndex<[T]> for ops::RangeToInclusive<usize> {
2913     type Output = [T];
2914
2915     #[inline]
2916     fn get(self, slice: &[T]) -> Option<&[T]> {
2917         (0..=self.end).get(slice)
2918     }
2919
2920     #[inline]
2921     fn get_mut(self, slice: &mut [T]) -> Option<&mut [T]> {
2922         (0..=self.end).get_mut(slice)
2923     }
2924
2925     #[inline]
2926     unsafe fn get_unchecked(self, slice: &[T]) -> &[T] {
2927         (0..=self.end).get_unchecked(slice)
2928     }
2929
2930     #[inline]
2931     unsafe fn get_unchecked_mut(self, slice: &mut [T]) -> &mut [T] {
2932         (0..=self.end).get_unchecked_mut(slice)
2933     }
2934
2935     #[inline]
2936     fn index(self, slice: &[T]) -> &[T] {
2937         (0..=self.end).index(slice)
2938     }
2939
2940     #[inline]
2941     fn index_mut(self, slice: &mut [T]) -> &mut [T] {
2942         (0..=self.end).index_mut(slice)
2943     }
2944 }
2945
2946 ////////////////////////////////////////////////////////////////////////////////
2947 // Common traits
2948 ////////////////////////////////////////////////////////////////////////////////
2949
2950 #[stable(feature = "rust1", since = "1.0.0")]
2951 impl<T> Default for &[T] {
2952     /// Creates an empty slice.
2953     fn default() -> Self { &[] }
2954 }
2955
2956 #[stable(feature = "mut_slice_default", since = "1.5.0")]
2957 impl<T> Default for &mut [T] {
2958     /// Creates a mutable empty slice.
2959     fn default() -> Self { &mut [] }
2960 }
2961
2962 //
2963 // Iterators
2964 //
2965
2966 #[stable(feature = "rust1", since = "1.0.0")]
2967 impl<'a, T> IntoIterator for &'a [T] {
2968     type Item = &'a T;
2969     type IntoIter = Iter<'a, T>;
2970
2971     fn into_iter(self) -> Iter<'a, T> {
2972         self.iter()
2973     }
2974 }
2975
2976 #[stable(feature = "rust1", since = "1.0.0")]
2977 impl<'a, T> IntoIterator for &'a mut [T] {
2978     type Item = &'a mut T;
2979     type IntoIter = IterMut<'a, T>;
2980
2981     fn into_iter(self) -> IterMut<'a, T> {
2982         self.iter_mut()
2983     }
2984 }
2985
2986 // Macro helper functions
2987 #[inline(always)]
2988 fn size_from_ptr<T>(_: *const T) -> usize {
2989     mem::size_of::<T>()
2990 }
2991
2992 // Inlining is_empty and len makes a huge performance difference
2993 macro_rules! is_empty {
2994     // The way we encode the length of a ZST iterator, this works both for ZST
2995     // and non-ZST.
2996     ($self: ident) => {$self.ptr == $self.end}
2997 }
2998 // To get rid of some bounds checks (see `position`), we compute the length in a somewhat
2999 // unexpected way. (Tested by `codegen/slice-position-bounds-check`.)
3000 macro_rules! len {
3001     ($self: ident) => {{
3002         let start = $self.ptr;
3003         let diff = ($self.end as usize).wrapping_sub(start as usize);
3004         let size = size_from_ptr(start);
3005         if size == 0 {
3006             diff
3007         } else {
3008             // Using division instead of `offset_from` helps LLVM remove bounds checks
3009             diff / size
3010         }
3011     }}
3012 }
3013
3014 // The shared definition of the `Iter` and `IterMut` iterators
3015 macro_rules! iterator {
3016     (
3017         struct $name:ident -> $ptr:ty,
3018         $elem:ty,
3019         $raw_mut:tt,
3020         {$( $mut_:tt )*},
3021         {$($extra:tt)*}
3022     ) => {
3023         impl<'a, T> $name<'a, T> {
3024             // Helper function for creating a slice from the iterator.
3025             #[inline(always)]
3026             fn make_slice(&self) -> &'a [T] {
3027                 unsafe { from_raw_parts(self.ptr, len!(self)) }
3028             }
3029
3030             // Helper function for moving the start of the iterator forwards by `offset` elements,
3031             // returning the old start.
3032             // Unsafe because the offset must be in-bounds or one-past-the-end.
3033             #[inline(always)]
3034             unsafe fn post_inc_start(&mut self, offset: isize) -> * $raw_mut T {
3035                 if mem::size_of::<T>() == 0 {
3036                     // This is *reducing* the length.  `ptr` never changes with ZST.
3037                     self.end = (self.end as * $raw_mut u8).wrapping_offset(-offset) as * $raw_mut T;
3038                     self.ptr
3039                 } else {
3040                     let old = self.ptr;
3041                     self.ptr = self.ptr.offset(offset);
3042                     old
3043                 }
3044             }
3045
3046             // Helper function for moving the end of the iterator backwards by `offset` elements,
3047             // returning the new end.
3048             // Unsafe because the offset must be in-bounds or one-past-the-end.
3049             #[inline(always)]
3050             unsafe fn pre_dec_end(&mut self, offset: isize) -> * $raw_mut T {
3051                 if mem::size_of::<T>() == 0 {
3052                     self.end = (self.end as * $raw_mut u8).wrapping_offset(-offset) as * $raw_mut T;
3053                     self.ptr
3054                 } else {
3055                     self.end = self.end.offset(-offset);
3056                     self.end
3057                 }
3058             }
3059         }
3060
3061         #[stable(feature = "rust1", since = "1.0.0")]
3062         impl<T> ExactSizeIterator for $name<'_, T> {
3063             #[inline(always)]
3064             fn len(&self) -> usize {
3065                 len!(self)
3066             }
3067
3068             #[inline(always)]
3069             fn is_empty(&self) -> bool {
3070                 is_empty!(self)
3071             }
3072         }
3073
3074         #[stable(feature = "rust1", since = "1.0.0")]
3075         impl<'a, T> Iterator for $name<'a, T> {
3076             type Item = $elem;
3077
3078             #[inline]
3079             fn next(&mut self) -> Option<$elem> {
3080                 // could be implemented with slices, but this avoids bounds checks
3081                 unsafe {
3082                     assume(!self.ptr.is_null());
3083                     if mem::size_of::<T>() != 0 {
3084                         assume(!self.end.is_null());
3085                     }
3086                     if is_empty!(self) {
3087                         None
3088                     } else {
3089                         Some(& $( $mut_ )* *self.post_inc_start(1))
3090                     }
3091                 }
3092             }
3093
3094             #[inline]
3095             fn size_hint(&self) -> (usize, Option<usize>) {
3096                 let exact = len!(self);
3097                 (exact, Some(exact))
3098             }
3099
3100             #[inline]
3101             fn count(self) -> usize {
3102                 len!(self)
3103             }
3104
3105             #[inline]
3106             fn nth(&mut self, n: usize) -> Option<$elem> {
3107                 if n >= len!(self) {
3108                     // This iterator is now empty.
3109                     if mem::size_of::<T>() == 0 {
3110                         // We have to do it this way as `ptr` may never be 0, but `end`
3111                         // could be (due to wrapping).
3112                         self.end = self.ptr;
3113                     } else {
3114                         self.ptr = self.end;
3115                     }
3116                     return None;
3117                 }
3118                 // We are in bounds. `offset` does the right thing even for ZSTs.
3119                 unsafe {
3120                     let elem = Some(& $( $mut_ )* *self.ptr.add(n));
3121                     self.post_inc_start((n as isize).wrapping_add(1));
3122                     elem
3123                 }
3124             }
3125
3126             #[inline]
3127             fn last(mut self) -> Option<$elem> {
3128                 self.next_back()
3129             }
3130
3131             #[inline]
3132             fn try_fold<B, F, R>(&mut self, init: B, mut f: F) -> R where
3133                 Self: Sized, F: FnMut(B, Self::Item) -> R, R: Try<Ok=B>
3134             {
3135                 // manual unrolling is needed when there are conditional exits from the loop
3136                 let mut accum = init;
3137                 unsafe {
3138                     while len!(self) >= 4 {
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                         accum = f(accum, & $( $mut_ )* *self.post_inc_start(1))?;
3143                     }
3144                     while !is_empty!(self) {
3145                         accum = f(accum, & $( $mut_ )* *self.post_inc_start(1))?;
3146                     }
3147                 }
3148                 Try::from_ok(accum)
3149             }
3150
3151             #[inline]
3152             fn fold<Acc, Fold>(mut self, init: Acc, mut f: Fold) -> Acc
3153                 where Fold: FnMut(Acc, Self::Item) -> Acc,
3154             {
3155                 // Let LLVM unroll this, rather than using the default
3156                 // impl that would force the manual unrolling above
3157                 let mut accum = init;
3158                 while let Some(x) = self.next() {
3159                     accum = f(accum, x);
3160                 }
3161                 accum
3162             }
3163
3164             #[inline]
3165             #[rustc_inherit_overflow_checks]
3166             fn position<P>(&mut self, mut predicate: P) -> Option<usize> where
3167                 Self: Sized,
3168                 P: FnMut(Self::Item) -> bool,
3169             {
3170                 // The addition might panic on overflow.
3171                 let n = len!(self);
3172                 self.try_fold(0, move |i, x| {
3173                     if predicate(x) { Err(i) }
3174                     else { Ok(i + 1) }
3175                 }).err()
3176                     .map(|i| {
3177                         unsafe { assume(i < n) };
3178                         i
3179                     })
3180             }
3181
3182             #[inline]
3183             fn rposition<P>(&mut self, mut predicate: P) -> Option<usize> where
3184                 P: FnMut(Self::Item) -> bool,
3185                 Self: Sized + ExactSizeIterator + DoubleEndedIterator
3186             {
3187                 // No need for an overflow check here, because `ExactSizeIterator`
3188                 let n = len!(self);
3189                 self.try_rfold(n, move |i, x| {
3190                     let i = i - 1;
3191                     if predicate(x) { Err(i) }
3192                     else { Ok(i) }
3193                 }).err()
3194                     .map(|i| {
3195                         unsafe { assume(i < n) };
3196                         i
3197                     })
3198             }
3199
3200             $($extra)*
3201         }
3202
3203         #[stable(feature = "rust1", since = "1.0.0")]
3204         impl<'a, T> DoubleEndedIterator for $name<'a, T> {
3205             #[inline]
3206             fn next_back(&mut self) -> Option<$elem> {
3207                 // could be implemented with slices, but this avoids bounds checks
3208                 unsafe {
3209                     assume(!self.ptr.is_null());
3210                     if mem::size_of::<T>() != 0 {
3211                         assume(!self.end.is_null());
3212                     }
3213                     if is_empty!(self) {
3214                         None
3215                     } else {
3216                         Some(& $( $mut_ )* *self.pre_dec_end(1))
3217                     }
3218                 }
3219             }
3220
3221             #[inline]
3222             fn try_rfold<B, F, R>(&mut self, init: B, mut f: F) -> R where
3223                 Self: Sized, F: FnMut(B, Self::Item) -> R, R: Try<Ok=B>
3224             {
3225                 // manual unrolling is needed when there are conditional exits from the loop
3226                 let mut accum = init;
3227                 unsafe {
3228                     while len!(self) >= 4 {
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                         accum = f(accum, & $( $mut_ )* *self.pre_dec_end(1))?;
3233                     }
3234                     // inlining is_empty everywhere makes a huge performance difference
3235                     while !is_empty!(self) {
3236                         accum = f(accum, & $( $mut_ )* *self.pre_dec_end(1))?;
3237                     }
3238                 }
3239                 Try::from_ok(accum)
3240             }
3241
3242             #[inline]
3243             fn rfold<Acc, Fold>(mut self, init: Acc, mut f: Fold) -> Acc
3244                 where Fold: FnMut(Acc, Self::Item) -> Acc,
3245             {
3246                 // Let LLVM unroll this, rather than using the default
3247                 // impl that would force the manual unrolling above
3248                 let mut accum = init;
3249                 while let Some(x) = self.next_back() {
3250                     accum = f(accum, x);
3251                 }
3252                 accum
3253             }
3254         }
3255
3256         #[stable(feature = "fused", since = "1.26.0")]
3257         impl<T> FusedIterator for $name<'_, T> {}
3258
3259         #[unstable(feature = "trusted_len", issue = "37572")]
3260         unsafe impl<T> TrustedLen for $name<'_, T> {}
3261     }
3262 }
3263
3264 /// Immutable slice iterator
3265 ///
3266 /// This struct is created by the [`iter`] method on [slices].
3267 ///
3268 /// # Examples
3269 ///
3270 /// Basic usage:
3271 ///
3272 /// ```
3273 /// // First, we declare a type which has `iter` method to get the `Iter` struct (&[usize here]):
3274 /// let slice = &[1, 2, 3];
3275 ///
3276 /// // Then, we iterate over it:
3277 /// for element in slice.iter() {
3278 ///     println!("{}", element);
3279 /// }
3280 /// ```
3281 ///
3282 /// [`iter`]: ../../std/primitive.slice.html#method.iter
3283 /// [slices]: ../../std/primitive.slice.html
3284 #[stable(feature = "rust1", since = "1.0.0")]
3285 pub struct Iter<'a, T: 'a> {
3286     ptr: *const T,
3287     end: *const T, // If T is a ZST, this is actually ptr+len.  This encoding is picked so that
3288                    // ptr == end is a quick test for the Iterator being empty, that works
3289                    // for both ZST and non-ZST.
3290     _marker: marker::PhantomData<&'a T>,
3291 }
3292
3293 #[stable(feature = "core_impl_debug", since = "1.9.0")]
3294 impl<T: fmt::Debug> fmt::Debug for Iter<'_, T> {
3295     fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
3296         f.debug_tuple("Iter")
3297             .field(&self.as_slice())
3298             .finish()
3299     }
3300 }
3301
3302 #[stable(feature = "rust1", since = "1.0.0")]
3303 unsafe impl<T: Sync> Sync for Iter<'_, T> {}
3304 #[stable(feature = "rust1", since = "1.0.0")]
3305 unsafe impl<T: Sync> Send for Iter<'_, T> {}
3306
3307 impl<'a, T> Iter<'a, T> {
3308     /// Views the underlying data as a subslice of the original data.
3309     ///
3310     /// This has the same lifetime as the original slice, and so the
3311     /// iterator can continue to be used while this exists.
3312     ///
3313     /// # Examples
3314     ///
3315     /// Basic usage:
3316     ///
3317     /// ```
3318     /// // First, we declare a type which has the `iter` method to get the `Iter`
3319     /// // struct (&[usize here]):
3320     /// let slice = &[1, 2, 3];
3321     ///
3322     /// // Then, we get the iterator:
3323     /// let mut iter = slice.iter();
3324     /// // So if we print what `as_slice` method returns here, we have "[1, 2, 3]":
3325     /// println!("{:?}", iter.as_slice());
3326     ///
3327     /// // Next, we move to the second element of the slice:
3328     /// iter.next();
3329     /// // Now `as_slice` returns "[2, 3]":
3330     /// println!("{:?}", iter.as_slice());
3331     /// ```
3332     #[stable(feature = "iter_to_slice", since = "1.4.0")]
3333     pub fn as_slice(&self) -> &'a [T] {
3334         self.make_slice()
3335     }
3336 }
3337
3338 iterator!{struct Iter -> *const T, &'a T, const, {/* no mut */}, {
3339     fn is_sorted_by<F>(self, mut compare: F) -> bool
3340     where
3341         Self: Sized,
3342         F: FnMut(&Self::Item, &Self::Item) -> Option<Ordering>,
3343     {
3344         self.as_slice().windows(2).all(|w| {
3345             compare(&&w[0], &&w[1]).map(|o| o != Ordering::Greater).unwrap_or(false)
3346         })
3347     }
3348 }}
3349
3350 #[stable(feature = "rust1", since = "1.0.0")]
3351 impl<T> Clone for Iter<'_, T> {
3352     fn clone(&self) -> Self { Iter { ptr: self.ptr, end: self.end, _marker: self._marker } }
3353 }
3354
3355 #[stable(feature = "slice_iter_as_ref", since = "1.13.0")]
3356 impl<T> AsRef<[T]> for Iter<'_, T> {
3357     fn as_ref(&self) -> &[T] {
3358         self.as_slice()
3359     }
3360 }
3361
3362 /// Mutable slice iterator.
3363 ///
3364 /// This struct is created by the [`iter_mut`] method on [slices].
3365 ///
3366 /// # Examples
3367 ///
3368 /// Basic usage:
3369 ///
3370 /// ```
3371 /// // First, we declare a type which has `iter_mut` method to get the `IterMut`
3372 /// // struct (&[usize here]):
3373 /// let mut slice = &mut [1, 2, 3];
3374 ///
3375 /// // Then, we iterate over it and increment each element value:
3376 /// for element in slice.iter_mut() {
3377 ///     *element += 1;
3378 /// }
3379 ///
3380 /// // We now have "[2, 3, 4]":
3381 /// println!("{:?}", slice);
3382 /// ```
3383 ///
3384 /// [`iter_mut`]: ../../std/primitive.slice.html#method.iter_mut
3385 /// [slices]: ../../std/primitive.slice.html
3386 #[stable(feature = "rust1", since = "1.0.0")]
3387 pub struct IterMut<'a, T: 'a> {
3388     ptr: *mut T,
3389     end: *mut T, // If T is a ZST, this is actually ptr+len.  This encoding is picked so that
3390                  // ptr == end is a quick test for the Iterator being empty, that works
3391                  // for both ZST and non-ZST.
3392     _marker: marker::PhantomData<&'a mut T>,
3393 }
3394
3395 #[stable(feature = "core_impl_debug", since = "1.9.0")]
3396 impl<T: fmt::Debug> fmt::Debug for IterMut<'_, T> {
3397     fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
3398         f.debug_tuple("IterMut")
3399             .field(&self.make_slice())
3400             .finish()
3401     }
3402 }
3403
3404 #[stable(feature = "rust1", since = "1.0.0")]
3405 unsafe impl<T: Sync> Sync for IterMut<'_, T> {}
3406 #[stable(feature = "rust1", since = "1.0.0")]
3407 unsafe impl<T: Send> Send for IterMut<'_, T> {}
3408
3409 impl<'a, T> IterMut<'a, T> {
3410     /// Views the underlying data as a subslice of the original data.
3411     ///
3412     /// To avoid creating `&mut` references that alias, this is forced
3413     /// to consume the iterator.
3414     ///
3415     /// # Examples
3416     ///
3417     /// Basic usage:
3418     ///
3419     /// ```
3420     /// // First, we declare a type which has `iter_mut` method to get the `IterMut`
3421     /// // struct (&[usize here]):
3422     /// let mut slice = &mut [1, 2, 3];
3423     ///
3424     /// {
3425     ///     // Then, we get the iterator:
3426     ///     let mut iter = slice.iter_mut();
3427     ///     // We move to next element:
3428     ///     iter.next();
3429     ///     // So if we print what `into_slice` method returns here, we have "[2, 3]":
3430     ///     println!("{:?}", iter.into_slice());
3431     /// }
3432     ///
3433     /// // Now let's modify a value of the slice:
3434     /// {
3435     ///     // First we get back the iterator:
3436     ///     let mut iter = slice.iter_mut();
3437     ///     // We change the value of the first element of the slice returned by the `next` method:
3438     ///     *iter.next().unwrap() += 1;
3439     /// }
3440     /// // Now slice is "[2, 2, 3]":
3441     /// println!("{:?}", slice);
3442     /// ```
3443     #[stable(feature = "iter_to_slice", since = "1.4.0")]
3444     pub fn into_slice(self) -> &'a mut [T] {
3445         unsafe { from_raw_parts_mut(self.ptr, len!(self)) }
3446     }
3447
3448     /// Views the underlying data as a subslice of the original data.
3449     ///
3450     /// To avoid creating `&mut [T]` references that alias, the returned slice
3451     /// borrows its lifetime from the iterator the method is applied on.
3452     ///
3453     /// # Examples
3454     ///
3455     /// Basic usage:
3456     ///
3457     /// ```
3458     /// # #![feature(slice_iter_mut_as_slice)]
3459     /// let mut slice: &mut [usize] = &mut [1, 2, 3];
3460     ///
3461     /// // First, we get the iterator:
3462     /// let mut iter = slice.iter_mut();
3463     /// // So if we check what the `as_slice` method returns here, we have "[1, 2, 3]":
3464     /// assert_eq!(iter.as_slice(), &[1, 2, 3]);
3465     ///
3466     /// // Next, we move to the second element of the slice:
3467     /// iter.next();
3468     /// // Now `as_slice` returns "[2, 3]":
3469     /// assert_eq!(iter.as_slice(), &[2, 3]);
3470     /// ```
3471     #[unstable(feature = "slice_iter_mut_as_slice", reason = "recently added", issue = "58957")]
3472     pub fn as_slice(&self) -> &[T] {
3473         self.make_slice()
3474     }
3475 }
3476
3477 iterator!{struct IterMut -> *mut T, &'a mut T, mut, {mut}, {}}
3478
3479 /// An internal abstraction over the splitting iterators, so that
3480 /// splitn, splitn_mut etc can be implemented once.
3481 #[doc(hidden)]
3482 trait SplitIter: DoubleEndedIterator {
3483     /// Marks the underlying iterator as complete, extracting the remaining
3484     /// portion of the slice.
3485     fn finish(&mut self) -> Option<Self::Item>;
3486 }
3487
3488 /// An iterator over subslices separated by elements that match a predicate
3489 /// function.
3490 ///
3491 /// This struct is created by the [`split`] method on [slices].
3492 ///
3493 /// [`split`]: ../../std/primitive.slice.html#method.split
3494 /// [slices]: ../../std/primitive.slice.html
3495 #[stable(feature = "rust1", since = "1.0.0")]
3496 pub struct Split<'a, T:'a, P> where P: FnMut(&T) -> bool {
3497     v: &'a [T],
3498     pred: P,
3499     finished: bool
3500 }
3501
3502 #[stable(feature = "core_impl_debug", since = "1.9.0")]
3503 impl<T: fmt::Debug, P> fmt::Debug for Split<'_, T, P> where P: FnMut(&T) -> bool {
3504     fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
3505         f.debug_struct("Split")
3506             .field("v", &self.v)
3507             .field("finished", &self.finished)
3508             .finish()
3509     }
3510 }
3511
3512 // FIXME(#26925) Remove in favor of `#[derive(Clone)]`
3513 #[stable(feature = "rust1", since = "1.0.0")]
3514 impl<T, P> Clone for Split<'_, T, P> where P: Clone + FnMut(&T) -> bool {
3515     fn clone(&self) -> Self {
3516         Split {
3517             v: self.v,
3518             pred: self.pred.clone(),
3519             finished: self.finished,
3520         }
3521     }
3522 }
3523
3524 #[stable(feature = "rust1", since = "1.0.0")]
3525 impl<'a, T, P> Iterator for Split<'a, T, P> where P: FnMut(&T) -> bool {
3526     type Item = &'a [T];
3527
3528     #[inline]
3529     fn next(&mut self) -> Option<&'a [T]> {
3530         if self.finished { return None; }
3531
3532         match self.v.iter().position(|x| (self.pred)(x)) {
3533             None => self.finish(),
3534             Some(idx) => {
3535                 let ret = Some(&self.v[..idx]);
3536                 self.v = &self.v[idx + 1..];
3537                 ret
3538             }
3539         }
3540     }
3541
3542     #[inline]
3543     fn size_hint(&self) -> (usize, Option<usize>) {
3544         if self.finished {
3545             (0, Some(0))
3546         } else {
3547             (1, Some(self.v.len() + 1))
3548         }
3549     }
3550 }
3551
3552 #[stable(feature = "rust1", since = "1.0.0")]
3553 impl<'a, T, P> DoubleEndedIterator for Split<'a, T, P> where P: FnMut(&T) -> bool {
3554     #[inline]
3555     fn next_back(&mut self) -> Option<&'a [T]> {
3556         if self.finished { return None; }
3557
3558         match self.v.iter().rposition(|x| (self.pred)(x)) {
3559             None => self.finish(),
3560             Some(idx) => {
3561                 let ret = Some(&self.v[idx + 1..]);
3562                 self.v = &self.v[..idx];
3563                 ret
3564             }
3565         }
3566     }
3567 }
3568
3569 impl<'a, T, P> SplitIter for Split<'a, T, P> where P: FnMut(&T) -> bool {
3570     #[inline]
3571     fn finish(&mut self) -> Option<&'a [T]> {
3572         if self.finished { None } else { self.finished = true; Some(self.v) }
3573     }
3574 }
3575
3576 #[stable(feature = "fused", since = "1.26.0")]
3577 impl<T, P> FusedIterator for Split<'_, T, P> where P: FnMut(&T) -> bool {}
3578
3579 /// An iterator over the subslices of the vector which are separated
3580 /// by elements that match `pred`.
3581 ///
3582 /// This struct is created by the [`split_mut`] method on [slices].
3583 ///
3584 /// [`split_mut`]: ../../std/primitive.slice.html#method.split_mut
3585 /// [slices]: ../../std/primitive.slice.html
3586 #[stable(feature = "rust1", since = "1.0.0")]
3587 pub struct SplitMut<'a, T:'a, P> where P: FnMut(&T) -> bool {
3588     v: &'a mut [T],
3589     pred: P,
3590     finished: bool
3591 }
3592
3593 #[stable(feature = "core_impl_debug", since = "1.9.0")]
3594 impl<T: fmt::Debug, P> fmt::Debug for SplitMut<'_, T, P> where P: FnMut(&T) -> bool {
3595     fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
3596         f.debug_struct("SplitMut")
3597             .field("v", &self.v)
3598             .field("finished", &self.finished)
3599             .finish()
3600     }
3601 }
3602
3603 impl<'a, T, P> SplitIter for SplitMut<'a, T, P> where P: FnMut(&T) -> bool {
3604     #[inline]
3605     fn finish(&mut self) -> Option<&'a mut [T]> {
3606         if self.finished {
3607             None
3608         } else {
3609             self.finished = true;
3610             Some(mem::replace(&mut self.v, &mut []))
3611         }
3612     }
3613 }
3614
3615 #[stable(feature = "rust1", since = "1.0.0")]
3616 impl<'a, T, P> Iterator for SplitMut<'a, T, P> where P: FnMut(&T) -> bool {
3617     type Item = &'a mut [T];
3618
3619     #[inline]
3620     fn next(&mut self) -> Option<&'a mut [T]> {
3621         if self.finished { return None; }
3622
3623         let idx_opt = { // work around borrowck limitations
3624             let pred = &mut self.pred;
3625             self.v.iter().position(|x| (*pred)(x))
3626         };
3627         match idx_opt {
3628             None => self.finish(),
3629             Some(idx) => {
3630                 let tmp = mem::replace(&mut self.v, &mut []);
3631                 let (head, tail) = tmp.split_at_mut(idx);
3632                 self.v = &mut tail[1..];
3633                 Some(head)
3634             }
3635         }
3636     }
3637
3638     #[inline]
3639     fn size_hint(&self) -> (usize, Option<usize>) {
3640         if self.finished {
3641             (0, Some(0))
3642         } else {
3643             // if the predicate doesn't match anything, we yield one slice
3644             // if it matches every element, we yield len+1 empty slices.
3645             (1, Some(self.v.len() + 1))
3646         }
3647     }
3648 }
3649
3650 #[stable(feature = "rust1", since = "1.0.0")]
3651 impl<'a, T, P> DoubleEndedIterator for SplitMut<'a, T, P> where
3652     P: FnMut(&T) -> bool,
3653 {
3654     #[inline]
3655     fn next_back(&mut self) -> Option<&'a mut [T]> {
3656         if self.finished { return None; }
3657
3658         let idx_opt = { // work around borrowck limitations
3659             let pred = &mut self.pred;
3660             self.v.iter().rposition(|x| (*pred)(x))
3661         };
3662         match idx_opt {
3663             None => self.finish(),
3664             Some(idx) => {
3665                 let tmp = mem::replace(&mut self.v, &mut []);
3666                 let (head, tail) = tmp.split_at_mut(idx);
3667                 self.v = head;
3668                 Some(&mut tail[1..])
3669             }
3670         }
3671     }
3672 }
3673
3674 #[stable(feature = "fused", since = "1.26.0")]
3675 impl<T, P> FusedIterator for SplitMut<'_, T, P> where P: FnMut(&T) -> bool {}
3676
3677 /// An iterator over subslices separated by elements that match a predicate
3678 /// function, starting from the end of the slice.
3679 ///
3680 /// This struct is created by the [`rsplit`] method on [slices].
3681 ///
3682 /// [`rsplit`]: ../../std/primitive.slice.html#method.rsplit
3683 /// [slices]: ../../std/primitive.slice.html
3684 #[stable(feature = "slice_rsplit", since = "1.27.0")]
3685 #[derive(Clone)] // Is this correct, or does it incorrectly require `T: Clone`?
3686 pub struct RSplit<'a, T:'a, P> where P: FnMut(&T) -> bool {
3687     inner: Split<'a, T, P>
3688 }
3689
3690 #[stable(feature = "slice_rsplit", since = "1.27.0")]
3691 impl<T: fmt::Debug, P> fmt::Debug for RSplit<'_, T, P> where P: FnMut(&T) -> bool {
3692     fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
3693         f.debug_struct("RSplit")
3694             .field("v", &self.inner.v)
3695             .field("finished", &self.inner.finished)
3696             .finish()
3697     }
3698 }
3699
3700 #[stable(feature = "slice_rsplit", since = "1.27.0")]
3701 impl<'a, T, P> Iterator for RSplit<'a, T, P> where P: FnMut(&T) -> bool {
3702     type Item = &'a [T];
3703
3704     #[inline]
3705     fn next(&mut self) -> Option<&'a [T]> {
3706         self.inner.next_back()
3707     }
3708
3709     #[inline]
3710     fn size_hint(&self) -> (usize, Option<usize>) {
3711         self.inner.size_hint()
3712     }
3713 }
3714
3715 #[stable(feature = "slice_rsplit", since = "1.27.0")]
3716 impl<'a, T, P> DoubleEndedIterator for RSplit<'a, T, P> where P: FnMut(&T) -> bool {
3717     #[inline]
3718     fn next_back(&mut self) -> Option<&'a [T]> {
3719         self.inner.next()
3720     }
3721 }
3722
3723 #[stable(feature = "slice_rsplit", since = "1.27.0")]
3724 impl<'a, T, P> SplitIter for RSplit<'a, T, P> where P: FnMut(&T) -> bool {
3725     #[inline]
3726     fn finish(&mut self) -> Option<&'a [T]> {
3727         self.inner.finish()
3728     }
3729 }
3730
3731 #[stable(feature = "slice_rsplit", since = "1.27.0")]
3732 impl<T, P> FusedIterator for RSplit<'_, T, P> where P: FnMut(&T) -> bool {}
3733
3734 /// An iterator over the subslices of the vector which are separated
3735 /// by elements that match `pred`, starting from the end of the slice.
3736 ///
3737 /// This struct is created by the [`rsplit_mut`] method on [slices].
3738 ///
3739 /// [`rsplit_mut`]: ../../std/primitive.slice.html#method.rsplit_mut
3740 /// [slices]: ../../std/primitive.slice.html
3741 #[stable(feature = "slice_rsplit", since = "1.27.0")]
3742 pub struct RSplitMut<'a, T:'a, P> where P: FnMut(&T) -> bool {
3743     inner: SplitMut<'a, T, P>
3744 }
3745
3746 #[stable(feature = "slice_rsplit", since = "1.27.0")]
3747 impl<T: fmt::Debug, P> fmt::Debug for RSplitMut<'_, T, P> where P: FnMut(&T) -> bool {
3748     fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
3749         f.debug_struct("RSplitMut")
3750             .field("v", &self.inner.v)
3751             .field("finished", &self.inner.finished)
3752             .finish()
3753     }
3754 }
3755
3756 #[stable(feature = "slice_rsplit", since = "1.27.0")]
3757 impl<'a, T, P> SplitIter for RSplitMut<'a, T, P> where P: FnMut(&T) -> bool {
3758     #[inline]
3759     fn finish(&mut self) -> Option<&'a mut [T]> {
3760         self.inner.finish()
3761     }
3762 }
3763
3764 #[stable(feature = "slice_rsplit", since = "1.27.0")]
3765 impl<'a, T, P> Iterator for RSplitMut<'a, T, P> where P: FnMut(&T) -> bool {
3766     type Item = &'a mut [T];
3767
3768     #[inline]
3769     fn next(&mut self) -> Option<&'a mut [T]> {
3770         self.inner.next_back()
3771     }
3772
3773     #[inline]
3774     fn size_hint(&self) -> (usize, Option<usize>) {
3775         self.inner.size_hint()
3776     }
3777 }
3778
3779 #[stable(feature = "slice_rsplit", since = "1.27.0")]
3780 impl<'a, T, P> DoubleEndedIterator for RSplitMut<'a, T, P> where
3781     P: FnMut(&T) -> bool,
3782 {
3783     #[inline]
3784     fn next_back(&mut self) -> Option<&'a mut [T]> {
3785         self.inner.next()
3786     }
3787 }
3788
3789 #[stable(feature = "slice_rsplit", since = "1.27.0")]
3790 impl<T, P> FusedIterator for RSplitMut<'_, T, P> where P: FnMut(&T) -> bool {}
3791
3792 /// An private iterator over subslices separated by elements that
3793 /// match a predicate function, splitting at most a fixed number of
3794 /// times.
3795 #[derive(Debug)]
3796 struct GenericSplitN<I> {
3797     iter: I,
3798     count: usize,
3799 }
3800
3801 impl<T, I: SplitIter<Item=T>> Iterator for GenericSplitN<I> {
3802     type Item = T;
3803
3804     #[inline]
3805     fn next(&mut self) -> Option<T> {
3806         match self.count {
3807             0 => None,
3808             1 => { self.count -= 1; self.iter.finish() }
3809             _ => { self.count -= 1; self.iter.next() }
3810         }
3811     }
3812
3813     #[inline]
3814     fn size_hint(&self) -> (usize, Option<usize>) {
3815         let (lower, upper_opt) = self.iter.size_hint();
3816         (lower, upper_opt.map(|upper| cmp::min(self.count, upper)))
3817     }
3818 }
3819
3820 /// An iterator over subslices separated by elements that match a predicate
3821 /// function, limited to a given number of splits.
3822 ///
3823 /// This struct is created by the [`splitn`] method on [slices].
3824 ///
3825 /// [`splitn`]: ../../std/primitive.slice.html#method.splitn
3826 /// [slices]: ../../std/primitive.slice.html
3827 #[stable(feature = "rust1", since = "1.0.0")]
3828 pub struct SplitN<'a, T: 'a, P> where P: FnMut(&T) -> bool {
3829     inner: GenericSplitN<Split<'a, T, P>>
3830 }
3831
3832 #[stable(feature = "core_impl_debug", since = "1.9.0")]
3833 impl<T: fmt::Debug, P> fmt::Debug for SplitN<'_, T, P> where P: FnMut(&T) -> bool {
3834     fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
3835         f.debug_struct("SplitN")
3836             .field("inner", &self.inner)
3837             .finish()
3838     }
3839 }
3840
3841 /// An iterator over subslices separated by elements that match a
3842 /// predicate function, limited to a given number of splits, starting
3843 /// from the end of the slice.
3844 ///
3845 /// This struct is created by the [`rsplitn`] method on [slices].
3846 ///
3847 /// [`rsplitn`]: ../../std/primitive.slice.html#method.rsplitn
3848 /// [slices]: ../../std/primitive.slice.html
3849 #[stable(feature = "rust1", since = "1.0.0")]
3850 pub struct RSplitN<'a, T: 'a, P> where P: FnMut(&T) -> bool {
3851     inner: GenericSplitN<RSplit<'a, T, P>>
3852 }
3853
3854 #[stable(feature = "core_impl_debug", since = "1.9.0")]
3855 impl<T: fmt::Debug, P> fmt::Debug for RSplitN<'_, T, P> where P: FnMut(&T) -> bool {
3856     fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
3857         f.debug_struct("RSplitN")
3858             .field("inner", &self.inner)
3859             .finish()
3860     }
3861 }
3862
3863 /// An iterator over subslices separated by elements that match a predicate
3864 /// function, limited to a given number of splits.
3865 ///
3866 /// This struct is created by the [`splitn_mut`] method on [slices].
3867 ///
3868 /// [`splitn_mut`]: ../../std/primitive.slice.html#method.splitn_mut
3869 /// [slices]: ../../std/primitive.slice.html
3870 #[stable(feature = "rust1", since = "1.0.0")]
3871 pub struct SplitNMut<'a, T: 'a, P> where P: FnMut(&T) -> bool {
3872     inner: GenericSplitN<SplitMut<'a, T, P>>
3873 }
3874
3875 #[stable(feature = "core_impl_debug", since = "1.9.0")]
3876 impl<T: fmt::Debug, P> fmt::Debug for SplitNMut<'_, T, P> where P: FnMut(&T) -> bool {
3877     fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
3878         f.debug_struct("SplitNMut")
3879             .field("inner", &self.inner)
3880             .finish()
3881     }
3882 }
3883
3884 /// An iterator over subslices separated by elements that match a
3885 /// predicate function, limited to a given number of splits, starting
3886 /// from the end of the slice.
3887 ///
3888 /// This struct is created by the [`rsplitn_mut`] method on [slices].
3889 ///
3890 /// [`rsplitn_mut`]: ../../std/primitive.slice.html#method.rsplitn_mut
3891 /// [slices]: ../../std/primitive.slice.html
3892 #[stable(feature = "rust1", since = "1.0.0")]
3893 pub struct RSplitNMut<'a, T: 'a, P> where P: FnMut(&T) -> bool {
3894     inner: GenericSplitN<RSplitMut<'a, T, P>>
3895 }
3896
3897 #[stable(feature = "core_impl_debug", since = "1.9.0")]
3898 impl<T: fmt::Debug, P> fmt::Debug for RSplitNMut<'_, T, P> where P: FnMut(&T) -> bool {
3899     fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
3900         f.debug_struct("RSplitNMut")
3901             .field("inner", &self.inner)
3902             .finish()
3903     }
3904 }
3905
3906 macro_rules! forward_iterator {
3907     ($name:ident: $elem:ident, $iter_of:ty) => {
3908         #[stable(feature = "rust1", since = "1.0.0")]
3909         impl<'a, $elem, P> Iterator for $name<'a, $elem, P> where
3910             P: FnMut(&T) -> bool
3911         {
3912             type Item = $iter_of;
3913
3914             #[inline]
3915             fn next(&mut self) -> Option<$iter_of> {
3916                 self.inner.next()
3917             }
3918
3919             #[inline]
3920             fn size_hint(&self) -> (usize, Option<usize>) {
3921                 self.inner.size_hint()
3922             }
3923         }
3924
3925         #[stable(feature = "fused", since = "1.26.0")]
3926         impl<'a, $elem, P> FusedIterator for $name<'a, $elem, P>
3927             where P: FnMut(&T) -> bool {}
3928     }
3929 }
3930
3931 forward_iterator! { SplitN: T, &'a [T] }
3932 forward_iterator! { RSplitN: T, &'a [T] }
3933 forward_iterator! { SplitNMut: T, &'a mut [T] }
3934 forward_iterator! { RSplitNMut: T, &'a mut [T] }
3935
3936 /// An iterator over overlapping subslices of length `size`.
3937 ///
3938 /// This struct is created by the [`windows`] method on [slices].
3939 ///
3940 /// [`windows`]: ../../std/primitive.slice.html#method.windows
3941 /// [slices]: ../../std/primitive.slice.html
3942 #[derive(Debug)]
3943 #[stable(feature = "rust1", since = "1.0.0")]
3944 pub struct Windows<'a, T:'a> {
3945     v: &'a [T],
3946     size: usize
3947 }
3948
3949 // FIXME(#26925) Remove in favor of `#[derive(Clone)]`
3950 #[stable(feature = "rust1", since = "1.0.0")]
3951 impl<T> Clone for Windows<'_, T> {
3952     fn clone(&self) -> Self {
3953         Windows {
3954             v: self.v,
3955             size: self.size,
3956         }
3957     }
3958 }
3959
3960 #[stable(feature = "rust1", since = "1.0.0")]
3961 impl<'a, T> Iterator for Windows<'a, T> {
3962     type Item = &'a [T];
3963
3964     #[inline]
3965     fn next(&mut self) -> Option<&'a [T]> {
3966         if self.size > self.v.len() {
3967             None
3968         } else {
3969             let ret = Some(&self.v[..self.size]);
3970             self.v = &self.v[1..];
3971             ret
3972         }
3973     }
3974
3975     #[inline]
3976     fn size_hint(&self) -> (usize, Option<usize>) {
3977         if self.size > self.v.len() {
3978             (0, Some(0))
3979         } else {
3980             let size = self.v.len() - self.size + 1;
3981             (size, Some(size))
3982         }
3983     }
3984
3985     #[inline]
3986     fn count(self) -> usize {
3987         self.len()
3988     }
3989
3990     #[inline]
3991     fn nth(&mut self, n: usize) -> Option<Self::Item> {
3992         let (end, overflow) = self.size.overflowing_add(n);
3993         if end > self.v.len() || overflow {
3994             self.v = &[];
3995             None
3996         } else {
3997             let nth = &self.v[n..end];
3998             self.v = &self.v[n+1..];
3999             Some(nth)
4000         }
4001     }
4002
4003     #[inline]
4004     fn last(self) -> Option<Self::Item> {
4005         if self.size > self.v.len() {
4006             None
4007         } else {
4008             let start = self.v.len() - self.size;
4009             Some(&self.v[start..])
4010         }
4011     }
4012 }
4013
4014 #[stable(feature = "rust1", since = "1.0.0")]
4015 impl<'a, T> DoubleEndedIterator for Windows<'a, T> {
4016     #[inline]
4017     fn next_back(&mut self) -> Option<&'a [T]> {
4018         if self.size > self.v.len() {
4019             None
4020         } else {
4021             let ret = Some(&self.v[self.v.len()-self.size..]);
4022             self.v = &self.v[..self.v.len()-1];
4023             ret
4024         }
4025     }
4026
4027     #[inline]
4028     fn nth_back(&mut self, n: usize) -> Option<Self::Item> {
4029         let (end, overflow) = self.v.len().overflowing_sub(n);
4030         if end < self.size || overflow {
4031             self.v = &[];
4032             None
4033         } else {
4034             let ret = &self.v[end-self.size..end];
4035             self.v = &self.v[..end-1];
4036             Some(ret)
4037         }
4038     }
4039 }
4040
4041 #[stable(feature = "rust1", since = "1.0.0")]
4042 impl<T> ExactSizeIterator for Windows<'_, T> {}
4043
4044 #[unstable(feature = "trusted_len", issue = "37572")]
4045 unsafe impl<T> TrustedLen for Windows<'_, T> {}
4046
4047 #[stable(feature = "fused", since = "1.26.0")]
4048 impl<T> FusedIterator for Windows<'_, T> {}
4049
4050 #[doc(hidden)]
4051 unsafe impl<'a, T> TrustedRandomAccess for Windows<'a, T> {
4052     unsafe fn get_unchecked(&mut self, i: usize) -> &'a [T] {
4053         from_raw_parts(self.v.as_ptr().add(i), self.size)
4054     }
4055     fn may_have_side_effect() -> bool { false }
4056 }
4057
4058 /// An iterator over a slice in (non-overlapping) chunks (`chunk_size` elements at a
4059 /// time), starting at the beginning of the slice.
4060 ///
4061 /// When the slice len is not evenly divided by the chunk size, the last slice
4062 /// of the iteration will be the remainder.
4063 ///
4064 /// This struct is created by the [`chunks`] method on [slices].
4065 ///
4066 /// [`chunks`]: ../../std/primitive.slice.html#method.chunks
4067 /// [slices]: ../../std/primitive.slice.html
4068 #[derive(Debug)]
4069 #[stable(feature = "rust1", since = "1.0.0")]
4070 pub struct Chunks<'a, T:'a> {
4071     v: &'a [T],
4072     chunk_size: usize
4073 }
4074
4075 // FIXME(#26925) Remove in favor of `#[derive(Clone)]`
4076 #[stable(feature = "rust1", since = "1.0.0")]
4077 impl<T> Clone for Chunks<'_, T> {
4078     fn clone(&self) -> Self {
4079         Chunks {
4080             v: self.v,
4081             chunk_size: self.chunk_size,
4082         }
4083     }
4084 }
4085
4086 #[stable(feature = "rust1", since = "1.0.0")]
4087 impl<'a, T> Iterator for Chunks<'a, T> {
4088     type Item = &'a [T];
4089
4090     #[inline]
4091     fn next(&mut self) -> Option<&'a [T]> {
4092         if self.v.is_empty() {
4093             None
4094         } else {
4095             let chunksz = cmp::min(self.v.len(), self.chunk_size);
4096             let (fst, snd) = self.v.split_at(chunksz);
4097             self.v = snd;
4098             Some(fst)
4099         }
4100     }
4101
4102     #[inline]
4103     fn size_hint(&self) -> (usize, Option<usize>) {
4104         if self.v.is_empty() {
4105             (0, Some(0))
4106         } else {
4107             let n = self.v.len() / self.chunk_size;
4108             let rem = self.v.len() % self.chunk_size;
4109             let n = if rem > 0 { n+1 } else { n };
4110             (n, Some(n))
4111         }
4112     }
4113
4114     #[inline]
4115     fn count(self) -> usize {
4116         self.len()
4117     }
4118
4119     #[inline]
4120     fn nth(&mut self, n: usize) -> Option<Self::Item> {
4121         let (start, overflow) = n.overflowing_mul(self.chunk_size);
4122         if start >= self.v.len() || overflow {
4123             self.v = &[];
4124             None
4125         } else {
4126             let end = match start.checked_add(self.chunk_size) {
4127                 Some(sum) => cmp::min(self.v.len(), sum),
4128                 None => self.v.len(),
4129             };
4130             let nth = &self.v[start..end];
4131             self.v = &self.v[end..];
4132             Some(nth)
4133         }
4134     }
4135
4136     #[inline]
4137     fn last(self) -> Option<Self::Item> {
4138         if self.v.is_empty() {
4139             None
4140         } else {
4141             let start = (self.v.len() - 1) / self.chunk_size * self.chunk_size;
4142             Some(&self.v[start..])
4143         }
4144     }
4145 }
4146
4147 #[stable(feature = "rust1", since = "1.0.0")]
4148 impl<'a, T> DoubleEndedIterator for Chunks<'a, T> {
4149     #[inline]
4150     fn next_back(&mut self) -> Option<&'a [T]> {
4151         if self.v.is_empty() {
4152             None
4153         } else {
4154             let remainder = self.v.len() % self.chunk_size;
4155             let chunksz = if remainder != 0 { remainder } else { self.chunk_size };
4156             let (fst, snd) = self.v.split_at(self.v.len() - chunksz);
4157             self.v = fst;
4158             Some(snd)
4159         }
4160     }
4161
4162     #[inline]
4163     fn nth_back(&mut self, n: usize) -> Option<Self::Item> {
4164         let len = self.len();
4165         if n >= len {
4166             self.v = &[];
4167             None
4168         } else {
4169             let start = (len - 1 - n) * self.chunk_size;
4170             let end = match start.checked_add(self.chunk_size) {
4171                 Some(res) => cmp::min(res, self.v.len()),
4172                 None => self.v.len(),
4173             };
4174             let nth_back = &self.v[start..end];
4175             self.v = &self.v[..start];
4176             Some(nth_back)
4177         }
4178     }
4179 }
4180
4181 #[stable(feature = "rust1", since = "1.0.0")]
4182 impl<T> ExactSizeIterator for Chunks<'_, T> {}
4183
4184 #[unstable(feature = "trusted_len", issue = "37572")]
4185 unsafe impl<T> TrustedLen for Chunks<'_, T> {}
4186
4187 #[stable(feature = "fused", since = "1.26.0")]
4188 impl<T> FusedIterator for Chunks<'_, T> {}
4189
4190 #[doc(hidden)]
4191 unsafe impl<'a, T> TrustedRandomAccess for Chunks<'a, T> {
4192     unsafe fn get_unchecked(&mut self, i: usize) -> &'a [T] {
4193         let start = i * self.chunk_size;
4194         let end = match start.checked_add(self.chunk_size) {
4195             None => self.v.len(),
4196             Some(end) => cmp::min(end, self.v.len()),
4197         };
4198         from_raw_parts(self.v.as_ptr().add(start), end - start)
4199     }
4200     fn may_have_side_effect() -> bool { false }
4201 }
4202
4203 /// An iterator over a slice in (non-overlapping) mutable chunks (`chunk_size`
4204 /// elements at a time), starting at the beginning of the slice.
4205 ///
4206 /// When the slice len is not evenly divided by the chunk size, the last slice
4207 /// of the iteration will be the remainder.
4208 ///
4209 /// This struct is created by the [`chunks_mut`] method on [slices].
4210 ///
4211 /// [`chunks_mut`]: ../../std/primitive.slice.html#method.chunks_mut
4212 /// [slices]: ../../std/primitive.slice.html
4213 #[derive(Debug)]
4214 #[stable(feature = "rust1", since = "1.0.0")]
4215 pub struct ChunksMut<'a, T:'a> {
4216     v: &'a mut [T],
4217     chunk_size: usize
4218 }
4219
4220 #[stable(feature = "rust1", since = "1.0.0")]
4221 impl<'a, T> Iterator for ChunksMut<'a, T> {
4222     type Item = &'a mut [T];
4223
4224     #[inline]
4225     fn next(&mut self) -> Option<&'a mut [T]> {
4226         if self.v.is_empty() {
4227             None
4228         } else {
4229             let sz = cmp::min(self.v.len(), self.chunk_size);
4230             let tmp = mem::replace(&mut self.v, &mut []);
4231             let (head, tail) = tmp.split_at_mut(sz);
4232             self.v = tail;
4233             Some(head)
4234         }
4235     }
4236
4237     #[inline]
4238     fn size_hint(&self) -> (usize, Option<usize>) {
4239         if self.v.is_empty() {
4240             (0, Some(0))
4241         } else {
4242             let n = self.v.len() / self.chunk_size;
4243             let rem = self.v.len() % self.chunk_size;
4244             let n = if rem > 0 { n + 1 } else { n };
4245             (n, Some(n))
4246         }
4247     }
4248
4249     #[inline]
4250     fn count(self) -> usize {
4251         self.len()
4252     }
4253
4254     #[inline]
4255     fn nth(&mut self, n: usize) -> Option<&'a mut [T]> {
4256         let (start, overflow) = n.overflowing_mul(self.chunk_size);
4257         if start >= self.v.len() || overflow {
4258             self.v = &mut [];
4259             None
4260         } else {
4261             let end = match start.checked_add(self.chunk_size) {
4262                 Some(sum) => cmp::min(self.v.len(), sum),
4263                 None => self.v.len(),
4264             };
4265             let tmp = mem::replace(&mut self.v, &mut []);
4266             let (head, tail) = tmp.split_at_mut(end);
4267             let (_, nth) =  head.split_at_mut(start);
4268             self.v = tail;
4269             Some(nth)
4270         }
4271     }
4272
4273     #[inline]
4274     fn last(self) -> Option<Self::Item> {
4275         if self.v.is_empty() {
4276             None
4277         } else {
4278             let start = (self.v.len() - 1) / self.chunk_size * self.chunk_size;
4279             Some(&mut self.v[start..])
4280         }
4281     }
4282 }
4283
4284 #[stable(feature = "rust1", since = "1.0.0")]
4285 impl<'a, T> DoubleEndedIterator for ChunksMut<'a, T> {
4286     #[inline]
4287     fn next_back(&mut self) -> Option<&'a mut [T]> {
4288         if self.v.is_empty() {
4289             None
4290         } else {
4291             let remainder = self.v.len() % self.chunk_size;
4292             let sz = if remainder != 0 { remainder } else { self.chunk_size };
4293             let tmp = mem::replace(&mut self.v, &mut []);
4294             let tmp_len = tmp.len();
4295             let (head, tail) = tmp.split_at_mut(tmp_len - sz);
4296             self.v = head;
4297             Some(tail)
4298         }
4299     }
4300 }
4301
4302 #[stable(feature = "rust1", since = "1.0.0")]
4303 impl<T> ExactSizeIterator for ChunksMut<'_, T> {}
4304
4305 #[unstable(feature = "trusted_len", issue = "37572")]
4306 unsafe impl<T> TrustedLen for ChunksMut<'_, T> {}
4307
4308 #[stable(feature = "fused", since = "1.26.0")]
4309 impl<T> FusedIterator for ChunksMut<'_, T> {}
4310
4311 #[doc(hidden)]
4312 unsafe impl<'a, T> TrustedRandomAccess for ChunksMut<'a, T> {
4313     unsafe fn get_unchecked(&mut self, i: usize) -> &'a mut [T] {
4314         let start = i * self.chunk_size;
4315         let end = match start.checked_add(self.chunk_size) {
4316             None => self.v.len(),
4317             Some(end) => cmp::min(end, self.v.len()),
4318         };
4319         from_raw_parts_mut(self.v.as_mut_ptr().add(start), end - start)
4320     }
4321     fn may_have_side_effect() -> bool { false }
4322 }
4323
4324 /// An iterator over a slice in (non-overlapping) chunks (`chunk_size` elements at a
4325 /// time), starting at the beginning of the slice.
4326 ///
4327 /// When the slice len is not evenly divided by the chunk size, the last
4328 /// up to `chunk_size-1` elements will be omitted but can be retrieved from
4329 /// the [`remainder`] function from the iterator.
4330 ///
4331 /// This struct is created by the [`chunks_exact`] method on [slices].
4332 ///
4333 /// [`chunks_exact`]: ../../std/primitive.slice.html#method.chunks_exact
4334 /// [`remainder`]: ../../std/slice/struct.ChunksExact.html#method.remainder
4335 /// [slices]: ../../std/primitive.slice.html
4336 #[derive(Debug)]
4337 #[stable(feature = "chunks_exact", since = "1.31.0")]
4338 pub struct ChunksExact<'a, T:'a> {
4339     v: &'a [T],
4340     rem: &'a [T],
4341     chunk_size: usize
4342 }
4343
4344 impl<'a, T> ChunksExact<'a, T> {
4345     /// Returns the remainder of the original slice that is not going to be
4346     /// returned by the iterator. The returned slice has at most `chunk_size-1`
4347     /// elements.
4348     #[stable(feature = "chunks_exact", since = "1.31.0")]
4349     pub fn remainder(&self) -> &'a [T] {
4350         self.rem
4351     }
4352 }
4353
4354 // FIXME(#26925) Remove in favor of `#[derive(Clone)]`
4355 #[stable(feature = "chunks_exact", since = "1.31.0")]
4356 impl<T> Clone for ChunksExact<'_, T> {
4357     fn clone(&self) -> Self {
4358         ChunksExact {
4359             v: self.v,
4360             rem: self.rem,
4361             chunk_size: self.chunk_size,
4362         }
4363     }
4364 }
4365
4366 #[stable(feature = "chunks_exact", since = "1.31.0")]
4367 impl<'a, T> Iterator for ChunksExact<'a, T> {
4368     type Item = &'a [T];
4369
4370     #[inline]
4371     fn next(&mut self) -> Option<&'a [T]> {
4372         if self.v.len() < self.chunk_size {
4373             None
4374         } else {
4375             let (fst, snd) = self.v.split_at(self.chunk_size);
4376             self.v = snd;
4377             Some(fst)
4378         }
4379     }
4380
4381     #[inline]
4382     fn size_hint(&self) -> (usize, Option<usize>) {
4383         let n = self.v.len() / self.chunk_size;
4384         (n, Some(n))
4385     }
4386
4387     #[inline]
4388     fn count(self) -> usize {
4389         self.len()
4390     }
4391
4392     #[inline]
4393     fn nth(&mut self, n: usize) -> Option<Self::Item> {
4394         let (start, overflow) = n.overflowing_mul(self.chunk_size);
4395         if start >= self.v.len() || overflow {
4396             self.v = &[];
4397             None
4398         } else {
4399             let (_, snd) = self.v.split_at(start);
4400             self.v = snd;
4401             self.next()
4402         }
4403     }
4404
4405     #[inline]
4406     fn last(mut self) -> Option<Self::Item> {
4407         self.next_back()
4408     }
4409 }
4410
4411 #[stable(feature = "chunks_exact", since = "1.31.0")]
4412 impl<'a, T> DoubleEndedIterator for ChunksExact<'a, T> {
4413     #[inline]
4414     fn next_back(&mut self) -> Option<&'a [T]> {
4415         if self.v.len() < self.chunk_size {
4416             None
4417         } else {
4418             let (fst, snd) = self.v.split_at(self.v.len() - self.chunk_size);
4419             self.v = fst;
4420             Some(snd)
4421         }
4422     }
4423 }
4424
4425 #[stable(feature = "chunks_exact", since = "1.31.0")]
4426 impl<T> ExactSizeIterator for ChunksExact<'_, T> {
4427     fn is_empty(&self) -> bool {
4428         self.v.is_empty()
4429     }
4430 }
4431
4432 #[unstable(feature = "trusted_len", issue = "37572")]
4433 unsafe impl<T> TrustedLen for ChunksExact<'_, T> {}
4434
4435 #[stable(feature = "chunks_exact", since = "1.31.0")]
4436 impl<T> FusedIterator for ChunksExact<'_, T> {}
4437
4438 #[doc(hidden)]
4439 #[stable(feature = "chunks_exact", since = "1.31.0")]
4440 unsafe impl<'a, T> TrustedRandomAccess for ChunksExact<'a, T> {
4441     unsafe fn get_unchecked(&mut self, i: usize) -> &'a [T] {
4442         let start = i * self.chunk_size;
4443         from_raw_parts(self.v.as_ptr().add(start), self.chunk_size)
4444     }
4445     fn may_have_side_effect() -> bool { false }
4446 }
4447
4448 /// An iterator over a slice in (non-overlapping) mutable chunks (`chunk_size`
4449 /// elements at a time), starting at the beginning of the slice.
4450 ///
4451 /// When the slice len is not evenly divided by the chunk size, the last up to
4452 /// `chunk_size-1` elements will be omitted but can be retrieved from the
4453 /// [`into_remainder`] function from the iterator.
4454 ///
4455 /// This struct is created by the [`chunks_exact_mut`] method on [slices].
4456 ///
4457 /// [`chunks_exact_mut`]: ../../std/primitive.slice.html#method.chunks_exact_mut
4458 /// [`into_remainder`]: ../../std/slice/struct.ChunksExactMut.html#method.into_remainder
4459 /// [slices]: ../../std/primitive.slice.html
4460 #[derive(Debug)]
4461 #[stable(feature = "chunks_exact", since = "1.31.0")]
4462 pub struct ChunksExactMut<'a, T:'a> {
4463     v: &'a mut [T],
4464     rem: &'a mut [T],
4465     chunk_size: usize
4466 }
4467
4468 impl<'a, T> ChunksExactMut<'a, T> {
4469     /// Returns the remainder of the original slice that is not going to be
4470     /// returned by the iterator. The returned slice has at most `chunk_size-1`
4471     /// elements.
4472     #[stable(feature = "chunks_exact", since = "1.31.0")]
4473     pub fn into_remainder(self) -> &'a mut [T] {
4474         self.rem
4475     }
4476 }
4477
4478 #[stable(feature = "chunks_exact", since = "1.31.0")]
4479 impl<'a, T> Iterator for ChunksExactMut<'a, T> {
4480     type Item = &'a mut [T];
4481
4482     #[inline]
4483     fn next(&mut self) -> Option<&'a mut [T]> {
4484         if self.v.len() < self.chunk_size {
4485             None
4486         } else {
4487             let tmp = mem::replace(&mut self.v, &mut []);
4488             let (head, tail) = tmp.split_at_mut(self.chunk_size);
4489             self.v = tail;
4490             Some(head)
4491         }
4492     }
4493
4494     #[inline]
4495     fn size_hint(&self) -> (usize, Option<usize>) {
4496         let n = self.v.len() / self.chunk_size;
4497         (n, Some(n))
4498     }
4499
4500     #[inline]
4501     fn count(self) -> usize {
4502         self.len()
4503     }
4504
4505     #[inline]
4506     fn nth(&mut self, n: usize) -> Option<&'a mut [T]> {
4507         let (start, overflow) = n.overflowing_mul(self.chunk_size);
4508         if start >= self.v.len() || overflow {
4509             self.v = &mut [];
4510             None
4511         } else {
4512             let tmp = mem::replace(&mut self.v, &mut []);
4513             let (_, snd) = tmp.split_at_mut(start);
4514             self.v = snd;
4515             self.next()
4516         }
4517     }
4518
4519     #[inline]
4520     fn last(mut self) -> Option<Self::Item> {
4521         self.next_back()
4522     }
4523 }
4524
4525 #[stable(feature = "chunks_exact", since = "1.31.0")]
4526 impl<'a, T> DoubleEndedIterator for ChunksExactMut<'a, T> {
4527     #[inline]
4528     fn next_back(&mut self) -> Option<&'a mut [T]> {
4529         if self.v.len() < self.chunk_size {
4530             None
4531         } else {
4532             let tmp = mem::replace(&mut self.v, &mut []);
4533             let tmp_len = tmp.len();
4534             let (head, tail) = tmp.split_at_mut(tmp_len - self.chunk_size);
4535             self.v = head;
4536             Some(tail)
4537         }
4538     }
4539 }
4540
4541 #[stable(feature = "chunks_exact", since = "1.31.0")]
4542 impl<T> ExactSizeIterator for ChunksExactMut<'_, T> {
4543     fn is_empty(&self) -> bool {
4544         self.v.is_empty()
4545     }
4546 }
4547
4548 #[unstable(feature = "trusted_len", issue = "37572")]
4549 unsafe impl<T> TrustedLen for ChunksExactMut<'_, T> {}
4550
4551 #[stable(feature = "chunks_exact", since = "1.31.0")]
4552 impl<T> FusedIterator for ChunksExactMut<'_, T> {}
4553
4554 #[doc(hidden)]
4555 #[stable(feature = "chunks_exact", since = "1.31.0")]
4556 unsafe impl<'a, T> TrustedRandomAccess for ChunksExactMut<'a, T> {
4557     unsafe fn get_unchecked(&mut self, i: usize) -> &'a mut [T] {
4558         let start = i * self.chunk_size;
4559         from_raw_parts_mut(self.v.as_mut_ptr().add(start), self.chunk_size)
4560     }
4561     fn may_have_side_effect() -> bool { false }
4562 }
4563
4564 /// An iterator over a slice in (non-overlapping) chunks (`chunk_size` elements at a
4565 /// time), starting at the end of the slice.
4566 ///
4567 /// When the slice len is not evenly divided by the chunk size, the last slice
4568 /// of the iteration will be the remainder.
4569 ///
4570 /// This struct is created by the [`rchunks`] method on [slices].
4571 ///
4572 /// [`rchunks`]: ../../std/primitive.slice.html#method.rchunks
4573 /// [slices]: ../../std/primitive.slice.html
4574 #[derive(Debug)]
4575 #[stable(feature = "rchunks", since = "1.31.0")]
4576 pub struct RChunks<'a, T:'a> {
4577     v: &'a [T],
4578     chunk_size: usize
4579 }
4580
4581 // FIXME(#26925) Remove in favor of `#[derive(Clone)]`
4582 #[stable(feature = "rchunks", since = "1.31.0")]
4583 impl<T> Clone for RChunks<'_, T> {
4584     fn clone(&self) -> Self {
4585         RChunks {
4586             v: self.v,
4587             chunk_size: self.chunk_size,
4588         }
4589     }
4590 }
4591
4592 #[stable(feature = "rchunks", since = "1.31.0")]
4593 impl<'a, T> Iterator for RChunks<'a, T> {
4594     type Item = &'a [T];
4595
4596     #[inline]
4597     fn next(&mut self) -> Option<&'a [T]> {
4598         if self.v.is_empty() {
4599             None
4600         } else {
4601             let chunksz = cmp::min(self.v.len(), self.chunk_size);
4602             let (fst, snd) = self.v.split_at(self.v.len() - chunksz);
4603             self.v = fst;
4604             Some(snd)
4605         }
4606     }
4607
4608     #[inline]
4609     fn size_hint(&self) -> (usize, Option<usize>) {
4610         if self.v.is_empty() {
4611             (0, Some(0))
4612         } else {
4613             let n = self.v.len() / self.chunk_size;
4614             let rem = self.v.len() % self.chunk_size;
4615             let n = if rem > 0 { n+1 } else { n };
4616             (n, Some(n))
4617         }
4618     }
4619
4620     #[inline]
4621     fn count(self) -> usize {
4622         self.len()
4623     }
4624
4625     #[inline]
4626     fn nth(&mut self, n: usize) -> Option<Self::Item> {
4627         let (end, overflow) = n.overflowing_mul(self.chunk_size);
4628         if end >= self.v.len() || overflow {
4629             self.v = &[];
4630             None
4631         } else {
4632             // Can't underflow because of the check above
4633             let end = self.v.len() - end;
4634             let start = match end.checked_sub(self.chunk_size) {
4635                 Some(sum) => sum,
4636                 None => 0,
4637             };
4638             let nth = &self.v[start..end];
4639             self.v = &self.v[0..start];
4640             Some(nth)
4641         }
4642     }
4643
4644     #[inline]
4645     fn last(self) -> Option<Self::Item> {
4646         if self.v.is_empty() {
4647             None
4648         } else {
4649             let rem = self.v.len() % self.chunk_size;
4650             let end = if rem == 0 { self.chunk_size } else { rem };
4651             Some(&self.v[0..end])
4652         }
4653     }
4654 }
4655
4656 #[stable(feature = "rchunks", since = "1.31.0")]
4657 impl<'a, T> DoubleEndedIterator for RChunks<'a, T> {
4658     #[inline]
4659     fn next_back(&mut self) -> Option<&'a [T]> {
4660         if self.v.is_empty() {
4661             None
4662         } else {
4663             let remainder = self.v.len() % self.chunk_size;
4664             let chunksz = if remainder != 0 { remainder } else { self.chunk_size };
4665             let (fst, snd) = self.v.split_at(chunksz);
4666             self.v = snd;
4667             Some(fst)
4668         }
4669     }
4670
4671     #[inline]
4672     fn nth_back(&mut self, n: usize) -> Option<Self::Item> {
4673         let len = self.len();
4674         if n >= len {
4675             self.v = &[];
4676             None
4677         } else {
4678             // can't underflow because `n < len`
4679             let offset_from_end = (len - 1 - n) * self.chunk_size;
4680             let end = self.v.len() - offset_from_end;
4681             let start = end.saturating_sub(self.chunk_size);
4682             let nth_back = &self.v[start..end];
4683             self.v = &self.v[end..];
4684             Some(nth_back)
4685         }
4686     }
4687 }
4688
4689 #[stable(feature = "rchunks", since = "1.31.0")]
4690 impl<T> ExactSizeIterator for RChunks<'_, T> {}
4691
4692 #[unstable(feature = "trusted_len", issue = "37572")]
4693 unsafe impl<T> TrustedLen for RChunks<'_, T> {}
4694
4695 #[stable(feature = "rchunks", since = "1.31.0")]
4696 impl<T> FusedIterator for RChunks<'_, T> {}
4697
4698 #[doc(hidden)]
4699 #[stable(feature = "rchunks", since = "1.31.0")]
4700 unsafe impl<'a, T> TrustedRandomAccess for RChunks<'a, T> {
4701     unsafe fn get_unchecked(&mut self, i: usize) -> &'a [T] {
4702         let end = self.v.len() - i * self.chunk_size;
4703         let start = match end.checked_sub(self.chunk_size) {
4704             None => 0,
4705             Some(start) => start,
4706         };
4707         from_raw_parts(self.v.as_ptr().add(start), end - start)
4708     }
4709     fn may_have_side_effect() -> bool { false }
4710 }
4711
4712 /// An iterator over a slice in (non-overlapping) mutable chunks (`chunk_size`
4713 /// elements at a time), starting at the end of the slice.
4714 ///
4715 /// When the slice len is not evenly divided by the chunk size, the last slice
4716 /// of the iteration will be the remainder.
4717 ///
4718 /// This struct is created by the [`rchunks_mut`] method on [slices].
4719 ///
4720 /// [`rchunks_mut`]: ../../std/primitive.slice.html#method.rchunks_mut
4721 /// [slices]: ../../std/primitive.slice.html
4722 #[derive(Debug)]
4723 #[stable(feature = "rchunks", since = "1.31.0")]
4724 pub struct RChunksMut<'a, T:'a> {
4725     v: &'a mut [T],
4726     chunk_size: usize
4727 }
4728
4729 #[stable(feature = "rchunks", since = "1.31.0")]
4730 impl<'a, T> Iterator for RChunksMut<'a, T> {
4731     type Item = &'a mut [T];
4732
4733     #[inline]
4734     fn next(&mut self) -> Option<&'a mut [T]> {
4735         if self.v.is_empty() {
4736             None
4737         } else {
4738             let sz = cmp::min(self.v.len(), self.chunk_size);
4739             let tmp = mem::replace(&mut self.v, &mut []);
4740             let tmp_len = tmp.len();
4741             let (head, tail) = tmp.split_at_mut(tmp_len - sz);
4742             self.v = head;
4743             Some(tail)
4744         }
4745     }
4746
4747     #[inline]
4748     fn size_hint(&self) -> (usize, Option<usize>) {
4749         if self.v.is_empty() {
4750             (0, Some(0))
4751         } else {
4752             let n = self.v.len() / self.chunk_size;
4753             let rem = self.v.len() % self.chunk_size;
4754             let n = if rem > 0 { n + 1 } else { n };
4755             (n, Some(n))
4756         }
4757     }
4758
4759     #[inline]
4760     fn count(self) -> usize {
4761         self.len()
4762     }
4763
4764     #[inline]
4765     fn nth(&mut self, n: usize) -> Option<&'a mut [T]> {
4766         let (end, overflow) = n.overflowing_mul(self.chunk_size);
4767         if end >= self.v.len() || overflow {
4768             self.v = &mut [];
4769             None
4770         } else {
4771             // Can't underflow because of the check above
4772             let end = self.v.len() - end;
4773             let start = match end.checked_sub(self.chunk_size) {
4774                 Some(sum) => sum,
4775                 None => 0,
4776             };
4777             let tmp = mem::replace(&mut self.v, &mut []);
4778             let (head, tail) = tmp.split_at_mut(start);
4779             let (nth, _) = tail.split_at_mut(end - start);
4780             self.v = head;
4781             Some(nth)
4782         }
4783     }
4784
4785     #[inline]
4786     fn last(self) -> Option<Self::Item> {
4787         if self.v.is_empty() {
4788             None
4789         } else {
4790             let rem = self.v.len() % self.chunk_size;
4791             let end = if rem == 0 { self.chunk_size } else { rem };
4792             Some(&mut self.v[0..end])
4793         }
4794     }
4795 }
4796
4797 #[stable(feature = "rchunks", since = "1.31.0")]
4798 impl<'a, T> DoubleEndedIterator for RChunksMut<'a, T> {
4799     #[inline]
4800     fn next_back(&mut self) -> Option<&'a mut [T]> {
4801         if self.v.is_empty() {
4802             None
4803         } else {
4804             let remainder = self.v.len() % self.chunk_size;
4805             let sz = if remainder != 0 { remainder } else { self.chunk_size };
4806             let tmp = mem::replace(&mut self.v, &mut []);
4807             let (head, tail) = tmp.split_at_mut(sz);
4808             self.v = tail;
4809             Some(head)
4810         }
4811     }
4812
4813     #[inline]
4814     fn nth_back(&mut self, n: usize) -> Option<Self::Item> {
4815         let len = self.len();
4816         if n >= len {
4817             self.v = &mut [];
4818             None
4819         } else {
4820             // can't underflow because `n < len`
4821             let offset_from_end = (len - 1 - n) * self.chunk_size;
4822             let end = self.v.len() - offset_from_end;
4823             let start = end.saturating_sub(self.chunk_size);
4824             let (tmp, tail) = mem::replace(&mut self.v, &mut []).split_at_mut(end);
4825             let (_, nth_back) = tmp.split_at_mut(start);
4826             self.v = tail;
4827             Some(nth_back)
4828         }
4829     }
4830 }
4831
4832 #[stable(feature = "rchunks", since = "1.31.0")]
4833 impl<T> ExactSizeIterator for RChunksMut<'_, T> {}
4834
4835 #[unstable(feature = "trusted_len", issue = "37572")]
4836 unsafe impl<T> TrustedLen for RChunksMut<'_, T> {}
4837
4838 #[stable(feature = "rchunks", since = "1.31.0")]
4839 impl<T> FusedIterator for RChunksMut<'_, T> {}
4840
4841 #[doc(hidden)]
4842 #[stable(feature = "rchunks", since = "1.31.0")]
4843 unsafe impl<'a, T> TrustedRandomAccess for RChunksMut<'a, T> {
4844     unsafe fn get_unchecked(&mut self, i: usize) -> &'a mut [T] {
4845         let end = self.v.len() - i * self.chunk_size;
4846         let start = match end.checked_sub(self.chunk_size) {
4847             None => 0,
4848             Some(start) => start,
4849         };
4850         from_raw_parts_mut(self.v.as_mut_ptr().add(start), end - start)
4851     }
4852     fn may_have_side_effect() -> bool { false }
4853 }
4854
4855 /// An iterator over a slice in (non-overlapping) chunks (`chunk_size` elements at a
4856 /// time), starting at the end of the slice.
4857 ///
4858 /// When the slice len is not evenly divided by the chunk size, the last
4859 /// up to `chunk_size-1` elements will be omitted but can be retrieved from
4860 /// the [`remainder`] function from the iterator.
4861 ///
4862 /// This struct is created by the [`rchunks_exact`] method on [slices].
4863 ///
4864 /// [`rchunks_exact`]: ../../std/primitive.slice.html#method.rchunks_exact
4865 /// [`remainder`]: ../../std/slice/struct.ChunksExact.html#method.remainder
4866 /// [slices]: ../../std/primitive.slice.html
4867 #[derive(Debug)]
4868 #[stable(feature = "rchunks", since = "1.31.0")]
4869 pub struct RChunksExact<'a, T:'a> {
4870     v: &'a [T],
4871     rem: &'a [T],
4872     chunk_size: usize
4873 }
4874
4875 impl<'a, T> RChunksExact<'a, T> {
4876     /// Returns the remainder of the original slice that is not going to be
4877     /// returned by the iterator. The returned slice has at most `chunk_size-1`
4878     /// elements.
4879     #[stable(feature = "rchunks", since = "1.31.0")]
4880     pub fn remainder(&self) -> &'a [T] {
4881         self.rem
4882     }
4883 }
4884
4885 // FIXME(#26925) Remove in favor of `#[derive(Clone)]`
4886 #[stable(feature = "rchunks", since = "1.31.0")]
4887 impl<'a, T> Clone for RChunksExact<'a, T> {
4888     fn clone(&self) -> RChunksExact<'a, T> {
4889         RChunksExact {
4890             v: self.v,
4891             rem: self.rem,
4892             chunk_size: self.chunk_size,
4893         }
4894     }
4895 }
4896
4897 #[stable(feature = "rchunks", since = "1.31.0")]
4898 impl<'a, T> Iterator for RChunksExact<'a, T> {
4899     type Item = &'a [T];
4900
4901     #[inline]
4902     fn next(&mut self) -> Option<&'a [T]> {
4903         if self.v.len() < self.chunk_size {
4904             None
4905         } else {
4906             let (fst, snd) = self.v.split_at(self.v.len() - self.chunk_size);
4907             self.v = fst;
4908             Some(snd)
4909         }
4910     }
4911
4912     #[inline]
4913     fn size_hint(&self) -> (usize, Option<usize>) {
4914         let n = self.v.len() / self.chunk_size;
4915         (n, Some(n))
4916     }
4917
4918     #[inline]
4919     fn count(self) -> usize {
4920         self.len()
4921     }
4922
4923     #[inline]
4924     fn nth(&mut self, n: usize) -> Option<Self::Item> {
4925         let (end, overflow) = n.overflowing_mul(self.chunk_size);
4926         if end >= self.v.len() || overflow {
4927             self.v = &[];
4928             None
4929         } else {
4930             let (fst, _) = self.v.split_at(self.v.len() - end);
4931             self.v = fst;
4932             self.next()
4933         }
4934     }
4935
4936     #[inline]
4937     fn last(mut self) -> Option<Self::Item> {
4938         self.next_back()
4939     }
4940 }
4941
4942 #[stable(feature = "rchunks", since = "1.31.0")]
4943 impl<'a, T> DoubleEndedIterator for RChunksExact<'a, T> {
4944     #[inline]
4945     fn next_back(&mut self) -> Option<&'a [T]> {
4946         if self.v.len() < self.chunk_size {
4947             None
4948         } else {
4949             let (fst, snd) = self.v.split_at(self.chunk_size);
4950             self.v = snd;
4951             Some(fst)
4952         }
4953     }
4954
4955     #[inline]
4956     fn nth_back(&mut self, n: usize) -> Option<Self::Item> {
4957         let len = self.len();
4958         if n >= len {
4959             self.v = &[];
4960             None
4961         } else {
4962             // now that we know that `n` corresponds to a chunk,
4963             // none of these operations can underflow/overflow
4964             let offset = (len - n) * self.chunk_size;
4965             let start = self.v.len() - offset;
4966             let end = start + self.chunk_size;
4967             let nth_back = &self.v[start..end];
4968             self.v = &self.v[end..];
4969             Some(nth_back)
4970         }
4971     }
4972 }
4973
4974 #[stable(feature = "rchunks", since = "1.31.0")]
4975 impl<'a, T> ExactSizeIterator for RChunksExact<'a, T> {
4976     fn is_empty(&self) -> bool {
4977         self.v.is_empty()
4978     }
4979 }
4980
4981 #[unstable(feature = "trusted_len", issue = "37572")]
4982 unsafe impl<T> TrustedLen for RChunksExact<'_, T> {}
4983
4984 #[stable(feature = "rchunks", since = "1.31.0")]
4985 impl<T> FusedIterator for RChunksExact<'_, T> {}
4986
4987 #[doc(hidden)]
4988 #[stable(feature = "rchunks", since = "1.31.0")]
4989 unsafe impl<'a, T> TrustedRandomAccess for RChunksExact<'a, T> {
4990     unsafe fn get_unchecked(&mut self, i: usize) -> &'a [T] {
4991         let end = self.v.len() - i * self.chunk_size;
4992         let start = end - self.chunk_size;
4993         from_raw_parts(self.v.as_ptr().add(start), self.chunk_size)
4994     }
4995     fn may_have_side_effect() -> bool { false }
4996 }
4997
4998 /// An iterator over a slice in (non-overlapping) mutable chunks (`chunk_size`
4999 /// elements at a time), starting at the end of the slice.
5000 ///
5001 /// When the slice len is not evenly divided by the chunk size, the last up to
5002 /// `chunk_size-1` elements will be omitted but can be retrieved from the
5003 /// [`into_remainder`] function from the iterator.
5004 ///
5005 /// This struct is created by the [`rchunks_exact_mut`] method on [slices].
5006 ///
5007 /// [`rchunks_exact_mut`]: ../../std/primitive.slice.html#method.rchunks_exact_mut
5008 /// [`into_remainder`]: ../../std/slice/struct.ChunksExactMut.html#method.into_remainder
5009 /// [slices]: ../../std/primitive.slice.html
5010 #[derive(Debug)]
5011 #[stable(feature = "rchunks", since = "1.31.0")]
5012 pub struct RChunksExactMut<'a, T:'a> {
5013     v: &'a mut [T],
5014     rem: &'a mut [T],
5015     chunk_size: usize
5016 }
5017
5018 impl<'a, T> RChunksExactMut<'a, T> {
5019     /// Returns the remainder of the original slice that is not going to be
5020     /// returned by the iterator. The returned slice has at most `chunk_size-1`
5021     /// elements.
5022     #[stable(feature = "rchunks", since = "1.31.0")]
5023     pub fn into_remainder(self) -> &'a mut [T] {
5024         self.rem
5025     }
5026 }
5027
5028 #[stable(feature = "rchunks", since = "1.31.0")]
5029 impl<'a, T> Iterator for RChunksExactMut<'a, T> {
5030     type Item = &'a mut [T];
5031
5032     #[inline]
5033     fn next(&mut self) -> Option<&'a mut [T]> {
5034         if self.v.len() < self.chunk_size {
5035             None
5036         } else {
5037             let tmp = mem::replace(&mut self.v, &mut []);
5038             let tmp_len = tmp.len();
5039             let (head, tail) = tmp.split_at_mut(tmp_len - self.chunk_size);
5040             self.v = head;
5041             Some(tail)
5042         }
5043     }
5044
5045     #[inline]
5046     fn size_hint(&self) -> (usize, Option<usize>) {
5047         let n = self.v.len() / self.chunk_size;
5048         (n, Some(n))
5049     }
5050
5051     #[inline]
5052     fn count(self) -> usize {
5053         self.len()
5054     }
5055
5056     #[inline]
5057     fn nth(&mut self, n: usize) -> Option<&'a mut [T]> {
5058         let (end, overflow) = n.overflowing_mul(self.chunk_size);
5059         if end >= self.v.len() || overflow {
5060             self.v = &mut [];
5061             None
5062         } else {
5063             let tmp = mem::replace(&mut self.v, &mut []);
5064             let tmp_len = tmp.len();
5065             let (fst, _) = tmp.split_at_mut(tmp_len - end);
5066             self.v = fst;
5067             self.next()
5068         }
5069     }
5070
5071     #[inline]
5072     fn last(mut self) -> Option<Self::Item> {
5073         self.next_back()
5074     }
5075 }
5076
5077 #[stable(feature = "rchunks", since = "1.31.0")]
5078 impl<'a, T> DoubleEndedIterator for RChunksExactMut<'a, T> {
5079     #[inline]
5080     fn next_back(&mut self) -> Option<&'a mut [T]> {
5081         if self.v.len() < self.chunk_size {
5082             None
5083         } else {
5084             let tmp = mem::replace(&mut self.v, &mut []);
5085             let (head, tail) = tmp.split_at_mut(self.chunk_size);
5086             self.v = tail;
5087             Some(head)
5088         }
5089     }
5090
5091     #[inline]
5092     fn nth_back(&mut self, n: usize) -> Option<Self::Item> {
5093         let len = self.len();
5094         if n >= len {
5095             self.v = &mut [];
5096             None
5097         } else {
5098             // now that we know that `n` corresponds to a chunk,
5099             // none of these operations can underflow/overflow
5100             let offset = (len - n) * self.chunk_size;
5101             let start = self.v.len() - offset;
5102             let end = start + self.chunk_size;
5103             let (tmp, tail) = mem::replace(&mut self.v, &mut []).split_at_mut(end);
5104             let (_, nth_back) = tmp.split_at_mut(start);
5105             self.v = tail;
5106             Some(nth_back)
5107         }
5108     }
5109 }
5110
5111 #[stable(feature = "rchunks", since = "1.31.0")]
5112 impl<T> ExactSizeIterator for RChunksExactMut<'_, T> {
5113     fn is_empty(&self) -> bool {
5114         self.v.is_empty()
5115     }
5116 }
5117
5118 #[unstable(feature = "trusted_len", issue = "37572")]
5119 unsafe impl<T> TrustedLen for RChunksExactMut<'_, T> {}
5120
5121 #[stable(feature = "rchunks", since = "1.31.0")]
5122 impl<T> FusedIterator for RChunksExactMut<'_, T> {}
5123
5124 #[doc(hidden)]
5125 #[stable(feature = "rchunks", since = "1.31.0")]
5126 unsafe impl<'a, T> TrustedRandomAccess for RChunksExactMut<'a, T> {
5127     unsafe fn get_unchecked(&mut self, i: usize) -> &'a mut [T] {
5128         let end = self.v.len() - i * self.chunk_size;
5129         let start = end - self.chunk_size;
5130         from_raw_parts_mut(self.v.as_mut_ptr().add(start), self.chunk_size)
5131     }
5132     fn may_have_side_effect() -> bool { false }
5133 }
5134
5135 //
5136 // Free functions
5137 //
5138
5139 /// Forms a slice from a pointer and a length.
5140 ///
5141 /// The `len` argument is the number of **elements**, not the number of bytes.
5142 ///
5143 /// # Safety
5144 ///
5145 /// This function is unsafe as there is no guarantee that the given pointer is
5146 /// valid for `len` elements, nor whether the lifetime inferred is a suitable
5147 /// lifetime for the returned slice.
5148 ///
5149 /// `data` must be non-null and aligned, even for zero-length slices. One
5150 /// reason for this is that enum layout optimizations may rely on references
5151 /// (including slices of any length) being aligned and non-null to distinguish
5152 /// them from other data. You can obtain a pointer that is usable as `data`
5153 /// for zero-length slices using [`NonNull::dangling()`].
5154 ///
5155 /// The total size of the slice must be no larger than `isize::MAX` **bytes**
5156 /// in memory. See the safety documentation of [`pointer::offset`].
5157 ///
5158 /// # Caveat
5159 ///
5160 /// The lifetime for the returned slice is inferred from its usage. To
5161 /// prevent accidental misuse, it's suggested to tie the lifetime to whichever
5162 /// source lifetime is safe in the context, such as by providing a helper
5163 /// function taking the lifetime of a host value for the slice, or by explicit
5164 /// annotation.
5165 ///
5166 /// # Examples
5167 ///
5168 /// ```
5169 /// use std::slice;
5170 ///
5171 /// // manifest a slice for a single element
5172 /// let x = 42;
5173 /// let ptr = &x as *const _;
5174 /// let slice = unsafe { slice::from_raw_parts(ptr, 1) };
5175 /// assert_eq!(slice[0], 42);
5176 /// ```
5177 ///
5178 /// [`NonNull::dangling()`]: ../../std/ptr/struct.NonNull.html#method.dangling
5179 /// [`pointer::offset`]: ../../std/primitive.pointer.html#method.offset
5180 #[inline]
5181 #[stable(feature = "rust1", since = "1.0.0")]
5182 pub unsafe fn from_raw_parts<'a, T>(data: *const T, len: usize) -> &'a [T] {
5183     debug_assert!(data as usize % mem::align_of::<T>() == 0, "attempt to create unaligned slice");
5184     debug_assert!(mem::size_of::<T>().saturating_mul(len) <= isize::MAX as usize,
5185                   "attempt to create slice covering half the address space");
5186     Repr { raw: FatPtr { data, len } }.rust
5187 }
5188
5189 /// Performs the same functionality as [`from_raw_parts`], except that a
5190 /// mutable slice is returned.
5191 ///
5192 /// This function is unsafe for the same reasons as [`from_raw_parts`], as well
5193 /// as not being able to provide a non-aliasing guarantee of the returned
5194 /// mutable slice. `data` must be non-null and aligned even for zero-length
5195 /// slices as with [`from_raw_parts`]. The total size of the slice must be no
5196 /// larger than `isize::MAX` **bytes** in memory.
5197 ///
5198 /// See the documentation of [`from_raw_parts`] for more details.
5199 ///
5200 /// [`from_raw_parts`]: ../../std/slice/fn.from_raw_parts.html
5201 #[inline]
5202 #[stable(feature = "rust1", since = "1.0.0")]
5203 pub unsafe fn from_raw_parts_mut<'a, T>(data: *mut T, len: usize) -> &'a mut [T] {
5204     debug_assert!(data as usize % mem::align_of::<T>() == 0, "attempt to create unaligned slice");
5205     debug_assert!(mem::size_of::<T>().saturating_mul(len) <= isize::MAX as usize,
5206                   "attempt to create slice covering half the address space");
5207     Repr { raw: FatPtr { data, len } }.rust_mut
5208 }
5209
5210 /// Converts a reference to T into a slice of length 1 (without copying).
5211 #[stable(feature = "from_ref", since = "1.28.0")]
5212 pub fn from_ref<T>(s: &T) -> &[T] {
5213     unsafe {
5214         from_raw_parts(s, 1)
5215     }
5216 }
5217
5218 /// Converts a reference to T into a slice of length 1 (without copying).
5219 #[stable(feature = "from_ref", since = "1.28.0")]
5220 pub fn from_mut<T>(s: &mut T) -> &mut [T] {
5221     unsafe {
5222         from_raw_parts_mut(s, 1)
5223     }
5224 }
5225
5226 // This function is public only because there is no other way to unit test heapsort.
5227 #[unstable(feature = "sort_internals", reason = "internal to sort module", issue = "0")]
5228 #[doc(hidden)]
5229 pub fn heapsort<T, F>(v: &mut [T], mut is_less: F)
5230     where F: FnMut(&T, &T) -> bool
5231 {
5232     sort::heapsort(v, &mut is_less);
5233 }
5234
5235 //
5236 // Comparison traits
5237 //
5238
5239 extern {
5240     /// Calls implementation provided memcmp.
5241     ///
5242     /// Interprets the data as u8.
5243     ///
5244     /// Returns 0 for equal, < 0 for less than and > 0 for greater
5245     /// than.
5246     // FIXME(#32610): Return type should be c_int
5247     fn memcmp(s1: *const u8, s2: *const u8, n: usize) -> i32;
5248 }
5249
5250 #[stable(feature = "rust1", since = "1.0.0")]
5251 impl<A, B> PartialEq<[B]> for [A] where A: PartialEq<B> {
5252     fn eq(&self, other: &[B]) -> bool {
5253         SlicePartialEq::equal(self, other)
5254     }
5255
5256     fn ne(&self, other: &[B]) -> bool {
5257         SlicePartialEq::not_equal(self, other)
5258     }
5259 }
5260
5261 #[stable(feature = "rust1", since = "1.0.0")]
5262 impl<T: Eq> Eq for [T] {}
5263
5264 /// Implements comparison of vectors lexicographically.
5265 #[stable(feature = "rust1", since = "1.0.0")]
5266 impl<T: Ord> Ord for [T] {
5267     fn cmp(&self, other: &[T]) -> Ordering {
5268         SliceOrd::compare(self, other)
5269     }
5270 }
5271
5272 /// Implements comparison of vectors lexicographically.
5273 #[stable(feature = "rust1", since = "1.0.0")]
5274 impl<T: PartialOrd> PartialOrd for [T] {
5275     fn partial_cmp(&self, other: &[T]) -> Option<Ordering> {
5276         SlicePartialOrd::partial_compare(self, other)
5277     }
5278 }
5279
5280 #[doc(hidden)]
5281 // intermediate trait for specialization of slice's PartialEq
5282 trait SlicePartialEq<B> {
5283     fn equal(&self, other: &[B]) -> bool;
5284
5285     fn not_equal(&self, other: &[B]) -> bool { !self.equal(other) }
5286 }
5287
5288 // Generic slice equality
5289 impl<A, B> SlicePartialEq<B> for [A]
5290     where A: PartialEq<B>
5291 {
5292     default fn equal(&self, other: &[B]) -> bool {
5293         if self.len() != other.len() {
5294             return false;
5295         }
5296
5297         for i in 0..self.len() {
5298             if !self[i].eq(&other[i]) {
5299                 return false;
5300             }
5301         }
5302
5303         true
5304     }
5305 }
5306
5307 // Use memcmp for bytewise equality when the types allow
5308 impl<A> SlicePartialEq<A> for [A]
5309     where A: PartialEq<A> + BytewiseEquality
5310 {
5311     fn equal(&self, other: &[A]) -> bool {
5312         if self.len() != other.len() {
5313             return false;
5314         }
5315         if self.as_ptr() == other.as_ptr() {
5316             return true;
5317         }
5318         unsafe {
5319             let size = mem::size_of_val(self);
5320             memcmp(self.as_ptr() as *const u8,
5321                    other.as_ptr() as *const u8, size) == 0
5322         }
5323     }
5324 }
5325
5326 #[doc(hidden)]
5327 // intermediate trait for specialization of slice's PartialOrd
5328 trait SlicePartialOrd<B> {
5329     fn partial_compare(&self, other: &[B]) -> Option<Ordering>;
5330 }
5331
5332 impl<A> SlicePartialOrd<A> for [A]
5333     where A: PartialOrd
5334 {
5335     default fn partial_compare(&self, other: &[A]) -> Option<Ordering> {
5336         let l = cmp::min(self.len(), other.len());
5337
5338         // Slice to the loop iteration range to enable bound check
5339         // elimination in the compiler
5340         let lhs = &self[..l];
5341         let rhs = &other[..l];
5342
5343         for i in 0..l {
5344             match lhs[i].partial_cmp(&rhs[i]) {
5345                 Some(Ordering::Equal) => (),
5346                 non_eq => return non_eq,
5347             }
5348         }
5349
5350         self.len().partial_cmp(&other.len())
5351     }
5352 }
5353
5354 impl<A> SlicePartialOrd<A> for [A]
5355     where A: Ord
5356 {
5357     default fn partial_compare(&self, other: &[A]) -> Option<Ordering> {
5358         Some(SliceOrd::compare(self, other))
5359     }
5360 }
5361
5362 #[doc(hidden)]
5363 // intermediate trait for specialization of slice's Ord
5364 trait SliceOrd<B> {
5365     fn compare(&self, other: &[B]) -> Ordering;
5366 }
5367
5368 impl<A> SliceOrd<A> for [A]
5369     where A: Ord
5370 {
5371     default fn compare(&self, other: &[A]) -> Ordering {
5372         let l = cmp::min(self.len(), other.len());
5373
5374         // Slice to the loop iteration range to enable bound check
5375         // elimination in the compiler
5376         let lhs = &self[..l];
5377         let rhs = &other[..l];
5378
5379         for i in 0..l {
5380             match lhs[i].cmp(&rhs[i]) {
5381                 Ordering::Equal => (),
5382                 non_eq => return non_eq,
5383             }
5384         }
5385
5386         self.len().cmp(&other.len())
5387     }
5388 }
5389
5390 // memcmp compares a sequence of unsigned bytes lexicographically.
5391 // this matches the order we want for [u8], but no others (not even [i8]).
5392 impl SliceOrd<u8> for [u8] {
5393     #[inline]
5394     fn compare(&self, other: &[u8]) -> Ordering {
5395         let order = unsafe {
5396             memcmp(self.as_ptr(), other.as_ptr(),
5397                    cmp::min(self.len(), other.len()))
5398         };
5399         if order == 0 {
5400             self.len().cmp(&other.len())
5401         } else if order < 0 {
5402             Less
5403         } else {
5404             Greater
5405         }
5406     }
5407 }
5408
5409 #[doc(hidden)]
5410 /// Trait implemented for types that can be compared for equality using
5411 /// their bytewise representation
5412 trait BytewiseEquality { }
5413
5414 macro_rules! impl_marker_for {
5415     ($traitname:ident, $($ty:ty)*) => {
5416         $(
5417             impl $traitname for $ty { }
5418         )*
5419     }
5420 }
5421
5422 impl_marker_for!(BytewiseEquality,
5423                  u8 i8 u16 i16 u32 i32 u64 i64 u128 i128 usize isize char bool);
5424
5425 #[doc(hidden)]
5426 unsafe impl<'a, T> TrustedRandomAccess for Iter<'a, T> {
5427     unsafe fn get_unchecked(&mut self, i: usize) -> &'a T {
5428         &*self.ptr.add(i)
5429     }
5430     fn may_have_side_effect() -> bool { false }
5431 }
5432
5433 #[doc(hidden)]
5434 unsafe impl<'a, T> TrustedRandomAccess for IterMut<'a, T> {
5435     unsafe fn get_unchecked(&mut self, i: usize) -> &'a mut T {
5436         &mut *self.ptr.add(i)
5437     }
5438     fn may_have_side_effect() -> bool { false }
5439 }
5440
5441 trait SliceContains: Sized {
5442     fn slice_contains(&self, x: &[Self]) -> bool;
5443 }
5444
5445 impl<T> SliceContains for T where T: PartialEq {
5446     default fn slice_contains(&self, x: &[Self]) -> bool {
5447         x.iter().any(|y| *y == *self)
5448     }
5449 }
5450
5451 impl SliceContains for u8 {
5452     fn slice_contains(&self, x: &[Self]) -> bool {
5453         memchr::memchr(*self, x).is_some()
5454     }
5455 }
5456
5457 impl SliceContains for i8 {
5458     fn slice_contains(&self, x: &[Self]) -> bool {
5459         let byte = *self as u8;
5460         let bytes: &[u8] = unsafe { from_raw_parts(x.as_ptr() as *const u8, x.len()) };
5461         memchr::memchr(byte, bytes).is_some()
5462     }
5463 }