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