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