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