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