]> git.lizzy.rs Git - rust.git/blob - src/libcore/slice/mod.rs
Add riscv64gc-unknown-none-elf target
[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 cmp::Ordering::{self, Less, Equal, Greater};
24 use cmp;
25 use fmt;
26 use intrinsics::assume;
27 use isize;
28 use iter::*;
29 use ops::{FnMut, Try, self};
30 use option::Option;
31 use option::Option::{None, Some};
32 use result::Result;
33 use result::Result::{Ok, Err};
34 use ptr;
35 use mem;
36 use 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     /// beginning 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 of the 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 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     /// # Examples
1567     ///
1568     /// ```
1569     /// let mut v = [-5i32, 4, 1, -3, 2];
1570     ///
1571     /// v.sort_unstable_by_key(|k| k.abs());
1572     /// assert!(v == [1, 2, -3, 4, -5]);
1573     /// ```
1574     ///
1575     /// [pdqsort]: https://github.com/orlp/pdqsort
1576     #[stable(feature = "sort_unstable", since = "1.20.0")]
1577     #[inline]
1578     pub fn sort_unstable_by_key<K, F>(&mut self, mut f: F)
1579         where F: FnMut(&T) -> K, K: Ord
1580     {
1581         sort::quicksort(self, |a, b| f(a).lt(&f(b)));
1582     }
1583
1584     /// Moves all consecutive repeated elements to the end of the slice according to the
1585     /// [`PartialEq`] trait implementation.
1586     ///
1587     /// Returns two slices. The first contains no consecutive repeated elements.
1588     /// The second contains all the duplicates in no specified order.
1589     ///
1590     /// If the slice is sorted, the first returned slice contains no duplicates.
1591     ///
1592     /// # Examples
1593     ///
1594     /// ```
1595     /// #![feature(slice_partition_dedup)]
1596     ///
1597     /// let mut slice = [1, 2, 2, 3, 3, 2, 1, 1];
1598     ///
1599     /// let (dedup, duplicates) = slice.partition_dedup();
1600     ///
1601     /// assert_eq!(dedup, [1, 2, 3, 2, 1]);
1602     /// assert_eq!(duplicates, [2, 3, 1]);
1603     /// ```
1604     #[unstable(feature = "slice_partition_dedup", issue = "54279")]
1605     #[inline]
1606     pub fn partition_dedup(&mut self) -> (&mut [T], &mut [T])
1607         where T: PartialEq
1608     {
1609         self.partition_dedup_by(|a, b| a == b)
1610     }
1611
1612     /// Moves all but the first of consecutive elements to the end of the slice satisfying
1613     /// a given equality relation.
1614     ///
1615     /// Returns two slices. The first contains no consecutive repeated elements.
1616     /// The second contains all the duplicates in no specified order.
1617     ///
1618     /// The `same_bucket` function is passed references to two elements from the slice and
1619     /// must determine if the elements compare equal. The elements are passed in opposite order
1620     /// from their order in the slice, so if `same_bucket(a, b)` returns `true`, `a` is moved
1621     /// at the end of the slice.
1622     ///
1623     /// If the slice is sorted, the first returned slice contains no duplicates.
1624     ///
1625     /// # Examples
1626     ///
1627     /// ```
1628     /// #![feature(slice_partition_dedup)]
1629     ///
1630     /// let mut slice = ["foo", "Foo", "BAZ", "Bar", "bar", "baz", "BAZ"];
1631     ///
1632     /// let (dedup, duplicates) = slice.partition_dedup_by(|a, b| a.eq_ignore_ascii_case(b));
1633     ///
1634     /// assert_eq!(dedup, ["foo", "BAZ", "Bar", "baz"]);
1635     /// assert_eq!(duplicates, ["bar", "Foo", "BAZ"]);
1636     /// ```
1637     #[unstable(feature = "slice_partition_dedup", issue = "54279")]
1638     #[inline]
1639     pub fn partition_dedup_by<F>(&mut self, mut same_bucket: F) -> (&mut [T], &mut [T])
1640         where F: FnMut(&mut T, &mut T) -> bool
1641     {
1642         // Although we have a mutable reference to `self`, we cannot make
1643         // *arbitrary* changes. The `same_bucket` calls could panic, so we
1644         // must ensure that the slice is in a valid state at all times.
1645         //
1646         // The way that we handle this is by using swaps; we iterate
1647         // over all the elements, swapping as we go so that at the end
1648         // the elements we wish to keep are in the front, and those we
1649         // wish to reject are at the back. We can then split the slice.
1650         // This operation is still O(n).
1651         //
1652         // Example: We start in this state, where `r` represents "next
1653         // read" and `w` represents "next_write`.
1654         //
1655         //           r
1656         //     +---+---+---+---+---+---+
1657         //     | 0 | 1 | 1 | 2 | 3 | 3 |
1658         //     +---+---+---+---+---+---+
1659         //           w
1660         //
1661         // Comparing self[r] against self[w-1], this is not a duplicate, so
1662         // we swap self[r] and self[w] (no effect as r==w) and then increment both
1663         // r and w, leaving us with:
1664         //
1665         //               r
1666         //     +---+---+---+---+---+---+
1667         //     | 0 | 1 | 1 | 2 | 3 | 3 |
1668         //     +---+---+---+---+---+---+
1669         //               w
1670         //
1671         // Comparing self[r] against self[w-1], this value is a duplicate,
1672         // so we increment `r` but leave everything else unchanged:
1673         //
1674         //                   r
1675         //     +---+---+---+---+---+---+
1676         //     | 0 | 1 | 1 | 2 | 3 | 3 |
1677         //     +---+---+---+---+---+---+
1678         //               w
1679         //
1680         // Comparing self[r] against self[w-1], this is not a duplicate,
1681         // so swap self[r] and self[w] and advance r and w:
1682         //
1683         //                       r
1684         //     +---+---+---+---+---+---+
1685         //     | 0 | 1 | 2 | 1 | 3 | 3 |
1686         //     +---+---+---+---+---+---+
1687         //                   w
1688         //
1689         // Not a duplicate, repeat:
1690         //
1691         //                           r
1692         //     +---+---+---+---+---+---+
1693         //     | 0 | 1 | 2 | 3 | 1 | 3 |
1694         //     +---+---+---+---+---+---+
1695         //                       w
1696         //
1697         // Duplicate, advance r. End of slice. Split at w.
1698
1699         let len = self.len();
1700         if len <= 1 {
1701             return (self, &mut [])
1702         }
1703
1704         let ptr = self.as_mut_ptr();
1705         let mut next_read: usize = 1;
1706         let mut next_write: usize = 1;
1707
1708         unsafe {
1709             // Avoid bounds checks by using raw pointers.
1710             while next_read < len {
1711                 let ptr_read = ptr.add(next_read);
1712                 let prev_ptr_write = ptr.add(next_write - 1);
1713                 if !same_bucket(&mut *ptr_read, &mut *prev_ptr_write) {
1714                     if next_read != next_write {
1715                         let ptr_write = prev_ptr_write.offset(1);
1716                         mem::swap(&mut *ptr_read, &mut *ptr_write);
1717                     }
1718                     next_write += 1;
1719                 }
1720                 next_read += 1;
1721             }
1722         }
1723
1724         self.split_at_mut(next_write)
1725     }
1726
1727     /// Moves all but the first of consecutive elements to the end of the slice that resolve
1728     /// to the same key.
1729     ///
1730     /// Returns two slices. The first contains no consecutive repeated elements.
1731     /// The second contains all the duplicates in no specified order.
1732     ///
1733     /// If the slice is sorted, the first returned slice contains no duplicates.
1734     ///
1735     /// # Examples
1736     ///
1737     /// ```
1738     /// #![feature(slice_partition_dedup)]
1739     ///
1740     /// let mut slice = [10, 20, 21, 30, 30, 20, 11, 13];
1741     ///
1742     /// let (dedup, duplicates) = slice.partition_dedup_by_key(|i| *i / 10);
1743     ///
1744     /// assert_eq!(dedup, [10, 20, 30, 20, 11]);
1745     /// assert_eq!(duplicates, [21, 30, 13]);
1746     /// ```
1747     #[unstable(feature = "slice_partition_dedup", issue = "54279")]
1748     #[inline]
1749     pub fn partition_dedup_by_key<K, F>(&mut self, mut key: F) -> (&mut [T], &mut [T])
1750         where F: FnMut(&mut T) -> K,
1751               K: PartialEq,
1752     {
1753         self.partition_dedup_by(|a, b| key(a) == key(b))
1754     }
1755
1756     /// Rotates the slice in-place such that the first `mid` elements of the
1757     /// slice move to the end while the last `self.len() - mid` elements move to
1758     /// the front. After calling `rotate_left`, the element previously at index
1759     /// `mid` will become the first element in the slice.
1760     ///
1761     /// # Panics
1762     ///
1763     /// This function will panic if `mid` is greater than the length of the
1764     /// slice. Note that `mid == self.len()` does _not_ panic and is a no-op
1765     /// rotation.
1766     ///
1767     /// # Complexity
1768     ///
1769     /// Takes linear (in `self.len()`) time.
1770     ///
1771     /// # Examples
1772     ///
1773     /// ```
1774     /// let mut a = ['a', 'b', 'c', 'd', 'e', 'f'];
1775     /// a.rotate_left(2);
1776     /// assert_eq!(a, ['c', 'd', 'e', 'f', 'a', 'b']);
1777     /// ```
1778     ///
1779     /// Rotating a subslice:
1780     ///
1781     /// ```
1782     /// let mut a = ['a', 'b', 'c', 'd', 'e', 'f'];
1783     /// a[1..5].rotate_left(1);
1784     /// assert_eq!(a, ['a', 'c', 'd', 'e', 'b', 'f']);
1785     /// ```
1786     #[stable(feature = "slice_rotate", since = "1.26.0")]
1787     pub fn rotate_left(&mut self, mid: usize) {
1788         assert!(mid <= self.len());
1789         let k = self.len() - mid;
1790
1791         unsafe {
1792             let p = self.as_mut_ptr();
1793             rotate::ptr_rotate(mid, p.add(mid), k);
1794         }
1795     }
1796
1797     /// Rotates the slice in-place such that the first `self.len() - k`
1798     /// elements of the slice move to the end while the last `k` elements move
1799     /// to the front. After calling `rotate_right`, the element previously at
1800     /// index `self.len() - k` will become the first element in the slice.
1801     ///
1802     /// # Panics
1803     ///
1804     /// This function will panic if `k` is greater than the length of the
1805     /// slice. Note that `k == self.len()` does _not_ panic and is a no-op
1806     /// rotation.
1807     ///
1808     /// # Complexity
1809     ///
1810     /// Takes linear (in `self.len()`) time.
1811     ///
1812     /// # Examples
1813     ///
1814     /// ```
1815     /// let mut a = ['a', 'b', 'c', 'd', 'e', 'f'];
1816     /// a.rotate_right(2);
1817     /// assert_eq!(a, ['e', 'f', 'a', 'b', 'c', 'd']);
1818     /// ```
1819     ///
1820     /// Rotate a subslice:
1821     ///
1822     /// ```
1823     /// let mut a = ['a', 'b', 'c', 'd', 'e', 'f'];
1824     /// a[1..5].rotate_right(1);
1825     /// assert_eq!(a, ['a', 'e', 'b', 'c', 'd', 'f']);
1826     /// ```
1827     #[stable(feature = "slice_rotate", since = "1.26.0")]
1828     pub fn rotate_right(&mut self, k: usize) {
1829         assert!(k <= self.len());
1830         let mid = self.len() - k;
1831
1832         unsafe {
1833             let p = self.as_mut_ptr();
1834             rotate::ptr_rotate(mid, p.add(mid), k);
1835         }
1836     }
1837
1838     /// Copies the elements from `src` into `self`.
1839     ///
1840     /// The length of `src` must be the same as `self`.
1841     ///
1842     /// If `src` implements `Copy`, it can be more performant to use
1843     /// [`copy_from_slice`].
1844     ///
1845     /// # Panics
1846     ///
1847     /// This function will panic if the two slices have different lengths.
1848     ///
1849     /// # Examples
1850     ///
1851     /// Cloning two elements from a slice into another:
1852     ///
1853     /// ```
1854     /// let src = [1, 2, 3, 4];
1855     /// let mut dst = [0, 0];
1856     ///
1857     /// // Because the slices have to be the same length,
1858     /// // we slice the source slice from four elements
1859     /// // to two. It will panic if we don't do this.
1860     /// dst.clone_from_slice(&src[2..]);
1861     ///
1862     /// assert_eq!(src, [1, 2, 3, 4]);
1863     /// assert_eq!(dst, [3, 4]);
1864     /// ```
1865     ///
1866     /// Rust enforces that there can only be one mutable reference with no
1867     /// immutable references to a particular piece of data in a particular
1868     /// scope. Because of this, attempting to use `clone_from_slice` on a
1869     /// single slice will result in a compile failure:
1870     ///
1871     /// ```compile_fail
1872     /// let mut slice = [1, 2, 3, 4, 5];
1873     ///
1874     /// slice[..2].clone_from_slice(&slice[3..]); // compile fail!
1875     /// ```
1876     ///
1877     /// To work around this, we can use [`split_at_mut`] to create two distinct
1878     /// sub-slices from a slice:
1879     ///
1880     /// ```
1881     /// let mut slice = [1, 2, 3, 4, 5];
1882     ///
1883     /// {
1884     ///     let (left, right) = slice.split_at_mut(2);
1885     ///     left.clone_from_slice(&right[1..]);
1886     /// }
1887     ///
1888     /// assert_eq!(slice, [4, 5, 3, 4, 5]);
1889     /// ```
1890     ///
1891     /// [`copy_from_slice`]: #method.copy_from_slice
1892     /// [`split_at_mut`]: #method.split_at_mut
1893     #[stable(feature = "clone_from_slice", since = "1.7.0")]
1894     pub fn clone_from_slice(&mut self, src: &[T]) where T: Clone {
1895         assert!(self.len() == src.len(),
1896                 "destination and source slices have different lengths");
1897         // NOTE: We need to explicitly slice them to the same length
1898         // for bounds checking to be elided, and the optimizer will
1899         // generate memcpy for simple cases (for example T = u8).
1900         let len = self.len();
1901         let src = &src[..len];
1902         for i in 0..len {
1903             self[i].clone_from(&src[i]);
1904         }
1905
1906     }
1907
1908     /// Copies all elements from `src` into `self`, using a memcpy.
1909     ///
1910     /// The length of `src` must be the same as `self`.
1911     ///
1912     /// If `src` does not implement `Copy`, use [`clone_from_slice`].
1913     ///
1914     /// # Panics
1915     ///
1916     /// This function will panic if the two slices have different lengths.
1917     ///
1918     /// # Examples
1919     ///
1920     /// Copying two elements from a slice into another:
1921     ///
1922     /// ```
1923     /// let src = [1, 2, 3, 4];
1924     /// let mut dst = [0, 0];
1925     ///
1926     /// // Because the slices have to be the same length,
1927     /// // we slice the source slice from four elements
1928     /// // to two. It will panic if we don't do this.
1929     /// dst.copy_from_slice(&src[2..]);
1930     ///
1931     /// assert_eq!(src, [1, 2, 3, 4]);
1932     /// assert_eq!(dst, [3, 4]);
1933     /// ```
1934     ///
1935     /// Rust enforces that there can only be one mutable reference with no
1936     /// immutable references to a particular piece of data in a particular
1937     /// scope. Because of this, attempting to use `copy_from_slice` on a
1938     /// single slice will result in a compile failure:
1939     ///
1940     /// ```compile_fail
1941     /// let mut slice = [1, 2, 3, 4, 5];
1942     ///
1943     /// slice[..2].copy_from_slice(&slice[3..]); // compile fail!
1944     /// ```
1945     ///
1946     /// To work around this, we can use [`split_at_mut`] to create two distinct
1947     /// sub-slices from a slice:
1948     ///
1949     /// ```
1950     /// let mut slice = [1, 2, 3, 4, 5];
1951     ///
1952     /// {
1953     ///     let (left, right) = slice.split_at_mut(2);
1954     ///     left.copy_from_slice(&right[1..]);
1955     /// }
1956     ///
1957     /// assert_eq!(slice, [4, 5, 3, 4, 5]);
1958     /// ```
1959     ///
1960     /// [`clone_from_slice`]: #method.clone_from_slice
1961     /// [`split_at_mut`]: #method.split_at_mut
1962     #[stable(feature = "copy_from_slice", since = "1.9.0")]
1963     pub fn copy_from_slice(&mut self, src: &[T]) where T: Copy {
1964         assert_eq!(self.len(), src.len(),
1965                    "destination and source slices have different lengths");
1966         unsafe {
1967             ptr::copy_nonoverlapping(
1968                 src.as_ptr(), self.as_mut_ptr(), self.len());
1969         }
1970     }
1971
1972     /// Copies elements from one part of the slice to another part of itself,
1973     /// using a memmove.
1974     ///
1975     /// `src` is the range within `self` to copy from. `dest` is the starting
1976     /// index of the range within `self` to copy to, which will have the same
1977     /// length as `src`. The two ranges may overlap. The ends of the two ranges
1978     /// must be less than or equal to `self.len()`.
1979     ///
1980     /// # Panics
1981     ///
1982     /// This function will panic if either range exceeds the end of the slice,
1983     /// or if the end of `src` is before the start.
1984     ///
1985     /// # Examples
1986     ///
1987     /// Copying four bytes within a slice:
1988     ///
1989     /// ```
1990     /// # #![feature(copy_within)]
1991     /// let mut bytes = *b"Hello, World!";
1992     ///
1993     /// bytes.copy_within(1..5, 8);
1994     ///
1995     /// assert_eq!(&bytes, b"Hello, Wello!");
1996     /// ```
1997     #[unstable(feature = "copy_within", issue = "54236")]
1998     pub fn copy_within<R: ops::RangeBounds<usize>>(&mut self, src: R, dest: usize)
1999     where
2000         T: Copy,
2001     {
2002         let src_start = match src.start_bound() {
2003             ops::Bound::Included(&n) => n,
2004             ops::Bound::Excluded(&n) => n
2005                 .checked_add(1)
2006                 .unwrap_or_else(|| slice_index_overflow_fail()),
2007             ops::Bound::Unbounded => 0,
2008         };
2009         let src_end = match src.end_bound() {
2010             ops::Bound::Included(&n) => n
2011                 .checked_add(1)
2012                 .unwrap_or_else(|| slice_index_overflow_fail()),
2013             ops::Bound::Excluded(&n) => n,
2014             ops::Bound::Unbounded => self.len(),
2015         };
2016         assert!(src_start <= src_end, "src end is before src start");
2017         assert!(src_end <= self.len(), "src is out of bounds");
2018         let count = src_end - src_start;
2019         assert!(dest <= self.len() - count, "dest is out of bounds");
2020         unsafe {
2021             ptr::copy(
2022                 self.get_unchecked(src_start),
2023                 self.get_unchecked_mut(dest),
2024                 count,
2025             );
2026         }
2027     }
2028
2029     /// Swaps all elements in `self` with those in `other`.
2030     ///
2031     /// The length of `other` must be the same as `self`.
2032     ///
2033     /// # Panics
2034     ///
2035     /// This function will panic if the two slices have different lengths.
2036     ///
2037     /// # Example
2038     ///
2039     /// Swapping two elements across slices:
2040     ///
2041     /// ```
2042     /// let mut slice1 = [0, 0];
2043     /// let mut slice2 = [1, 2, 3, 4];
2044     ///
2045     /// slice1.swap_with_slice(&mut slice2[2..]);
2046     ///
2047     /// assert_eq!(slice1, [3, 4]);
2048     /// assert_eq!(slice2, [1, 2, 0, 0]);
2049     /// ```
2050     ///
2051     /// Rust enforces that there can only be one mutable reference to a
2052     /// particular piece of data in a particular scope. Because of this,
2053     /// attempting to use `swap_with_slice` on a single slice will result in
2054     /// a compile failure:
2055     ///
2056     /// ```compile_fail
2057     /// let mut slice = [1, 2, 3, 4, 5];
2058     /// slice[..2].swap_with_slice(&mut slice[3..]); // compile fail!
2059     /// ```
2060     ///
2061     /// To work around this, we can use [`split_at_mut`] to create two distinct
2062     /// mutable sub-slices from a slice:
2063     ///
2064     /// ```
2065     /// let mut slice = [1, 2, 3, 4, 5];
2066     ///
2067     /// {
2068     ///     let (left, right) = slice.split_at_mut(2);
2069     ///     left.swap_with_slice(&mut right[1..]);
2070     /// }
2071     ///
2072     /// assert_eq!(slice, [4, 5, 3, 1, 2]);
2073     /// ```
2074     ///
2075     /// [`split_at_mut`]: #method.split_at_mut
2076     #[stable(feature = "swap_with_slice", since = "1.27.0")]
2077     pub fn swap_with_slice(&mut self, other: &mut [T]) {
2078         assert!(self.len() == other.len(),
2079                 "destination and source slices have different lengths");
2080         unsafe {
2081             ptr::swap_nonoverlapping(
2082                 self.as_mut_ptr(), other.as_mut_ptr(), self.len());
2083         }
2084     }
2085
2086     /// Function to calculate lengths of the middle and trailing slice for `align_to{,_mut}`.
2087     fn align_to_offsets<U>(&self) -> (usize, usize) {
2088         // What we gonna do about `rest` is figure out what multiple of `U`s we can put in a
2089         // lowest number of `T`s. And how many `T`s we need for each such "multiple".
2090         //
2091         // Consider for example T=u8 U=u16. Then we can put 1 U in 2 Ts. Simple. Now, consider
2092         // for example a case where size_of::<T> = 16, size_of::<U> = 24. We can put 2 Us in
2093         // place of every 3 Ts in the `rest` slice. A bit more complicated.
2094         //
2095         // Formula to calculate this is:
2096         //
2097         // Us = lcm(size_of::<T>, size_of::<U>) / size_of::<U>
2098         // Ts = lcm(size_of::<T>, size_of::<U>) / size_of::<T>
2099         //
2100         // Expanded and simplified:
2101         //
2102         // Us = size_of::<T> / gcd(size_of::<T>, size_of::<U>)
2103         // Ts = size_of::<U> / gcd(size_of::<T>, size_of::<U>)
2104         //
2105         // Luckily since all this is constant-evaluated... performance here matters not!
2106         #[inline]
2107         fn gcd(a: usize, b: usize) -> usize {
2108             // iterative stein’s algorithm
2109             // We should still make this `const fn` (and revert to recursive algorithm if we do)
2110             // because relying on llvm to consteval all this is… well, it makes me uncomfortable.
2111             let (ctz_a, mut ctz_b) = unsafe {
2112                 if a == 0 { return b; }
2113                 if b == 0 { return a; }
2114                 (::intrinsics::cttz_nonzero(a), ::intrinsics::cttz_nonzero(b))
2115             };
2116             let k = ctz_a.min(ctz_b);
2117             let mut a = a >> ctz_a;
2118             let mut b = b;
2119             loop {
2120                 // remove all factors of 2 from b
2121                 b >>= ctz_b;
2122                 if a > b {
2123                     ::mem::swap(&mut a, &mut b);
2124                 }
2125                 b = b - a;
2126                 unsafe {
2127                     if b == 0 {
2128                         break;
2129                     }
2130                     ctz_b = ::intrinsics::cttz_nonzero(b);
2131                 }
2132             }
2133             a << k
2134         }
2135         let gcd: usize = gcd(::mem::size_of::<T>(), ::mem::size_of::<U>());
2136         let ts: usize = ::mem::size_of::<U>() / gcd;
2137         let us: usize = ::mem::size_of::<T>() / gcd;
2138
2139         // Armed with this knowledge, we can find how many `U`s we can fit!
2140         let us_len = self.len() / ts * us;
2141         // And how many `T`s will be in the trailing slice!
2142         let ts_len = self.len() % ts;
2143         (us_len, ts_len)
2144     }
2145
2146     /// Transmute the slice to a slice of another type, ensuring alignment of the types is
2147     /// maintained.
2148     ///
2149     /// This method splits the slice into three distinct slices: prefix, correctly aligned middle
2150     /// slice of a new type, and the suffix slice. The method does a best effort to make the
2151     /// middle slice the greatest length possible for a given type and input slice, but only
2152     /// your algorithm's performance should depend on that, not its correctness.
2153     ///
2154     /// This method has no purpose when either input element `T` or output element `U` are
2155     /// zero-sized and will return the original slice without splitting anything.
2156     ///
2157     /// # Unsafety
2158     ///
2159     /// This method is essentially a `transmute` with respect to the elements in the returned
2160     /// middle slice, so all the usual caveats pertaining to `transmute::<T, U>` also apply here.
2161     ///
2162     /// # Examples
2163     ///
2164     /// Basic usage:
2165     ///
2166     /// ```
2167     /// unsafe {
2168     ///     let bytes: [u8; 7] = [1, 2, 3, 4, 5, 6, 7];
2169     ///     let (prefix, shorts, suffix) = bytes.align_to::<u16>();
2170     ///     // less_efficient_algorithm_for_bytes(prefix);
2171     ///     // more_efficient_algorithm_for_aligned_shorts(shorts);
2172     ///     // less_efficient_algorithm_for_bytes(suffix);
2173     /// }
2174     /// ```
2175     #[stable(feature = "slice_align_to", since = "1.30.0")]
2176     pub unsafe fn align_to<U>(&self) -> (&[T], &[U], &[T]) {
2177         // Note that most of this function will be constant-evaluated,
2178         if ::mem::size_of::<U>() == 0 || ::mem::size_of::<T>() == 0 {
2179             // handle ZSTs specially, which is â€“ don't handle them at all.
2180             return (self, &[], &[]);
2181         }
2182
2183         // First, find at what point do we split between the first and 2nd slice. Easy with
2184         // ptr.align_offset.
2185         let ptr = self.as_ptr();
2186         let offset = ::ptr::align_offset(ptr, ::mem::align_of::<U>());
2187         if offset > self.len() {
2188             (self, &[], &[])
2189         } else {
2190             let (left, rest) = self.split_at(offset);
2191             // now `rest` is definitely aligned, so `from_raw_parts_mut` below is okay
2192             let (us_len, ts_len) = rest.align_to_offsets::<U>();
2193             (left,
2194              from_raw_parts(rest.as_ptr() as *const U, us_len),
2195              from_raw_parts(rest.as_ptr().add(rest.len() - ts_len), ts_len))
2196         }
2197     }
2198
2199     /// Transmute the slice to a slice of another type, ensuring alignment of the types is
2200     /// maintained.
2201     ///
2202     /// This method splits the slice into three distinct slices: prefix, correctly aligned middle
2203     /// slice of a new type, and the suffix slice. The method does a best effort to make the
2204     /// middle slice the greatest length possible for a given type and input slice, but only
2205     /// your algorithm's performance should depend on that, not its correctness.
2206     ///
2207     /// This method has no purpose when either input element `T` or output element `U` are
2208     /// zero-sized and will return the original slice without splitting anything.
2209     ///
2210     /// # Unsafety
2211     ///
2212     /// This method is essentially a `transmute` with respect to the elements in the returned
2213     /// middle slice, so all the usual caveats pertaining to `transmute::<T, U>` also apply here.
2214     ///
2215     /// # Examples
2216     ///
2217     /// Basic usage:
2218     ///
2219     /// ```
2220     /// unsafe {
2221     ///     let mut bytes: [u8; 7] = [1, 2, 3, 4, 5, 6, 7];
2222     ///     let (prefix, shorts, suffix) = bytes.align_to_mut::<u16>();
2223     ///     // less_efficient_algorithm_for_bytes(prefix);
2224     ///     // more_efficient_algorithm_for_aligned_shorts(shorts);
2225     ///     // less_efficient_algorithm_for_bytes(suffix);
2226     /// }
2227     /// ```
2228     #[stable(feature = "slice_align_to", since = "1.30.0")]
2229     pub unsafe fn align_to_mut<U>(&mut self) -> (&mut [T], &mut [U], &mut [T]) {
2230         // Note that most of this function will be constant-evaluated,
2231         if ::mem::size_of::<U>() == 0 || ::mem::size_of::<T>() == 0 {
2232             // handle ZSTs specially, which is â€“ don't handle them at all.
2233             return (self, &mut [], &mut []);
2234         }
2235
2236         // First, find at what point do we split between the first and 2nd slice. Easy with
2237         // ptr.align_offset.
2238         let ptr = self.as_ptr();
2239         let offset = ::ptr::align_offset(ptr, ::mem::align_of::<U>());
2240         if offset > self.len() {
2241             (self, &mut [], &mut [])
2242         } else {
2243             let (left, rest) = self.split_at_mut(offset);
2244             // now `rest` is definitely aligned, so `from_raw_parts_mut` below is okay
2245             let (us_len, ts_len) = rest.align_to_offsets::<U>();
2246             let mut_ptr = rest.as_mut_ptr();
2247             (left,
2248              from_raw_parts_mut(mut_ptr as *mut U, us_len),
2249              from_raw_parts_mut(mut_ptr.add(rest.len() - ts_len), ts_len))
2250         }
2251     }
2252
2253     /// Checks if the elements of this slice are sorted.
2254     ///
2255     /// That is, for each element `a` and its following element `b`, `a <= b` must hold. If the
2256     /// slice yields exactly zero or one element, `true` is returned.
2257     ///
2258     /// Note that if `Self::Item` is only `PartialOrd`, but not `Ord`, the above definition
2259     /// implies that this function returns `false` if any two consecutive items are not
2260     /// comparable.
2261     ///
2262     /// # Examples
2263     ///
2264     /// ```
2265     /// #![feature(is_sorted)]
2266     /// let empty: [i32; 0] = [];
2267     ///
2268     /// assert!([1, 2, 2, 9].is_sorted());
2269     /// assert!(![1, 3, 2, 4].is_sorted());
2270     /// assert!([0].is_sorted());
2271     /// assert!(empty.is_sorted());
2272     /// assert!(![0.0, 1.0, std::f32::NAN].is_sorted());
2273     /// ```
2274     #[inline]
2275     #[unstable(feature = "is_sorted", reason = "new API", issue = "53485")]
2276     pub fn is_sorted(&self) -> bool
2277     where
2278         T: PartialOrd,
2279     {
2280         self.is_sorted_by(|a, b| a.partial_cmp(b))
2281     }
2282
2283     /// Checks if the elements of this slice are sorted using the given comparator function.
2284     ///
2285     /// Instead of using `PartialOrd::partial_cmp`, this function uses the given `compare`
2286     /// function to determine the ordering of two elements. Apart from that, it's equivalent to
2287     /// [`is_sorted`]; see its documentation for more information.
2288     ///
2289     /// [`is_sorted`]: #method.is_sorted
2290     #[unstable(feature = "is_sorted", reason = "new API", issue = "53485")]
2291     pub fn is_sorted_by<F>(&self, mut compare: F) -> bool
2292     where
2293         F: FnMut(&T, &T) -> Option<Ordering>
2294     {
2295         self.iter().is_sorted_by(|a, b| compare(*a, *b))
2296     }
2297
2298     /// Checks if the elements of this slice are sorted using the given key extraction function.
2299     ///
2300     /// Instead of comparing the slice's elements directly, this function compares the keys of the
2301     /// elements, as determined by `f`. Apart from that, it's equivalent to [`is_sorted`]; see its
2302     /// documentation for more information.
2303     ///
2304     /// [`is_sorted`]: #method.is_sorted
2305     ///
2306     /// # Examples
2307     ///
2308     /// ```
2309     /// #![feature(is_sorted)]
2310     ///
2311     /// assert!(["c", "bb", "aaa"].is_sorted_by_key(|s| s.len()));
2312     /// assert!(![-2i32, -1, 0, 3].is_sorted_by_key(|n| n.abs()));
2313     /// ```
2314     #[inline]
2315     #[unstable(feature = "is_sorted", reason = "new API", issue = "53485")]
2316     pub fn is_sorted_by_key<F, K>(&self, mut f: F) -> bool
2317     where
2318         F: FnMut(&T) -> K,
2319         K: PartialOrd
2320     {
2321         self.is_sorted_by(|a, b| f(a).partial_cmp(&f(b)))
2322     }
2323 }
2324
2325 #[lang = "slice_u8"]
2326 #[cfg(not(test))]
2327 impl [u8] {
2328     /// Checks if all bytes in this slice are within the ASCII range.
2329     #[stable(feature = "ascii_methods_on_intrinsics", since = "1.23.0")]
2330     #[inline]
2331     pub fn is_ascii(&self) -> bool {
2332         self.iter().all(|b| b.is_ascii())
2333     }
2334
2335     /// Checks that two slices are an ASCII case-insensitive match.
2336     ///
2337     /// Same as `to_ascii_lowercase(a) == to_ascii_lowercase(b)`,
2338     /// but without allocating and copying temporaries.
2339     #[stable(feature = "ascii_methods_on_intrinsics", since = "1.23.0")]
2340     #[inline]
2341     pub fn eq_ignore_ascii_case(&self, other: &[u8]) -> bool {
2342         self.len() == other.len() &&
2343             self.iter().zip(other).all(|(a, b)| {
2344                 a.eq_ignore_ascii_case(b)
2345             })
2346     }
2347
2348     /// Converts this slice to its ASCII upper case equivalent in-place.
2349     ///
2350     /// ASCII letters 'a' to 'z' are mapped to 'A' to 'Z',
2351     /// but non-ASCII letters are unchanged.
2352     ///
2353     /// To return a new uppercased value without modifying the existing one, use
2354     /// [`to_ascii_uppercase`].
2355     ///
2356     /// [`to_ascii_uppercase`]: #method.to_ascii_uppercase
2357     #[stable(feature = "ascii_methods_on_intrinsics", since = "1.23.0")]
2358     #[inline]
2359     pub fn make_ascii_uppercase(&mut self) {
2360         for byte in self {
2361             byte.make_ascii_uppercase();
2362         }
2363     }
2364
2365     /// Converts this slice to its ASCII lower case equivalent in-place.
2366     ///
2367     /// ASCII letters 'A' to 'Z' are mapped to 'a' to 'z',
2368     /// but non-ASCII letters are unchanged.
2369     ///
2370     /// To return a new lowercased value without modifying the existing one, use
2371     /// [`to_ascii_lowercase`].
2372     ///
2373     /// [`to_ascii_lowercase`]: #method.to_ascii_lowercase
2374     #[stable(feature = "ascii_methods_on_intrinsics", since = "1.23.0")]
2375     #[inline]
2376     pub fn make_ascii_lowercase(&mut self) {
2377         for byte in self {
2378             byte.make_ascii_lowercase();
2379         }
2380     }
2381
2382 }
2383
2384 #[stable(feature = "rust1", since = "1.0.0")]
2385 impl<T, I> ops::Index<I> for [T]
2386     where I: SliceIndex<[T]>
2387 {
2388     type Output = I::Output;
2389
2390     #[inline]
2391     fn index(&self, index: I) -> &I::Output {
2392         index.index(self)
2393     }
2394 }
2395
2396 #[stable(feature = "rust1", since = "1.0.0")]
2397 impl<T, I> ops::IndexMut<I> for [T]
2398     where I: SliceIndex<[T]>
2399 {
2400     #[inline]
2401     fn index_mut(&mut self, index: I) -> &mut I::Output {
2402         index.index_mut(self)
2403     }
2404 }
2405
2406 #[inline(never)]
2407 #[cold]
2408 fn slice_index_len_fail(index: usize, len: usize) -> ! {
2409     panic!("index {} out of range for slice of length {}", index, len);
2410 }
2411
2412 #[inline(never)]
2413 #[cold]
2414 fn slice_index_order_fail(index: usize, end: usize) -> ! {
2415     panic!("slice index starts at {} but ends at {}", index, end);
2416 }
2417
2418 #[inline(never)]
2419 #[cold]
2420 fn slice_index_overflow_fail() -> ! {
2421     panic!("attempted to index slice up to maximum usize");
2422 }
2423
2424 mod private_slice_index {
2425     use super::ops;
2426     #[stable(feature = "slice_get_slice", since = "1.28.0")]
2427     pub trait Sealed {}
2428
2429     #[stable(feature = "slice_get_slice", since = "1.28.0")]
2430     impl Sealed for usize {}
2431     #[stable(feature = "slice_get_slice", since = "1.28.0")]
2432     impl Sealed for ops::Range<usize> {}
2433     #[stable(feature = "slice_get_slice", since = "1.28.0")]
2434     impl Sealed for ops::RangeTo<usize> {}
2435     #[stable(feature = "slice_get_slice", since = "1.28.0")]
2436     impl Sealed for ops::RangeFrom<usize> {}
2437     #[stable(feature = "slice_get_slice", since = "1.28.0")]
2438     impl Sealed for ops::RangeFull {}
2439     #[stable(feature = "slice_get_slice", since = "1.28.0")]
2440     impl Sealed for ops::RangeInclusive<usize> {}
2441     #[stable(feature = "slice_get_slice", since = "1.28.0")]
2442     impl Sealed for ops::RangeToInclusive<usize> {}
2443 }
2444
2445 /// A helper trait used for indexing operations.
2446 #[stable(feature = "slice_get_slice", since = "1.28.0")]
2447 #[rustc_on_unimplemented(
2448     on(
2449         T = "str",
2450         label = "string indices are ranges of `usize`",
2451     ),
2452     on(
2453         all(any(T = "str", T = "&str", T = "std::string::String"), _Self="{integer}"),
2454         note="you can use `.chars().nth()` or `.bytes().nth()`
2455 see chapter in The Book <https://doc.rust-lang.org/book/ch08-02-strings.html#indexing-into-strings>"
2456     ),
2457     message = "the type `{T}` cannot be indexed by `{Self}`",
2458     label = "slice indices are of type `usize` or ranges of `usize`",
2459 )]
2460 pub trait SliceIndex<T: ?Sized>: private_slice_index::Sealed {
2461     /// The output type returned by methods.
2462     #[stable(feature = "slice_get_slice", since = "1.28.0")]
2463     type Output: ?Sized;
2464
2465     /// Returns a shared reference to the output at this location, if in
2466     /// bounds.
2467     #[unstable(feature = "slice_index_methods", issue = "0")]
2468     fn get(self, slice: &T) -> Option<&Self::Output>;
2469
2470     /// Returns a mutable reference to the output at this location, if in
2471     /// bounds.
2472     #[unstable(feature = "slice_index_methods", issue = "0")]
2473     fn get_mut(self, slice: &mut T) -> Option<&mut Self::Output>;
2474
2475     /// Returns a shared reference to the output at this location, without
2476     /// performing any bounds checking.
2477     #[unstable(feature = "slice_index_methods", issue = "0")]
2478     unsafe fn get_unchecked(self, slice: &T) -> &Self::Output;
2479
2480     /// Returns a mutable reference to the output at this location, without
2481     /// performing any bounds checking.
2482     #[unstable(feature = "slice_index_methods", issue = "0")]
2483     unsafe fn get_unchecked_mut(self, slice: &mut T) -> &mut Self::Output;
2484
2485     /// Returns a shared reference to the output at this location, panicking
2486     /// if out of bounds.
2487     #[unstable(feature = "slice_index_methods", issue = "0")]
2488     fn index(self, slice: &T) -> &Self::Output;
2489
2490     /// Returns a mutable reference to the output at this location, panicking
2491     /// if out of bounds.
2492     #[unstable(feature = "slice_index_methods", issue = "0")]
2493     fn index_mut(self, slice: &mut T) -> &mut Self::Output;
2494 }
2495
2496 #[stable(feature = "slice_get_slice_impls", since = "1.15.0")]
2497 impl<T> SliceIndex<[T]> for usize {
2498     type Output = T;
2499
2500     #[inline]
2501     fn get(self, slice: &[T]) -> Option<&T> {
2502         if self < slice.len() {
2503             unsafe {
2504                 Some(self.get_unchecked(slice))
2505             }
2506         } else {
2507             None
2508         }
2509     }
2510
2511     #[inline]
2512     fn get_mut(self, slice: &mut [T]) -> Option<&mut T> {
2513         if self < slice.len() {
2514             unsafe {
2515                 Some(self.get_unchecked_mut(slice))
2516             }
2517         } else {
2518             None
2519         }
2520     }
2521
2522     #[inline]
2523     unsafe fn get_unchecked(self, slice: &[T]) -> &T {
2524         &*slice.as_ptr().add(self)
2525     }
2526
2527     #[inline]
2528     unsafe fn get_unchecked_mut(self, slice: &mut [T]) -> &mut T {
2529         &mut *slice.as_mut_ptr().add(self)
2530     }
2531
2532     #[inline]
2533     fn index(self, slice: &[T]) -> &T {
2534         // N.B., use intrinsic indexing
2535         &(*slice)[self]
2536     }
2537
2538     #[inline]
2539     fn index_mut(self, slice: &mut [T]) -> &mut T {
2540         // N.B., use intrinsic indexing
2541         &mut (*slice)[self]
2542     }
2543 }
2544
2545 #[stable(feature = "slice_get_slice_impls", since = "1.15.0")]
2546 impl<T> SliceIndex<[T]> for  ops::Range<usize> {
2547     type Output = [T];
2548
2549     #[inline]
2550     fn get(self, slice: &[T]) -> Option<&[T]> {
2551         if self.start > self.end || self.end > slice.len() {
2552             None
2553         } else {
2554             unsafe {
2555                 Some(self.get_unchecked(slice))
2556             }
2557         }
2558     }
2559
2560     #[inline]
2561     fn get_mut(self, slice: &mut [T]) -> Option<&mut [T]> {
2562         if self.start > self.end || self.end > slice.len() {
2563             None
2564         } else {
2565             unsafe {
2566                 Some(self.get_unchecked_mut(slice))
2567             }
2568         }
2569     }
2570
2571     #[inline]
2572     unsafe fn get_unchecked(self, slice: &[T]) -> &[T] {
2573         from_raw_parts(slice.as_ptr().add(self.start), self.end - self.start)
2574     }
2575
2576     #[inline]
2577     unsafe fn get_unchecked_mut(self, slice: &mut [T]) -> &mut [T] {
2578         from_raw_parts_mut(slice.as_mut_ptr().add(self.start), self.end - self.start)
2579     }
2580
2581     #[inline]
2582     fn index(self, slice: &[T]) -> &[T] {
2583         if self.start > self.end {
2584             slice_index_order_fail(self.start, self.end);
2585         } else if self.end > slice.len() {
2586             slice_index_len_fail(self.end, slice.len());
2587         }
2588         unsafe {
2589             self.get_unchecked(slice)
2590         }
2591     }
2592
2593     #[inline]
2594     fn index_mut(self, slice: &mut [T]) -> &mut [T] {
2595         if self.start > self.end {
2596             slice_index_order_fail(self.start, self.end);
2597         } else if self.end > slice.len() {
2598             slice_index_len_fail(self.end, slice.len());
2599         }
2600         unsafe {
2601             self.get_unchecked_mut(slice)
2602         }
2603     }
2604 }
2605
2606 #[stable(feature = "slice_get_slice_impls", since = "1.15.0")]
2607 impl<T> SliceIndex<[T]> for ops::RangeTo<usize> {
2608     type Output = [T];
2609
2610     #[inline]
2611     fn get(self, slice: &[T]) -> Option<&[T]> {
2612         (0..self.end).get(slice)
2613     }
2614
2615     #[inline]
2616     fn get_mut(self, slice: &mut [T]) -> Option<&mut [T]> {
2617         (0..self.end).get_mut(slice)
2618     }
2619
2620     #[inline]
2621     unsafe fn get_unchecked(self, slice: &[T]) -> &[T] {
2622         (0..self.end).get_unchecked(slice)
2623     }
2624
2625     #[inline]
2626     unsafe fn get_unchecked_mut(self, slice: &mut [T]) -> &mut [T] {
2627         (0..self.end).get_unchecked_mut(slice)
2628     }
2629
2630     #[inline]
2631     fn index(self, slice: &[T]) -> &[T] {
2632         (0..self.end).index(slice)
2633     }
2634
2635     #[inline]
2636     fn index_mut(self, slice: &mut [T]) -> &mut [T] {
2637         (0..self.end).index_mut(slice)
2638     }
2639 }
2640
2641 #[stable(feature = "slice_get_slice_impls", since = "1.15.0")]
2642 impl<T> SliceIndex<[T]> for ops::RangeFrom<usize> {
2643     type Output = [T];
2644
2645     #[inline]
2646     fn get(self, slice: &[T]) -> Option<&[T]> {
2647         (self.start..slice.len()).get(slice)
2648     }
2649
2650     #[inline]
2651     fn get_mut(self, slice: &mut [T]) -> Option<&mut [T]> {
2652         (self.start..slice.len()).get_mut(slice)
2653     }
2654
2655     #[inline]
2656     unsafe fn get_unchecked(self, slice: &[T]) -> &[T] {
2657         (self.start..slice.len()).get_unchecked(slice)
2658     }
2659
2660     #[inline]
2661     unsafe fn get_unchecked_mut(self, slice: &mut [T]) -> &mut [T] {
2662         (self.start..slice.len()).get_unchecked_mut(slice)
2663     }
2664
2665     #[inline]
2666     fn index(self, slice: &[T]) -> &[T] {
2667         (self.start..slice.len()).index(slice)
2668     }
2669
2670     #[inline]
2671     fn index_mut(self, slice: &mut [T]) -> &mut [T] {
2672         (self.start..slice.len()).index_mut(slice)
2673     }
2674 }
2675
2676 #[stable(feature = "slice_get_slice_impls", since = "1.15.0")]
2677 impl<T> SliceIndex<[T]> for ops::RangeFull {
2678     type Output = [T];
2679
2680     #[inline]
2681     fn get(self, slice: &[T]) -> Option<&[T]> {
2682         Some(slice)
2683     }
2684
2685     #[inline]
2686     fn get_mut(self, slice: &mut [T]) -> Option<&mut [T]> {
2687         Some(slice)
2688     }
2689
2690     #[inline]
2691     unsafe fn get_unchecked(self, slice: &[T]) -> &[T] {
2692         slice
2693     }
2694
2695     #[inline]
2696     unsafe fn get_unchecked_mut(self, slice: &mut [T]) -> &mut [T] {
2697         slice
2698     }
2699
2700     #[inline]
2701     fn index(self, slice: &[T]) -> &[T] {
2702         slice
2703     }
2704
2705     #[inline]
2706     fn index_mut(self, slice: &mut [T]) -> &mut [T] {
2707         slice
2708     }
2709 }
2710
2711
2712 #[stable(feature = "inclusive_range", since = "1.26.0")]
2713 impl<T> SliceIndex<[T]> for ops::RangeInclusive<usize> {
2714     type Output = [T];
2715
2716     #[inline]
2717     fn get(self, slice: &[T]) -> Option<&[T]> {
2718         if *self.end() == usize::max_value() { None }
2719         else { (*self.start()..self.end() + 1).get(slice) }
2720     }
2721
2722     #[inline]
2723     fn get_mut(self, slice: &mut [T]) -> Option<&mut [T]> {
2724         if *self.end() == usize::max_value() { None }
2725         else { (*self.start()..self.end() + 1).get_mut(slice) }
2726     }
2727
2728     #[inline]
2729     unsafe fn get_unchecked(self, slice: &[T]) -> &[T] {
2730         (*self.start()..self.end() + 1).get_unchecked(slice)
2731     }
2732
2733     #[inline]
2734     unsafe fn get_unchecked_mut(self, slice: &mut [T]) -> &mut [T] {
2735         (*self.start()..self.end() + 1).get_unchecked_mut(slice)
2736     }
2737
2738     #[inline]
2739     fn index(self, slice: &[T]) -> &[T] {
2740         if *self.end() == usize::max_value() { slice_index_overflow_fail(); }
2741         (*self.start()..self.end() + 1).index(slice)
2742     }
2743
2744     #[inline]
2745     fn index_mut(self, slice: &mut [T]) -> &mut [T] {
2746         if *self.end() == usize::max_value() { slice_index_overflow_fail(); }
2747         (*self.start()..self.end() + 1).index_mut(slice)
2748     }
2749 }
2750
2751 #[stable(feature = "inclusive_range", since = "1.26.0")]
2752 impl<T> SliceIndex<[T]> for ops::RangeToInclusive<usize> {
2753     type Output = [T];
2754
2755     #[inline]
2756     fn get(self, slice: &[T]) -> Option<&[T]> {
2757         (0..=self.end).get(slice)
2758     }
2759
2760     #[inline]
2761     fn get_mut(self, slice: &mut [T]) -> Option<&mut [T]> {
2762         (0..=self.end).get_mut(slice)
2763     }
2764
2765     #[inline]
2766     unsafe fn get_unchecked(self, slice: &[T]) -> &[T] {
2767         (0..=self.end).get_unchecked(slice)
2768     }
2769
2770     #[inline]
2771     unsafe fn get_unchecked_mut(self, slice: &mut [T]) -> &mut [T] {
2772         (0..=self.end).get_unchecked_mut(slice)
2773     }
2774
2775     #[inline]
2776     fn index(self, slice: &[T]) -> &[T] {
2777         (0..=self.end).index(slice)
2778     }
2779
2780     #[inline]
2781     fn index_mut(self, slice: &mut [T]) -> &mut [T] {
2782         (0..=self.end).index_mut(slice)
2783     }
2784 }
2785
2786 ////////////////////////////////////////////////////////////////////////////////
2787 // Common traits
2788 ////////////////////////////////////////////////////////////////////////////////
2789
2790 #[stable(feature = "rust1", since = "1.0.0")]
2791 impl<T> Default for &[T] {
2792     /// Creates an empty slice.
2793     fn default() -> Self { &[] }
2794 }
2795
2796 #[stable(feature = "mut_slice_default", since = "1.5.0")]
2797 impl<T> Default for &mut [T] {
2798     /// Creates a mutable empty slice.
2799     fn default() -> Self { &mut [] }
2800 }
2801
2802 //
2803 // Iterators
2804 //
2805
2806 #[stable(feature = "rust1", since = "1.0.0")]
2807 impl<'a, T> IntoIterator for &'a [T] {
2808     type Item = &'a T;
2809     type IntoIter = Iter<'a, T>;
2810
2811     fn into_iter(self) -> Iter<'a, T> {
2812         self.iter()
2813     }
2814 }
2815
2816 #[stable(feature = "rust1", since = "1.0.0")]
2817 impl<'a, T> IntoIterator for &'a mut [T] {
2818     type Item = &'a mut T;
2819     type IntoIter = IterMut<'a, T>;
2820
2821     fn into_iter(self) -> IterMut<'a, T> {
2822         self.iter_mut()
2823     }
2824 }
2825
2826 // Macro helper functions
2827 #[inline(always)]
2828 fn size_from_ptr<T>(_: *const T) -> usize {
2829     mem::size_of::<T>()
2830 }
2831
2832 // Inlining is_empty and len makes a huge performance difference
2833 macro_rules! is_empty {
2834     // The way we encode the length of a ZST iterator, this works both for ZST
2835     // and non-ZST.
2836     ($self: ident) => {$self.ptr == $self.end}
2837 }
2838 // To get rid of some bounds checks (see `position`), we compute the length in a somewhat
2839 // unexpected way. (Tested by `codegen/slice-position-bounds-check`.)
2840 macro_rules! len {
2841     ($self: ident) => {{
2842         let start = $self.ptr;
2843         let diff = ($self.end as usize).wrapping_sub(start as usize);
2844         let size = size_from_ptr(start);
2845         if size == 0 {
2846             diff
2847         } else {
2848             // Using division instead of `offset_from` helps LLVM remove bounds checks
2849             diff / size
2850         }
2851     }}
2852 }
2853
2854 // The shared definition of the `Iter` and `IterMut` iterators
2855 macro_rules! iterator {
2856     (
2857         struct $name:ident -> $ptr:ty,
2858         $elem:ty,
2859         $raw_mut:tt,
2860         {$( $mut_:tt )*},
2861         {$($extra:tt)*}
2862     ) => {
2863         impl<'a, T> $name<'a, T> {
2864             // Helper function for creating a slice from the iterator.
2865             #[inline(always)]
2866             fn make_slice(&self) -> &'a [T] {
2867                 unsafe { from_raw_parts(self.ptr, len!(self)) }
2868             }
2869
2870             // Helper function for moving the start of the iterator forwards by `offset` elements,
2871             // returning the old start.
2872             // Unsafe because the offset must be in-bounds or one-past-the-end.
2873             #[inline(always)]
2874             unsafe fn post_inc_start(&mut self, offset: isize) -> * $raw_mut T {
2875                 if mem::size_of::<T>() == 0 {
2876                     // This is *reducing* the length.  `ptr` never changes with ZST.
2877                     self.end = (self.end as * $raw_mut u8).wrapping_offset(-offset) as * $raw_mut T;
2878                     self.ptr
2879                 } else {
2880                     let old = self.ptr;
2881                     self.ptr = self.ptr.offset(offset);
2882                     old
2883                 }
2884             }
2885
2886             // Helper function for moving the end of the iterator backwards by `offset` elements,
2887             // returning the new end.
2888             // Unsafe because the offset must be in-bounds or one-past-the-end.
2889             #[inline(always)]
2890             unsafe fn pre_dec_end(&mut self, offset: isize) -> * $raw_mut T {
2891                 if mem::size_of::<T>() == 0 {
2892                     self.end = (self.end as * $raw_mut u8).wrapping_offset(-offset) as * $raw_mut T;
2893                     self.ptr
2894                 } else {
2895                     self.end = self.end.offset(-offset);
2896                     self.end
2897                 }
2898             }
2899         }
2900
2901         #[stable(feature = "rust1", since = "1.0.0")]
2902         impl<'a, T> ExactSizeIterator for $name<'a, T> {
2903             #[inline(always)]
2904             fn len(&self) -> usize {
2905                 len!(self)
2906             }
2907
2908             #[inline(always)]
2909             fn is_empty(&self) -> bool {
2910                 is_empty!(self)
2911             }
2912         }
2913
2914         #[stable(feature = "rust1", since = "1.0.0")]
2915         impl<'a, T> Iterator for $name<'a, T> {
2916             type Item = $elem;
2917
2918             #[inline]
2919             fn next(&mut self) -> Option<$elem> {
2920                 // could be implemented with slices, but this avoids bounds checks
2921                 unsafe {
2922                     assume(!self.ptr.is_null());
2923                     if mem::size_of::<T>() != 0 {
2924                         assume(!self.end.is_null());
2925                     }
2926                     if is_empty!(self) {
2927                         None
2928                     } else {
2929                         Some(& $( $mut_ )* *self.post_inc_start(1))
2930                     }
2931                 }
2932             }
2933
2934             #[inline]
2935             fn size_hint(&self) -> (usize, Option<usize>) {
2936                 let exact = len!(self);
2937                 (exact, Some(exact))
2938             }
2939
2940             #[inline]
2941             fn count(self) -> usize {
2942                 len!(self)
2943             }
2944
2945             #[inline]
2946             fn nth(&mut self, n: usize) -> Option<$elem> {
2947                 if n >= len!(self) {
2948                     // This iterator is now empty.
2949                     if mem::size_of::<T>() == 0 {
2950                         // We have to do it this way as `ptr` may never be 0, but `end`
2951                         // could be (due to wrapping).
2952                         self.end = self.ptr;
2953                     } else {
2954                         self.ptr = self.end;
2955                     }
2956                     return None;
2957                 }
2958                 // We are in bounds. `offset` does the right thing even for ZSTs.
2959                 unsafe {
2960                     let elem = Some(& $( $mut_ )* *self.ptr.add(n));
2961                     self.post_inc_start((n as isize).wrapping_add(1));
2962                     elem
2963                 }
2964             }
2965
2966             #[inline]
2967             fn last(mut self) -> Option<$elem> {
2968                 self.next_back()
2969             }
2970
2971             #[inline]
2972             fn try_fold<B, F, R>(&mut self, init: B, mut f: F) -> R where
2973                 Self: Sized, F: FnMut(B, Self::Item) -> R, R: Try<Ok=B>
2974             {
2975                 // manual unrolling is needed when there are conditional exits from the loop
2976                 let mut accum = init;
2977                 unsafe {
2978                     while len!(self) >= 4 {
2979                         accum = f(accum, & $( $mut_ )* *self.post_inc_start(1))?;
2980                         accum = f(accum, & $( $mut_ )* *self.post_inc_start(1))?;
2981                         accum = f(accum, & $( $mut_ )* *self.post_inc_start(1))?;
2982                         accum = f(accum, & $( $mut_ )* *self.post_inc_start(1))?;
2983                     }
2984                     while !is_empty!(self) {
2985                         accum = f(accum, & $( $mut_ )* *self.post_inc_start(1))?;
2986                     }
2987                 }
2988                 Try::from_ok(accum)
2989             }
2990
2991             #[inline]
2992             fn fold<Acc, Fold>(mut self, init: Acc, mut f: Fold) -> Acc
2993                 where Fold: FnMut(Acc, Self::Item) -> Acc,
2994             {
2995                 // Let LLVM unroll this, rather than using the default
2996                 // impl that would force the manual unrolling above
2997                 let mut accum = init;
2998                 while let Some(x) = self.next() {
2999                     accum = f(accum, x);
3000                 }
3001                 accum
3002             }
3003
3004             #[inline]
3005             #[rustc_inherit_overflow_checks]
3006             fn position<P>(&mut self, mut predicate: P) -> Option<usize> where
3007                 Self: Sized,
3008                 P: FnMut(Self::Item) -> bool,
3009             {
3010                 // The addition might panic on overflow.
3011                 let n = len!(self);
3012                 self.try_fold(0, move |i, x| {
3013                     if predicate(x) { Err(i) }
3014                     else { Ok(i + 1) }
3015                 }).err()
3016                     .map(|i| {
3017                         unsafe { assume(i < n) };
3018                         i
3019                     })
3020             }
3021
3022             #[inline]
3023             fn rposition<P>(&mut self, mut predicate: P) -> Option<usize> where
3024                 P: FnMut(Self::Item) -> bool,
3025                 Self: Sized + ExactSizeIterator + DoubleEndedIterator
3026             {
3027                 // No need for an overflow check here, because `ExactSizeIterator`
3028                 let n = len!(self);
3029                 self.try_rfold(n, move |i, x| {
3030                     let i = i - 1;
3031                     if predicate(x) { Err(i) }
3032                     else { Ok(i) }
3033                 }).err()
3034                     .map(|i| {
3035                         unsafe { assume(i < n) };
3036                         i
3037                     })
3038             }
3039
3040             $($extra)*
3041         }
3042
3043         #[stable(feature = "rust1", since = "1.0.0")]
3044         impl<'a, T> DoubleEndedIterator for $name<'a, T> {
3045             #[inline]
3046             fn next_back(&mut self) -> Option<$elem> {
3047                 // could be implemented with slices, but this avoids bounds checks
3048                 unsafe {
3049                     assume(!self.ptr.is_null());
3050                     if mem::size_of::<T>() != 0 {
3051                         assume(!self.end.is_null());
3052                     }
3053                     if is_empty!(self) {
3054                         None
3055                     } else {
3056                         Some(& $( $mut_ )* *self.pre_dec_end(1))
3057                     }
3058                 }
3059             }
3060
3061             #[inline]
3062             fn try_rfold<B, F, R>(&mut self, init: B, mut f: F) -> R where
3063                 Self: Sized, F: FnMut(B, Self::Item) -> R, R: Try<Ok=B>
3064             {
3065                 // manual unrolling is needed when there are conditional exits from the loop
3066                 let mut accum = init;
3067                 unsafe {
3068                     while len!(self) >= 4 {
3069                         accum = f(accum, & $( $mut_ )* *self.pre_dec_end(1))?;
3070                         accum = f(accum, & $( $mut_ )* *self.pre_dec_end(1))?;
3071                         accum = f(accum, & $( $mut_ )* *self.pre_dec_end(1))?;
3072                         accum = f(accum, & $( $mut_ )* *self.pre_dec_end(1))?;
3073                     }
3074                     // inlining is_empty everywhere makes a huge performance difference
3075                     while !is_empty!(self) {
3076                         accum = f(accum, & $( $mut_ )* *self.pre_dec_end(1))?;
3077                     }
3078                 }
3079                 Try::from_ok(accum)
3080             }
3081
3082             #[inline]
3083             fn rfold<Acc, Fold>(mut self, init: Acc, mut f: Fold) -> Acc
3084                 where Fold: FnMut(Acc, Self::Item) -> Acc,
3085             {
3086                 // Let LLVM unroll this, rather than using the default
3087                 // impl that would force the manual unrolling above
3088                 let mut accum = init;
3089                 while let Some(x) = self.next_back() {
3090                     accum = f(accum, x);
3091                 }
3092                 accum
3093             }
3094         }
3095
3096         #[stable(feature = "fused", since = "1.26.0")]
3097         impl<'a, T> FusedIterator for $name<'a, T> {}
3098
3099         #[unstable(feature = "trusted_len", issue = "37572")]
3100         unsafe impl<'a, T> TrustedLen for $name<'a, T> {}
3101     }
3102 }
3103
3104 /// Immutable slice iterator
3105 ///
3106 /// This struct is created by the [`iter`] method on [slices].
3107 ///
3108 /// # Examples
3109 ///
3110 /// Basic usage:
3111 ///
3112 /// ```
3113 /// // First, we declare a type which has `iter` method to get the `Iter` struct (&[usize here]):
3114 /// let slice = &[1, 2, 3];
3115 ///
3116 /// // Then, we iterate over it:
3117 /// for element in slice.iter() {
3118 ///     println!("{}", element);
3119 /// }
3120 /// ```
3121 ///
3122 /// [`iter`]: ../../std/primitive.slice.html#method.iter
3123 /// [slices]: ../../std/primitive.slice.html
3124 #[stable(feature = "rust1", since = "1.0.0")]
3125 pub struct Iter<'a, T: 'a> {
3126     ptr: *const T,
3127     end: *const T, // If T is a ZST, this is actually ptr+len.  This encoding is picked so that
3128                    // ptr == end is a quick test for the Iterator being empty, that works
3129                    // for both ZST and non-ZST.
3130     _marker: marker::PhantomData<&'a T>,
3131 }
3132
3133 #[stable(feature = "core_impl_debug", since = "1.9.0")]
3134 impl<T: fmt::Debug> fmt::Debug for Iter<'_, T> {
3135     fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
3136         f.debug_tuple("Iter")
3137             .field(&self.as_slice())
3138             .finish()
3139     }
3140 }
3141
3142 #[stable(feature = "rust1", since = "1.0.0")]
3143 unsafe impl<T: Sync> Sync for Iter<'_, T> {}
3144 #[stable(feature = "rust1", since = "1.0.0")]
3145 unsafe impl<T: Sync> Send for Iter<'_, T> {}
3146
3147 impl<'a, T> Iter<'a, T> {
3148     /// View the underlying data as a subslice of the original data.
3149     ///
3150     /// This has the same lifetime as the original slice, and so the
3151     /// iterator can continue to be used while this exists.
3152     ///
3153     /// # Examples
3154     ///
3155     /// Basic usage:
3156     ///
3157     /// ```
3158     /// // First, we declare a type which has the `iter` method to get the `Iter`
3159     /// // struct (&[usize here]):
3160     /// let slice = &[1, 2, 3];
3161     ///
3162     /// // Then, we get the iterator:
3163     /// let mut iter = slice.iter();
3164     /// // So if we print what `as_slice` method returns here, we have "[1, 2, 3]":
3165     /// println!("{:?}", iter.as_slice());
3166     ///
3167     /// // Next, we move to the second element of the slice:
3168     /// iter.next();
3169     /// // Now `as_slice` returns "[2, 3]":
3170     /// println!("{:?}", iter.as_slice());
3171     /// ```
3172     #[stable(feature = "iter_to_slice", since = "1.4.0")]
3173     pub fn as_slice(&self) -> &'a [T] {
3174         self.make_slice()
3175     }
3176 }
3177
3178 iterator!{struct Iter -> *const T, &'a T, const, {/* no mut */}, {
3179     fn is_sorted_by<F>(self, mut compare: F) -> bool
3180     where
3181         Self: Sized,
3182         F: FnMut(&Self::Item, &Self::Item) -> Option<Ordering>,
3183     {
3184         self.as_slice().windows(2).all(|w| {
3185             compare(&&w[0], &&w[1]).map(|o| o != Ordering::Greater).unwrap_or(false)
3186         })
3187     }
3188 }}
3189
3190 #[stable(feature = "rust1", since = "1.0.0")]
3191 impl<T> Clone for Iter<'_, T> {
3192     fn clone(&self) -> Self { Iter { ptr: self.ptr, end: self.end, _marker: self._marker } }
3193 }
3194
3195 #[stable(feature = "slice_iter_as_ref", since = "1.13.0")]
3196 impl<T> AsRef<[T]> for Iter<'_, T> {
3197     fn as_ref(&self) -> &[T] {
3198         self.as_slice()
3199     }
3200 }
3201
3202 /// Mutable slice iterator.
3203 ///
3204 /// This struct is created by the [`iter_mut`] method on [slices].
3205 ///
3206 /// # Examples
3207 ///
3208 /// Basic usage:
3209 ///
3210 /// ```
3211 /// // First, we declare a type which has `iter_mut` method to get the `IterMut`
3212 /// // struct (&[usize here]):
3213 /// let mut slice = &mut [1, 2, 3];
3214 ///
3215 /// // Then, we iterate over it and increment each element value:
3216 /// for element in slice.iter_mut() {
3217 ///     *element += 1;
3218 /// }
3219 ///
3220 /// // We now have "[2, 3, 4]":
3221 /// println!("{:?}", slice);
3222 /// ```
3223 ///
3224 /// [`iter_mut`]: ../../std/primitive.slice.html#method.iter_mut
3225 /// [slices]: ../../std/primitive.slice.html
3226 #[stable(feature = "rust1", since = "1.0.0")]
3227 pub struct IterMut<'a, T: 'a> {
3228     ptr: *mut T,
3229     end: *mut T, // If T is a ZST, this is actually ptr+len.  This encoding is picked so that
3230                  // ptr == end is a quick test for the Iterator being empty, that works
3231                  // for both ZST and non-ZST.
3232     _marker: marker::PhantomData<&'a mut T>,
3233 }
3234
3235 #[stable(feature = "core_impl_debug", since = "1.9.0")]
3236 impl<T: fmt::Debug> fmt::Debug for IterMut<'_, T> {
3237     fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
3238         f.debug_tuple("IterMut")
3239             .field(&self.make_slice())
3240             .finish()
3241     }
3242 }
3243
3244 #[stable(feature = "rust1", since = "1.0.0")]
3245 unsafe impl<T: Sync> Sync for IterMut<'_, T> {}
3246 #[stable(feature = "rust1", since = "1.0.0")]
3247 unsafe impl<T: Send> Send for IterMut<'_, T> {}
3248
3249 impl<'a, T> IterMut<'a, T> {
3250     /// View the underlying data as a subslice of the original data.
3251     ///
3252     /// To avoid creating `&mut` references that alias, this is forced
3253     /// to consume the iterator.
3254     ///
3255     /// # Examples
3256     ///
3257     /// Basic usage:
3258     ///
3259     /// ```
3260     /// // First, we declare a type which has `iter_mut` method to get the `IterMut`
3261     /// // struct (&[usize here]):
3262     /// let mut slice = &mut [1, 2, 3];
3263     ///
3264     /// {
3265     ///     // Then, we get the iterator:
3266     ///     let mut iter = slice.iter_mut();
3267     ///     // We move to next element:
3268     ///     iter.next();
3269     ///     // So if we print what `into_slice` method returns here, we have "[2, 3]":
3270     ///     println!("{:?}", iter.into_slice());
3271     /// }
3272     ///
3273     /// // Now let's modify a value of the slice:
3274     /// {
3275     ///     // First we get back the iterator:
3276     ///     let mut iter = slice.iter_mut();
3277     ///     // We change the value of the first element of the slice returned by the `next` method:
3278     ///     *iter.next().unwrap() += 1;
3279     /// }
3280     /// // Now slice is "[2, 2, 3]":
3281     /// println!("{:?}", slice);
3282     /// ```
3283     #[stable(feature = "iter_to_slice", since = "1.4.0")]
3284     pub fn into_slice(self) -> &'a mut [T] {
3285         unsafe { from_raw_parts_mut(self.ptr, len!(self)) }
3286     }
3287 }
3288
3289 iterator!{struct IterMut -> *mut T, &'a mut T, mut, {mut}, {}}
3290
3291 /// An internal abstraction over the splitting iterators, so that
3292 /// splitn, splitn_mut etc can be implemented once.
3293 #[doc(hidden)]
3294 trait SplitIter: DoubleEndedIterator {
3295     /// Marks the underlying iterator as complete, extracting the remaining
3296     /// portion of the slice.
3297     fn finish(&mut self) -> Option<Self::Item>;
3298 }
3299
3300 /// An iterator over subslices separated by elements that match a predicate
3301 /// function.
3302 ///
3303 /// This struct is created by the [`split`] method on [slices].
3304 ///
3305 /// [`split`]: ../../std/primitive.slice.html#method.split
3306 /// [slices]: ../../std/primitive.slice.html
3307 #[stable(feature = "rust1", since = "1.0.0")]
3308 pub struct Split<'a, T:'a, P> where P: FnMut(&T) -> bool {
3309     v: &'a [T],
3310     pred: P,
3311     finished: bool
3312 }
3313
3314 #[stable(feature = "core_impl_debug", since = "1.9.0")]
3315 impl<T: fmt::Debug, P> fmt::Debug for Split<'_, T, P> where P: FnMut(&T) -> bool {
3316     fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
3317         f.debug_struct("Split")
3318             .field("v", &self.v)
3319             .field("finished", &self.finished)
3320             .finish()
3321     }
3322 }
3323
3324 // FIXME(#26925) Remove in favor of `#[derive(Clone)]`
3325 #[stable(feature = "rust1", since = "1.0.0")]
3326 impl<T, P> Clone for Split<'_, T, P> where P: Clone + FnMut(&T) -> bool {
3327     fn clone(&self) -> Self {
3328         Split {
3329             v: self.v,
3330             pred: self.pred.clone(),
3331             finished: self.finished,
3332         }
3333     }
3334 }
3335
3336 #[stable(feature = "rust1", since = "1.0.0")]
3337 impl<'a, T, P> Iterator for Split<'a, T, P> where P: FnMut(&T) -> bool {
3338     type Item = &'a [T];
3339
3340     #[inline]
3341     fn next(&mut self) -> Option<&'a [T]> {
3342         if self.finished { return None; }
3343
3344         match self.v.iter().position(|x| (self.pred)(x)) {
3345             None => self.finish(),
3346             Some(idx) => {
3347                 let ret = Some(&self.v[..idx]);
3348                 self.v = &self.v[idx + 1..];
3349                 ret
3350             }
3351         }
3352     }
3353
3354     #[inline]
3355     fn size_hint(&self) -> (usize, Option<usize>) {
3356         if self.finished {
3357             (0, Some(0))
3358         } else {
3359             (1, Some(self.v.len() + 1))
3360         }
3361     }
3362 }
3363
3364 #[stable(feature = "rust1", since = "1.0.0")]
3365 impl<'a, T, P> DoubleEndedIterator for Split<'a, T, P> where P: FnMut(&T) -> bool {
3366     #[inline]
3367     fn next_back(&mut self) -> Option<&'a [T]> {
3368         if self.finished { return None; }
3369
3370         match self.v.iter().rposition(|x| (self.pred)(x)) {
3371             None => self.finish(),
3372             Some(idx) => {
3373                 let ret = Some(&self.v[idx + 1..]);
3374                 self.v = &self.v[..idx];
3375                 ret
3376             }
3377         }
3378     }
3379 }
3380
3381 impl<'a, T, P> SplitIter for Split<'a, T, P> where P: FnMut(&T) -> bool {
3382     #[inline]
3383     fn finish(&mut self) -> Option<&'a [T]> {
3384         if self.finished { None } else { self.finished = true; Some(self.v) }
3385     }
3386 }
3387
3388 #[stable(feature = "fused", since = "1.26.0")]
3389 impl<T, P> FusedIterator for Split<'_, T, P> where P: FnMut(&T) -> bool {}
3390
3391 /// An iterator over the subslices of the vector which are separated
3392 /// by elements that match `pred`.
3393 ///
3394 /// This struct is created by the [`split_mut`] method on [slices].
3395 ///
3396 /// [`split_mut`]: ../../std/primitive.slice.html#method.split_mut
3397 /// [slices]: ../../std/primitive.slice.html
3398 #[stable(feature = "rust1", since = "1.0.0")]
3399 pub struct SplitMut<'a, T:'a, P> where P: FnMut(&T) -> bool {
3400     v: &'a mut [T],
3401     pred: P,
3402     finished: bool
3403 }
3404
3405 #[stable(feature = "core_impl_debug", since = "1.9.0")]
3406 impl<T: fmt::Debug, P> fmt::Debug for SplitMut<'_, T, P> where P: FnMut(&T) -> bool {
3407     fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
3408         f.debug_struct("SplitMut")
3409             .field("v", &self.v)
3410             .field("finished", &self.finished)
3411             .finish()
3412     }
3413 }
3414
3415 impl<'a, T, P> SplitIter for SplitMut<'a, T, P> where P: FnMut(&T) -> bool {
3416     #[inline]
3417     fn finish(&mut self) -> Option<&'a mut [T]> {
3418         if self.finished {
3419             None
3420         } else {
3421             self.finished = true;
3422             Some(mem::replace(&mut self.v, &mut []))
3423         }
3424     }
3425 }
3426
3427 #[stable(feature = "rust1", since = "1.0.0")]
3428 impl<'a, T, P> Iterator for SplitMut<'a, T, P> where P: FnMut(&T) -> bool {
3429     type Item = &'a mut [T];
3430
3431     #[inline]
3432     fn next(&mut self) -> Option<&'a mut [T]> {
3433         if self.finished { return None; }
3434
3435         let idx_opt = { // work around borrowck limitations
3436             let pred = &mut self.pred;
3437             self.v.iter().position(|x| (*pred)(x))
3438         };
3439         match idx_opt {
3440             None => self.finish(),
3441             Some(idx) => {
3442                 let tmp = mem::replace(&mut self.v, &mut []);
3443                 let (head, tail) = tmp.split_at_mut(idx);
3444                 self.v = &mut tail[1..];
3445                 Some(head)
3446             }
3447         }
3448     }
3449
3450     #[inline]
3451     fn size_hint(&self) -> (usize, Option<usize>) {
3452         if self.finished {
3453             (0, Some(0))
3454         } else {
3455             // if the predicate doesn't match anything, we yield one slice
3456             // if it matches every element, we yield len+1 empty slices.
3457             (1, Some(self.v.len() + 1))
3458         }
3459     }
3460 }
3461
3462 #[stable(feature = "rust1", since = "1.0.0")]
3463 impl<'a, T, P> DoubleEndedIterator for SplitMut<'a, T, P> where
3464     P: FnMut(&T) -> bool,
3465 {
3466     #[inline]
3467     fn next_back(&mut self) -> Option<&'a mut [T]> {
3468         if self.finished { return None; }
3469
3470         let idx_opt = { // work around borrowck limitations
3471             let pred = &mut self.pred;
3472             self.v.iter().rposition(|x| (*pred)(x))
3473         };
3474         match idx_opt {
3475             None => self.finish(),
3476             Some(idx) => {
3477                 let tmp = mem::replace(&mut self.v, &mut []);
3478                 let (head, tail) = tmp.split_at_mut(idx);
3479                 self.v = head;
3480                 Some(&mut tail[1..])
3481             }
3482         }
3483     }
3484 }
3485
3486 #[stable(feature = "fused", since = "1.26.0")]
3487 impl<T, P> FusedIterator for SplitMut<'_, T, P> where P: FnMut(&T) -> bool {}
3488
3489 /// An iterator over subslices separated by elements that match a predicate
3490 /// function, starting from the end of the slice.
3491 ///
3492 /// This struct is created by the [`rsplit`] method on [slices].
3493 ///
3494 /// [`rsplit`]: ../../std/primitive.slice.html#method.rsplit
3495 /// [slices]: ../../std/primitive.slice.html
3496 #[stable(feature = "slice_rsplit", since = "1.27.0")]
3497 #[derive(Clone)] // Is this correct, or does it incorrectly require `T: Clone`?
3498 pub struct RSplit<'a, T:'a, P> where P: FnMut(&T) -> bool {
3499     inner: Split<'a, T, P>
3500 }
3501
3502 #[stable(feature = "slice_rsplit", since = "1.27.0")]
3503 impl<T: fmt::Debug, P> fmt::Debug for RSplit<'_, T, P> where P: FnMut(&T) -> bool {
3504     fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
3505         f.debug_struct("RSplit")
3506             .field("v", &self.inner.v)
3507             .field("finished", &self.inner.finished)
3508             .finish()
3509     }
3510 }
3511
3512 #[stable(feature = "slice_rsplit", since = "1.27.0")]
3513 impl<'a, T, P> Iterator for RSplit<'a, T, P> where P: FnMut(&T) -> bool {
3514     type Item = &'a [T];
3515
3516     #[inline]
3517     fn next(&mut self) -> Option<&'a [T]> {
3518         self.inner.next_back()
3519     }
3520
3521     #[inline]
3522     fn size_hint(&self) -> (usize, Option<usize>) {
3523         self.inner.size_hint()
3524     }
3525 }
3526
3527 #[stable(feature = "slice_rsplit", since = "1.27.0")]
3528 impl<'a, T, P> DoubleEndedIterator for RSplit<'a, T, P> where P: FnMut(&T) -> bool {
3529     #[inline]
3530     fn next_back(&mut self) -> Option<&'a [T]> {
3531         self.inner.next()
3532     }
3533 }
3534
3535 #[stable(feature = "slice_rsplit", since = "1.27.0")]
3536 impl<'a, T, P> SplitIter for RSplit<'a, T, P> where P: FnMut(&T) -> bool {
3537     #[inline]
3538     fn finish(&mut self) -> Option<&'a [T]> {
3539         self.inner.finish()
3540     }
3541 }
3542
3543 #[stable(feature = "slice_rsplit", since = "1.27.0")]
3544 impl<T, P> FusedIterator for RSplit<'_, T, P> where P: FnMut(&T) -> bool {}
3545
3546 /// An iterator over the subslices of the vector which are separated
3547 /// by elements that match `pred`, starting from the end of the slice.
3548 ///
3549 /// This struct is created by the [`rsplit_mut`] method on [slices].
3550 ///
3551 /// [`rsplit_mut`]: ../../std/primitive.slice.html#method.rsplit_mut
3552 /// [slices]: ../../std/primitive.slice.html
3553 #[stable(feature = "slice_rsplit", since = "1.27.0")]
3554 pub struct RSplitMut<'a, T:'a, P> where P: FnMut(&T) -> bool {
3555     inner: SplitMut<'a, T, P>
3556 }
3557
3558 #[stable(feature = "slice_rsplit", since = "1.27.0")]
3559 impl<T: fmt::Debug, P> fmt::Debug for RSplitMut<'_, T, P> where P: FnMut(&T) -> bool {
3560     fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
3561         f.debug_struct("RSplitMut")
3562             .field("v", &self.inner.v)
3563             .field("finished", &self.inner.finished)
3564             .finish()
3565     }
3566 }
3567
3568 #[stable(feature = "slice_rsplit", since = "1.27.0")]
3569 impl<'a, T, P> SplitIter for RSplitMut<'a, T, P> where P: FnMut(&T) -> bool {
3570     #[inline]
3571     fn finish(&mut self) -> Option<&'a mut [T]> {
3572         self.inner.finish()
3573     }
3574 }
3575
3576 #[stable(feature = "slice_rsplit", since = "1.27.0")]
3577 impl<'a, T, P> Iterator for RSplitMut<'a, T, P> where P: FnMut(&T) -> bool {
3578     type Item = &'a mut [T];
3579
3580     #[inline]
3581     fn next(&mut self) -> Option<&'a mut [T]> {
3582         self.inner.next_back()
3583     }
3584
3585     #[inline]
3586     fn size_hint(&self) -> (usize, Option<usize>) {
3587         self.inner.size_hint()
3588     }
3589 }
3590
3591 #[stable(feature = "slice_rsplit", since = "1.27.0")]
3592 impl<'a, T, P> DoubleEndedIterator for RSplitMut<'a, T, P> where
3593     P: FnMut(&T) -> bool,
3594 {
3595     #[inline]
3596     fn next_back(&mut self) -> Option<&'a mut [T]> {
3597         self.inner.next()
3598     }
3599 }
3600
3601 #[stable(feature = "slice_rsplit", since = "1.27.0")]
3602 impl<T, P> FusedIterator for RSplitMut<'_, T, P> where P: FnMut(&T) -> bool {}
3603
3604 /// An private iterator over subslices separated by elements that
3605 /// match a predicate function, splitting at most a fixed number of
3606 /// times.
3607 #[derive(Debug)]
3608 struct GenericSplitN<I> {
3609     iter: I,
3610     count: usize,
3611 }
3612
3613 impl<T, I: SplitIter<Item=T>> Iterator for GenericSplitN<I> {
3614     type Item = T;
3615
3616     #[inline]
3617     fn next(&mut self) -> Option<T> {
3618         match self.count {
3619             0 => None,
3620             1 => { self.count -= 1; self.iter.finish() }
3621             _ => { self.count -= 1; self.iter.next() }
3622         }
3623     }
3624
3625     #[inline]
3626     fn size_hint(&self) -> (usize, Option<usize>) {
3627         let (lower, upper_opt) = self.iter.size_hint();
3628         (lower, upper_opt.map(|upper| cmp::min(self.count, upper)))
3629     }
3630 }
3631
3632 /// An iterator over subslices separated by elements that match a predicate
3633 /// function, limited to a given number of splits.
3634 ///
3635 /// This struct is created by the [`splitn`] method on [slices].
3636 ///
3637 /// [`splitn`]: ../../std/primitive.slice.html#method.splitn
3638 /// [slices]: ../../std/primitive.slice.html
3639 #[stable(feature = "rust1", since = "1.0.0")]
3640 pub struct SplitN<'a, T: 'a, P> where P: FnMut(&T) -> bool {
3641     inner: GenericSplitN<Split<'a, T, P>>
3642 }
3643
3644 #[stable(feature = "core_impl_debug", since = "1.9.0")]
3645 impl<T: fmt::Debug, P> fmt::Debug for SplitN<'_, T, P> where P: FnMut(&T) -> bool {
3646     fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
3647         f.debug_struct("SplitN")
3648             .field("inner", &self.inner)
3649             .finish()
3650     }
3651 }
3652
3653 /// An iterator over subslices separated by elements that match a
3654 /// predicate function, limited to a given number of splits, starting
3655 /// from the end of the slice.
3656 ///
3657 /// This struct is created by the [`rsplitn`] method on [slices].
3658 ///
3659 /// [`rsplitn`]: ../../std/primitive.slice.html#method.rsplitn
3660 /// [slices]: ../../std/primitive.slice.html
3661 #[stable(feature = "rust1", since = "1.0.0")]
3662 pub struct RSplitN<'a, T: 'a, P> where P: FnMut(&T) -> bool {
3663     inner: GenericSplitN<RSplit<'a, T, P>>
3664 }
3665
3666 #[stable(feature = "core_impl_debug", since = "1.9.0")]
3667 impl<T: fmt::Debug, P> fmt::Debug for RSplitN<'_, T, P> where P: FnMut(&T) -> bool {
3668     fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
3669         f.debug_struct("RSplitN")
3670             .field("inner", &self.inner)
3671             .finish()
3672     }
3673 }
3674
3675 /// An iterator over subslices separated by elements that match a predicate
3676 /// function, limited to a given number of splits.
3677 ///
3678 /// This struct is created by the [`splitn_mut`] method on [slices].
3679 ///
3680 /// [`splitn_mut`]: ../../std/primitive.slice.html#method.splitn_mut
3681 /// [slices]: ../../std/primitive.slice.html
3682 #[stable(feature = "rust1", since = "1.0.0")]
3683 pub struct SplitNMut<'a, T: 'a, P> where P: FnMut(&T) -> bool {
3684     inner: GenericSplitN<SplitMut<'a, T, P>>
3685 }
3686
3687 #[stable(feature = "core_impl_debug", since = "1.9.0")]
3688 impl<T: fmt::Debug, P> fmt::Debug for SplitNMut<'_, T, P> where P: FnMut(&T) -> bool {
3689     fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
3690         f.debug_struct("SplitNMut")
3691             .field("inner", &self.inner)
3692             .finish()
3693     }
3694 }
3695
3696 /// An iterator over subslices separated by elements that match a
3697 /// predicate function, limited to a given number of splits, starting
3698 /// from the end of the slice.
3699 ///
3700 /// This struct is created by the [`rsplitn_mut`] method on [slices].
3701 ///
3702 /// [`rsplitn_mut`]: ../../std/primitive.slice.html#method.rsplitn_mut
3703 /// [slices]: ../../std/primitive.slice.html
3704 #[stable(feature = "rust1", since = "1.0.0")]
3705 pub struct RSplitNMut<'a, T: 'a, P> where P: FnMut(&T) -> bool {
3706     inner: GenericSplitN<RSplitMut<'a, T, P>>
3707 }
3708
3709 #[stable(feature = "core_impl_debug", since = "1.9.0")]
3710 impl<T: fmt::Debug, P> fmt::Debug for RSplitNMut<'_, T, P> where P: FnMut(&T) -> bool {
3711     fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
3712         f.debug_struct("RSplitNMut")
3713             .field("inner", &self.inner)
3714             .finish()
3715     }
3716 }
3717
3718 macro_rules! forward_iterator {
3719     ($name:ident: $elem:ident, $iter_of:ty) => {
3720         #[stable(feature = "rust1", since = "1.0.0")]
3721         impl<'a, $elem, P> Iterator for $name<'a, $elem, P> where
3722             P: FnMut(&T) -> bool
3723         {
3724             type Item = $iter_of;
3725
3726             #[inline]
3727             fn next(&mut self) -> Option<$iter_of> {
3728                 self.inner.next()
3729             }
3730
3731             #[inline]
3732             fn size_hint(&self) -> (usize, Option<usize>) {
3733                 self.inner.size_hint()
3734             }
3735         }
3736
3737         #[stable(feature = "fused", since = "1.26.0")]
3738         impl<'a, $elem, P> FusedIterator for $name<'a, $elem, P>
3739             where P: FnMut(&T) -> bool {}
3740     }
3741 }
3742
3743 forward_iterator! { SplitN: T, &'a [T] }
3744 forward_iterator! { RSplitN: T, &'a [T] }
3745 forward_iterator! { SplitNMut: T, &'a mut [T] }
3746 forward_iterator! { RSplitNMut: T, &'a mut [T] }
3747
3748 /// An iterator over overlapping subslices of length `size`.
3749 ///
3750 /// This struct is created by the [`windows`] method on [slices].
3751 ///
3752 /// [`windows`]: ../../std/primitive.slice.html#method.windows
3753 /// [slices]: ../../std/primitive.slice.html
3754 #[derive(Debug)]
3755 #[stable(feature = "rust1", since = "1.0.0")]
3756 pub struct Windows<'a, T:'a> {
3757     v: &'a [T],
3758     size: usize
3759 }
3760
3761 // FIXME(#26925) Remove in favor of `#[derive(Clone)]`
3762 #[stable(feature = "rust1", since = "1.0.0")]
3763 impl<T> Clone for Windows<'_, T> {
3764     fn clone(&self) -> Self {
3765         Windows {
3766             v: self.v,
3767             size: self.size,
3768         }
3769     }
3770 }
3771
3772 #[stable(feature = "rust1", since = "1.0.0")]
3773 impl<'a, T> Iterator for Windows<'a, T> {
3774     type Item = &'a [T];
3775
3776     #[inline]
3777     fn next(&mut self) -> Option<&'a [T]> {
3778         if self.size > self.v.len() {
3779             None
3780         } else {
3781             let ret = Some(&self.v[..self.size]);
3782             self.v = &self.v[1..];
3783             ret
3784         }
3785     }
3786
3787     #[inline]
3788     fn size_hint(&self) -> (usize, Option<usize>) {
3789         if self.size > self.v.len() {
3790             (0, Some(0))
3791         } else {
3792             let size = self.v.len() - self.size + 1;
3793             (size, Some(size))
3794         }
3795     }
3796
3797     #[inline]
3798     fn count(self) -> usize {
3799         self.len()
3800     }
3801
3802     #[inline]
3803     fn nth(&mut self, n: usize) -> Option<Self::Item> {
3804         let (end, overflow) = self.size.overflowing_add(n);
3805         if end > self.v.len() || overflow {
3806             self.v = &[];
3807             None
3808         } else {
3809             let nth = &self.v[n..end];
3810             self.v = &self.v[n+1..];
3811             Some(nth)
3812         }
3813     }
3814
3815     #[inline]
3816     fn last(self) -> Option<Self::Item> {
3817         if self.size > self.v.len() {
3818             None
3819         } else {
3820             let start = self.v.len() - self.size;
3821             Some(&self.v[start..])
3822         }
3823     }
3824 }
3825
3826 #[stable(feature = "rust1", since = "1.0.0")]
3827 impl<'a, T> DoubleEndedIterator for Windows<'a, T> {
3828     #[inline]
3829     fn next_back(&mut self) -> Option<&'a [T]> {
3830         if self.size > self.v.len() {
3831             None
3832         } else {
3833             let ret = Some(&self.v[self.v.len()-self.size..]);
3834             self.v = &self.v[..self.v.len()-1];
3835             ret
3836         }
3837     }
3838 }
3839
3840 #[stable(feature = "rust1", since = "1.0.0")]
3841 impl<T> ExactSizeIterator for Windows<'_, T> {}
3842
3843 #[unstable(feature = "trusted_len", issue = "37572")]
3844 unsafe impl<T> TrustedLen for Windows<'_, T> {}
3845
3846 #[stable(feature = "fused", since = "1.26.0")]
3847 impl<T> FusedIterator for Windows<'_, T> {}
3848
3849 #[doc(hidden)]
3850 unsafe impl<'a, T> TrustedRandomAccess for Windows<'a, T> {
3851     unsafe fn get_unchecked(&mut self, i: usize) -> &'a [T] {
3852         from_raw_parts(self.v.as_ptr().add(i), self.size)
3853     }
3854     fn may_have_side_effect() -> bool { false }
3855 }
3856
3857 /// An iterator over a slice in (non-overlapping) chunks (`chunk_size` elements at a
3858 /// time), starting at the beginning of the slice.
3859 ///
3860 /// When the slice len is not evenly divided by the chunk size, the last slice
3861 /// of the iteration will be the remainder.
3862 ///
3863 /// This struct is created by the [`chunks`] method on [slices].
3864 ///
3865 /// [`chunks`]: ../../std/primitive.slice.html#method.chunks
3866 /// [slices]: ../../std/primitive.slice.html
3867 #[derive(Debug)]
3868 #[stable(feature = "rust1", since = "1.0.0")]
3869 pub struct Chunks<'a, T:'a> {
3870     v: &'a [T],
3871     chunk_size: usize
3872 }
3873
3874 // FIXME(#26925) Remove in favor of `#[derive(Clone)]`
3875 #[stable(feature = "rust1", since = "1.0.0")]
3876 impl<T> Clone for Chunks<'_, T> {
3877     fn clone(&self) -> Self {
3878         Chunks {
3879             v: self.v,
3880             chunk_size: self.chunk_size,
3881         }
3882     }
3883 }
3884
3885 #[stable(feature = "rust1", since = "1.0.0")]
3886 impl<'a, T> Iterator for Chunks<'a, T> {
3887     type Item = &'a [T];
3888
3889     #[inline]
3890     fn next(&mut self) -> Option<&'a [T]> {
3891         if self.v.is_empty() {
3892             None
3893         } else {
3894             let chunksz = cmp::min(self.v.len(), self.chunk_size);
3895             let (fst, snd) = self.v.split_at(chunksz);
3896             self.v = snd;
3897             Some(fst)
3898         }
3899     }
3900
3901     #[inline]
3902     fn size_hint(&self) -> (usize, Option<usize>) {
3903         if self.v.is_empty() {
3904             (0, Some(0))
3905         } else {
3906             let n = self.v.len() / self.chunk_size;
3907             let rem = self.v.len() % self.chunk_size;
3908             let n = if rem > 0 { n+1 } else { n };
3909             (n, Some(n))
3910         }
3911     }
3912
3913     #[inline]
3914     fn count(self) -> usize {
3915         self.len()
3916     }
3917
3918     #[inline]
3919     fn nth(&mut self, n: usize) -> Option<Self::Item> {
3920         let (start, overflow) = n.overflowing_mul(self.chunk_size);
3921         if start >= self.v.len() || overflow {
3922             self.v = &[];
3923             None
3924         } else {
3925             let end = match start.checked_add(self.chunk_size) {
3926                 Some(sum) => cmp::min(self.v.len(), sum),
3927                 None => self.v.len(),
3928             };
3929             let nth = &self.v[start..end];
3930             self.v = &self.v[end..];
3931             Some(nth)
3932         }
3933     }
3934
3935     #[inline]
3936     fn last(self) -> Option<Self::Item> {
3937         if self.v.is_empty() {
3938             None
3939         } else {
3940             let start = (self.v.len() - 1) / self.chunk_size * self.chunk_size;
3941             Some(&self.v[start..])
3942         }
3943     }
3944 }
3945
3946 #[stable(feature = "rust1", since = "1.0.0")]
3947 impl<'a, T> DoubleEndedIterator for Chunks<'a, T> {
3948     #[inline]
3949     fn next_back(&mut self) -> Option<&'a [T]> {
3950         if self.v.is_empty() {
3951             None
3952         } else {
3953             let remainder = self.v.len() % self.chunk_size;
3954             let chunksz = if remainder != 0 { remainder } else { self.chunk_size };
3955             let (fst, snd) = self.v.split_at(self.v.len() - chunksz);
3956             self.v = fst;
3957             Some(snd)
3958         }
3959     }
3960 }
3961
3962 #[stable(feature = "rust1", since = "1.0.0")]
3963 impl<T> ExactSizeIterator for Chunks<'_, T> {}
3964
3965 #[unstable(feature = "trusted_len", issue = "37572")]
3966 unsafe impl<T> TrustedLen for Chunks<'_, T> {}
3967
3968 #[stable(feature = "fused", since = "1.26.0")]
3969 impl<T> FusedIterator for Chunks<'_, T> {}
3970
3971 #[doc(hidden)]
3972 unsafe impl<'a, T> TrustedRandomAccess for Chunks<'a, T> {
3973     unsafe fn get_unchecked(&mut self, i: usize) -> &'a [T] {
3974         let start = i * self.chunk_size;
3975         let end = match start.checked_add(self.chunk_size) {
3976             None => self.v.len(),
3977             Some(end) => cmp::min(end, self.v.len()),
3978         };
3979         from_raw_parts(self.v.as_ptr().add(start), end - start)
3980     }
3981     fn may_have_side_effect() -> bool { false }
3982 }
3983
3984 /// An iterator over a slice in (non-overlapping) mutable chunks (`chunk_size`
3985 /// elements at a time), starting at the beginning of the slice.
3986 ///
3987 /// When the slice len is not evenly divided by the chunk size, the last slice
3988 /// of the iteration will be the remainder.
3989 ///
3990 /// This struct is created by the [`chunks_mut`] method on [slices].
3991 ///
3992 /// [`chunks_mut`]: ../../std/primitive.slice.html#method.chunks_mut
3993 /// [slices]: ../../std/primitive.slice.html
3994 #[derive(Debug)]
3995 #[stable(feature = "rust1", since = "1.0.0")]
3996 pub struct ChunksMut<'a, T:'a> {
3997     v: &'a mut [T],
3998     chunk_size: usize
3999 }
4000
4001 #[stable(feature = "rust1", since = "1.0.0")]
4002 impl<'a, T> Iterator for ChunksMut<'a, T> {
4003     type Item = &'a mut [T];
4004
4005     #[inline]
4006     fn next(&mut self) -> Option<&'a mut [T]> {
4007         if self.v.is_empty() {
4008             None
4009         } else {
4010             let sz = cmp::min(self.v.len(), self.chunk_size);
4011             let tmp = mem::replace(&mut self.v, &mut []);
4012             let (head, tail) = tmp.split_at_mut(sz);
4013             self.v = tail;
4014             Some(head)
4015         }
4016     }
4017
4018     #[inline]
4019     fn size_hint(&self) -> (usize, Option<usize>) {
4020         if self.v.is_empty() {
4021             (0, Some(0))
4022         } else {
4023             let n = self.v.len() / self.chunk_size;
4024             let rem = self.v.len() % self.chunk_size;
4025             let n = if rem > 0 { n + 1 } else { n };
4026             (n, Some(n))
4027         }
4028     }
4029
4030     #[inline]
4031     fn count(self) -> usize {
4032         self.len()
4033     }
4034
4035     #[inline]
4036     fn nth(&mut self, n: usize) -> Option<&'a mut [T]> {
4037         let (start, overflow) = n.overflowing_mul(self.chunk_size);
4038         if start >= self.v.len() || overflow {
4039             self.v = &mut [];
4040             None
4041         } else {
4042             let end = match start.checked_add(self.chunk_size) {
4043                 Some(sum) => cmp::min(self.v.len(), sum),
4044                 None => self.v.len(),
4045             };
4046             let tmp = mem::replace(&mut self.v, &mut []);
4047             let (head, tail) = tmp.split_at_mut(end);
4048             let (_, nth) =  head.split_at_mut(start);
4049             self.v = tail;
4050             Some(nth)
4051         }
4052     }
4053
4054     #[inline]
4055     fn last(self) -> Option<Self::Item> {
4056         if self.v.is_empty() {
4057             None
4058         } else {
4059             let start = (self.v.len() - 1) / self.chunk_size * self.chunk_size;
4060             Some(&mut self.v[start..])
4061         }
4062     }
4063 }
4064
4065 #[stable(feature = "rust1", since = "1.0.0")]
4066 impl<'a, T> DoubleEndedIterator for ChunksMut<'a, T> {
4067     #[inline]
4068     fn next_back(&mut self) -> Option<&'a mut [T]> {
4069         if self.v.is_empty() {
4070             None
4071         } else {
4072             let remainder = self.v.len() % self.chunk_size;
4073             let sz = if remainder != 0 { remainder } else { self.chunk_size };
4074             let tmp = mem::replace(&mut self.v, &mut []);
4075             let tmp_len = tmp.len();
4076             let (head, tail) = tmp.split_at_mut(tmp_len - sz);
4077             self.v = head;
4078             Some(tail)
4079         }
4080     }
4081 }
4082
4083 #[stable(feature = "rust1", since = "1.0.0")]
4084 impl<T> ExactSizeIterator for ChunksMut<'_, T> {}
4085
4086 #[unstable(feature = "trusted_len", issue = "37572")]
4087 unsafe impl<T> TrustedLen for ChunksMut<'_, T> {}
4088
4089 #[stable(feature = "fused", since = "1.26.0")]
4090 impl<T> FusedIterator for ChunksMut<'_, T> {}
4091
4092 #[doc(hidden)]
4093 unsafe impl<'a, T> TrustedRandomAccess for ChunksMut<'a, T> {
4094     unsafe fn get_unchecked(&mut self, i: usize) -> &'a mut [T] {
4095         let start = i * self.chunk_size;
4096         let end = match start.checked_add(self.chunk_size) {
4097             None => self.v.len(),
4098             Some(end) => cmp::min(end, self.v.len()),
4099         };
4100         from_raw_parts_mut(self.v.as_mut_ptr().add(start), end - start)
4101     }
4102     fn may_have_side_effect() -> bool { false }
4103 }
4104
4105 /// An iterator over a slice in (non-overlapping) chunks (`chunk_size` elements at a
4106 /// time), starting at the beginning of the slice.
4107 ///
4108 /// When the slice len is not evenly divided by the chunk size, the last
4109 /// up to `chunk_size-1` elements will be omitted but can be retrieved from
4110 /// the [`remainder`] function from the iterator.
4111 ///
4112 /// This struct is created by the [`chunks_exact`] method on [slices].
4113 ///
4114 /// [`chunks_exact`]: ../../std/primitive.slice.html#method.chunks_exact
4115 /// [`remainder`]: ../../std/slice/struct.ChunksExact.html#method.remainder
4116 /// [slices]: ../../std/primitive.slice.html
4117 #[derive(Debug)]
4118 #[stable(feature = "chunks_exact", since = "1.31.0")]
4119 pub struct ChunksExact<'a, T:'a> {
4120     v: &'a [T],
4121     rem: &'a [T],
4122     chunk_size: usize
4123 }
4124
4125 impl<'a, T> ChunksExact<'a, T> {
4126     /// Return the remainder of the original slice that is not going to be
4127     /// returned by the iterator. The returned slice has at most `chunk_size-1`
4128     /// elements.
4129     #[stable(feature = "chunks_exact", since = "1.31.0")]
4130     pub fn remainder(&self) -> &'a [T] {
4131         self.rem
4132     }
4133 }
4134
4135 // FIXME(#26925) Remove in favor of `#[derive(Clone)]`
4136 #[stable(feature = "chunks_exact", since = "1.31.0")]
4137 impl<T> Clone for ChunksExact<'_, T> {
4138     fn clone(&self) -> Self {
4139         ChunksExact {
4140             v: self.v,
4141             rem: self.rem,
4142             chunk_size: self.chunk_size,
4143         }
4144     }
4145 }
4146
4147 #[stable(feature = "chunks_exact", since = "1.31.0")]
4148 impl<'a, T> Iterator for ChunksExact<'a, T> {
4149     type Item = &'a [T];
4150
4151     #[inline]
4152     fn next(&mut self) -> Option<&'a [T]> {
4153         if self.v.len() < self.chunk_size {
4154             None
4155         } else {
4156             let (fst, snd) = self.v.split_at(self.chunk_size);
4157             self.v = snd;
4158             Some(fst)
4159         }
4160     }
4161
4162     #[inline]
4163     fn size_hint(&self) -> (usize, Option<usize>) {
4164         let n = self.v.len() / self.chunk_size;
4165         (n, Some(n))
4166     }
4167
4168     #[inline]
4169     fn count(self) -> usize {
4170         self.len()
4171     }
4172
4173     #[inline]
4174     fn nth(&mut self, n: usize) -> Option<Self::Item> {
4175         let (start, overflow) = n.overflowing_mul(self.chunk_size);
4176         if start >= self.v.len() || overflow {
4177             self.v = &[];
4178             None
4179         } else {
4180             let (_, snd) = self.v.split_at(start);
4181             self.v = snd;
4182             self.next()
4183         }
4184     }
4185
4186     #[inline]
4187     fn last(mut self) -> Option<Self::Item> {
4188         self.next_back()
4189     }
4190 }
4191
4192 #[stable(feature = "chunks_exact", since = "1.31.0")]
4193 impl<'a, T> DoubleEndedIterator for ChunksExact<'a, T> {
4194     #[inline]
4195     fn next_back(&mut self) -> Option<&'a [T]> {
4196         if self.v.len() < self.chunk_size {
4197             None
4198         } else {
4199             let (fst, snd) = self.v.split_at(self.v.len() - self.chunk_size);
4200             self.v = fst;
4201             Some(snd)
4202         }
4203     }
4204 }
4205
4206 #[stable(feature = "chunks_exact", since = "1.31.0")]
4207 impl<T> ExactSizeIterator for ChunksExact<'_, T> {
4208     fn is_empty(&self) -> bool {
4209         self.v.is_empty()
4210     }
4211 }
4212
4213 #[unstable(feature = "trusted_len", issue = "37572")]
4214 unsafe impl<T> TrustedLen for ChunksExact<'_, T> {}
4215
4216 #[stable(feature = "chunks_exact", since = "1.31.0")]
4217 impl<T> FusedIterator for ChunksExact<'_, T> {}
4218
4219 #[doc(hidden)]
4220 #[stable(feature = "chunks_exact", since = "1.31.0")]
4221 unsafe impl<'a, T> TrustedRandomAccess for ChunksExact<'a, T> {
4222     unsafe fn get_unchecked(&mut self, i: usize) -> &'a [T] {
4223         let start = i * self.chunk_size;
4224         from_raw_parts(self.v.as_ptr().add(start), self.chunk_size)
4225     }
4226     fn may_have_side_effect() -> bool { false }
4227 }
4228
4229 /// An iterator over a slice in (non-overlapping) mutable chunks (`chunk_size`
4230 /// elements at a time), starting at the beginning of the slice.
4231 ///
4232 /// When the slice len is not evenly divided by the chunk size, the last up to
4233 /// `chunk_size-1` elements will be omitted but can be retrieved from the
4234 /// [`into_remainder`] function from the iterator.
4235 ///
4236 /// This struct is created by the [`chunks_exact_mut`] method on [slices].
4237 ///
4238 /// [`chunks_exact_mut`]: ../../std/primitive.slice.html#method.chunks_exact_mut
4239 /// [`into_remainder`]: ../../std/slice/struct.ChunksExactMut.html#method.into_remainder
4240 /// [slices]: ../../std/primitive.slice.html
4241 #[derive(Debug)]
4242 #[stable(feature = "chunks_exact", since = "1.31.0")]
4243 pub struct ChunksExactMut<'a, T:'a> {
4244     v: &'a mut [T],
4245     rem: &'a mut [T],
4246     chunk_size: usize
4247 }
4248
4249 impl<'a, T> ChunksExactMut<'a, T> {
4250     /// Return the remainder of the original slice that is not going to be
4251     /// returned by the iterator. The returned slice has at most `chunk_size-1`
4252     /// elements.
4253     #[stable(feature = "chunks_exact", since = "1.31.0")]
4254     pub fn into_remainder(self) -> &'a mut [T] {
4255         self.rem
4256     }
4257 }
4258
4259 #[stable(feature = "chunks_exact", since = "1.31.0")]
4260 impl<'a, T> Iterator for ChunksExactMut<'a, T> {
4261     type Item = &'a mut [T];
4262
4263     #[inline]
4264     fn next(&mut self) -> Option<&'a mut [T]> {
4265         if self.v.len() < self.chunk_size {
4266             None
4267         } else {
4268             let tmp = mem::replace(&mut self.v, &mut []);
4269             let (head, tail) = tmp.split_at_mut(self.chunk_size);
4270             self.v = tail;
4271             Some(head)
4272         }
4273     }
4274
4275     #[inline]
4276     fn size_hint(&self) -> (usize, Option<usize>) {
4277         let n = self.v.len() / self.chunk_size;
4278         (n, Some(n))
4279     }
4280
4281     #[inline]
4282     fn count(self) -> usize {
4283         self.len()
4284     }
4285
4286     #[inline]
4287     fn nth(&mut self, n: usize) -> Option<&'a mut [T]> {
4288         let (start, overflow) = n.overflowing_mul(self.chunk_size);
4289         if start >= self.v.len() || overflow {
4290             self.v = &mut [];
4291             None
4292         } else {
4293             let tmp = mem::replace(&mut self.v, &mut []);
4294             let (_, snd) = tmp.split_at_mut(start);
4295             self.v = snd;
4296             self.next()
4297         }
4298     }
4299
4300     #[inline]
4301     fn last(mut self) -> Option<Self::Item> {
4302         self.next_back()
4303     }
4304 }
4305
4306 #[stable(feature = "chunks_exact", since = "1.31.0")]
4307 impl<'a, T> DoubleEndedIterator for ChunksExactMut<'a, T> {
4308     #[inline]
4309     fn next_back(&mut self) -> Option<&'a mut [T]> {
4310         if self.v.len() < self.chunk_size {
4311             None
4312         } else {
4313             let tmp = mem::replace(&mut self.v, &mut []);
4314             let tmp_len = tmp.len();
4315             let (head, tail) = tmp.split_at_mut(tmp_len - self.chunk_size);
4316             self.v = head;
4317             Some(tail)
4318         }
4319     }
4320 }
4321
4322 #[stable(feature = "chunks_exact", since = "1.31.0")]
4323 impl<T> ExactSizeIterator for ChunksExactMut<'_, T> {
4324     fn is_empty(&self) -> bool {
4325         self.v.is_empty()
4326     }
4327 }
4328
4329 #[unstable(feature = "trusted_len", issue = "37572")]
4330 unsafe impl<T> TrustedLen for ChunksExactMut<'_, T> {}
4331
4332 #[stable(feature = "chunks_exact", since = "1.31.0")]
4333 impl<T> FusedIterator for ChunksExactMut<'_, T> {}
4334
4335 #[doc(hidden)]
4336 #[stable(feature = "chunks_exact", since = "1.31.0")]
4337 unsafe impl<'a, T> TrustedRandomAccess for ChunksExactMut<'a, T> {
4338     unsafe fn get_unchecked(&mut self, i: usize) -> &'a mut [T] {
4339         let start = i * self.chunk_size;
4340         from_raw_parts_mut(self.v.as_mut_ptr().add(start), self.chunk_size)
4341     }
4342     fn may_have_side_effect() -> bool { false }
4343 }
4344
4345 /// An iterator over a slice in (non-overlapping) chunks (`chunk_size` elements at a
4346 /// time), starting at the end of the slice.
4347 ///
4348 /// When the slice len is not evenly divided by the chunk size, the last slice
4349 /// of the iteration will be the remainder.
4350 ///
4351 /// This struct is created by the [`rchunks`] method on [slices].
4352 ///
4353 /// [`rchunks`]: ../../std/primitive.slice.html#method.rchunks
4354 /// [slices]: ../../std/primitive.slice.html
4355 #[derive(Debug)]
4356 #[stable(feature = "rchunks", since = "1.31.0")]
4357 pub struct RChunks<'a, T:'a> {
4358     v: &'a [T],
4359     chunk_size: usize
4360 }
4361
4362 // FIXME(#26925) Remove in favor of `#[derive(Clone)]`
4363 #[stable(feature = "rchunks", since = "1.31.0")]
4364 impl<'a, T> Clone for RChunks<'a, T> {
4365     fn clone(&self) -> RChunks<'a, T> {
4366         RChunks {
4367             v: self.v,
4368             chunk_size: self.chunk_size,
4369         }
4370     }
4371 }
4372
4373 #[stable(feature = "rchunks", since = "1.31.0")]
4374 impl<'a, T> Iterator for RChunks<'a, T> {
4375     type Item = &'a [T];
4376
4377     #[inline]
4378     fn next(&mut self) -> Option<&'a [T]> {
4379         if self.v.is_empty() {
4380             None
4381         } else {
4382             let chunksz = cmp::min(self.v.len(), self.chunk_size);
4383             let (fst, snd) = self.v.split_at(self.v.len() - chunksz);
4384             self.v = fst;
4385             Some(snd)
4386         }
4387     }
4388
4389     #[inline]
4390     fn size_hint(&self) -> (usize, Option<usize>) {
4391         if self.v.is_empty() {
4392             (0, Some(0))
4393         } else {
4394             let n = self.v.len() / self.chunk_size;
4395             let rem = self.v.len() % self.chunk_size;
4396             let n = if rem > 0 { n+1 } else { n };
4397             (n, Some(n))
4398         }
4399     }
4400
4401     #[inline]
4402     fn count(self) -> usize {
4403         self.len()
4404     }
4405
4406     #[inline]
4407     fn nth(&mut self, n: usize) -> Option<Self::Item> {
4408         let (end, overflow) = n.overflowing_mul(self.chunk_size);
4409         if end >= self.v.len() || overflow {
4410             self.v = &[];
4411             None
4412         } else {
4413             // Can't underflow because of the check above
4414             let end = self.v.len() - end;
4415             let start = match end.checked_sub(self.chunk_size) {
4416                 Some(sum) => sum,
4417                 None => 0,
4418             };
4419             let nth = &self.v[start..end];
4420             self.v = &self.v[0..start];
4421             Some(nth)
4422         }
4423     }
4424
4425     #[inline]
4426     fn last(self) -> Option<Self::Item> {
4427         if self.v.is_empty() {
4428             None
4429         } else {
4430             let rem = self.v.len() % self.chunk_size;
4431             let end = if rem == 0 { self.chunk_size } else { rem };
4432             Some(&self.v[0..end])
4433         }
4434     }
4435 }
4436
4437 #[stable(feature = "rchunks", since = "1.31.0")]
4438 impl<'a, T> DoubleEndedIterator for RChunks<'a, T> {
4439     #[inline]
4440     fn next_back(&mut self) -> Option<&'a [T]> {
4441         if self.v.is_empty() {
4442             None
4443         } else {
4444             let remainder = self.v.len() % self.chunk_size;
4445             let chunksz = if remainder != 0 { remainder } else { self.chunk_size };
4446             let (fst, snd) = self.v.split_at(chunksz);
4447             self.v = snd;
4448             Some(fst)
4449         }
4450     }
4451 }
4452
4453 #[stable(feature = "rchunks", since = "1.31.0")]
4454 impl<'a, T> ExactSizeIterator for RChunks<'a, T> {}
4455
4456 #[unstable(feature = "trusted_len", issue = "37572")]
4457 unsafe impl<'a, T> TrustedLen for RChunks<'a, T> {}
4458
4459 #[stable(feature = "rchunks", since = "1.31.0")]
4460 impl<'a, T> FusedIterator for RChunks<'a, T> {}
4461
4462 #[doc(hidden)]
4463 #[stable(feature = "rchunks", since = "1.31.0")]
4464 unsafe impl<'a, T> TrustedRandomAccess for RChunks<'a, T> {
4465     unsafe fn get_unchecked(&mut self, i: usize) -> &'a [T] {
4466         let end = self.v.len() - i * self.chunk_size;
4467         let start = match end.checked_sub(self.chunk_size) {
4468             None => 0,
4469             Some(start) => start,
4470         };
4471         from_raw_parts(self.v.as_ptr().add(start), end - start)
4472     }
4473     fn may_have_side_effect() -> bool { false }
4474 }
4475
4476 /// An iterator over a slice in (non-overlapping) mutable chunks (`chunk_size`
4477 /// elements at a time), starting at the end of the slice.
4478 ///
4479 /// When the slice len is not evenly divided by the chunk size, the last slice
4480 /// of the iteration will be the remainder.
4481 ///
4482 /// This struct is created by the [`rchunks_mut`] method on [slices].
4483 ///
4484 /// [`rchunks_mut`]: ../../std/primitive.slice.html#method.rchunks_mut
4485 /// [slices]: ../../std/primitive.slice.html
4486 #[derive(Debug)]
4487 #[stable(feature = "rchunks", since = "1.31.0")]
4488 pub struct RChunksMut<'a, T:'a> {
4489     v: &'a mut [T],
4490     chunk_size: usize
4491 }
4492
4493 #[stable(feature = "rchunks", since = "1.31.0")]
4494 impl<'a, T> Iterator for RChunksMut<'a, T> {
4495     type Item = &'a mut [T];
4496
4497     #[inline]
4498     fn next(&mut self) -> Option<&'a mut [T]> {
4499         if self.v.is_empty() {
4500             None
4501         } else {
4502             let sz = cmp::min(self.v.len(), self.chunk_size);
4503             let tmp = mem::replace(&mut self.v, &mut []);
4504             let tmp_len = tmp.len();
4505             let (head, tail) = tmp.split_at_mut(tmp_len - sz);
4506             self.v = head;
4507             Some(tail)
4508         }
4509     }
4510
4511     #[inline]
4512     fn size_hint(&self) -> (usize, Option<usize>) {
4513         if self.v.is_empty() {
4514             (0, Some(0))
4515         } else {
4516             let n = self.v.len() / self.chunk_size;
4517             let rem = self.v.len() % self.chunk_size;
4518             let n = if rem > 0 { n + 1 } else { n };
4519             (n, Some(n))
4520         }
4521     }
4522
4523     #[inline]
4524     fn count(self) -> usize {
4525         self.len()
4526     }
4527
4528     #[inline]
4529     fn nth(&mut self, n: usize) -> Option<&'a mut [T]> {
4530         let (end, overflow) = n.overflowing_mul(self.chunk_size);
4531         if end >= self.v.len() || overflow {
4532             self.v = &mut [];
4533             None
4534         } else {
4535             // Can't underflow because of the check above
4536             let end = self.v.len() - end;
4537             let start = match end.checked_sub(self.chunk_size) {
4538                 Some(sum) => sum,
4539                 None => 0,
4540             };
4541             let tmp = mem::replace(&mut self.v, &mut []);
4542             let (head, tail) = tmp.split_at_mut(start);
4543             let (nth, _) = tail.split_at_mut(end - start);
4544             self.v = head;
4545             Some(nth)
4546         }
4547     }
4548
4549     #[inline]
4550     fn last(self) -> Option<Self::Item> {
4551         if self.v.is_empty() {
4552             None
4553         } else {
4554             let rem = self.v.len() % self.chunk_size;
4555             let end = if rem == 0 { self.chunk_size } else { rem };
4556             Some(&mut self.v[0..end])
4557         }
4558     }
4559 }
4560
4561 #[stable(feature = "rchunks", since = "1.31.0")]
4562 impl<'a, T> DoubleEndedIterator for RChunksMut<'a, T> {
4563     #[inline]
4564     fn next_back(&mut self) -> Option<&'a mut [T]> {
4565         if self.v.is_empty() {
4566             None
4567         } else {
4568             let remainder = self.v.len() % self.chunk_size;
4569             let sz = if remainder != 0 { remainder } else { self.chunk_size };
4570             let tmp = mem::replace(&mut self.v, &mut []);
4571             let (head, tail) = tmp.split_at_mut(sz);
4572             self.v = tail;
4573             Some(head)
4574         }
4575     }
4576 }
4577
4578 #[stable(feature = "rchunks", since = "1.31.0")]
4579 impl<'a, T> ExactSizeIterator for RChunksMut<'a, T> {}
4580
4581 #[unstable(feature = "trusted_len", issue = "37572")]
4582 unsafe impl<'a, T> TrustedLen for RChunksMut<'a, T> {}
4583
4584 #[stable(feature = "rchunks", since = "1.31.0")]
4585 impl<'a, T> FusedIterator for RChunksMut<'a, T> {}
4586
4587 #[doc(hidden)]
4588 #[stable(feature = "rchunks", since = "1.31.0")]
4589 unsafe impl<'a, T> TrustedRandomAccess for RChunksMut<'a, T> {
4590     unsafe fn get_unchecked(&mut self, i: usize) -> &'a mut [T] {
4591         let end = self.v.len() - i * self.chunk_size;
4592         let start = match end.checked_sub(self.chunk_size) {
4593             None => 0,
4594             Some(start) => start,
4595         };
4596         from_raw_parts_mut(self.v.as_mut_ptr().add(start), end - start)
4597     }
4598     fn may_have_side_effect() -> bool { false }
4599 }
4600
4601 /// An iterator over a slice in (non-overlapping) chunks (`chunk_size` elements at a
4602 /// time), starting at the end of the slice.
4603 ///
4604 /// When the slice len is not evenly divided by the chunk size, the last
4605 /// up to `chunk_size-1` elements will be omitted but can be retrieved from
4606 /// the [`remainder`] function from the iterator.
4607 ///
4608 /// This struct is created by the [`rchunks_exact`] method on [slices].
4609 ///
4610 /// [`rchunks_exact`]: ../../std/primitive.slice.html#method.rchunks_exact
4611 /// [`remainder`]: ../../std/slice/struct.ChunksExact.html#method.remainder
4612 /// [slices]: ../../std/primitive.slice.html
4613 #[derive(Debug)]
4614 #[stable(feature = "rchunks", since = "1.31.0")]
4615 pub struct RChunksExact<'a, T:'a> {
4616     v: &'a [T],
4617     rem: &'a [T],
4618     chunk_size: usize
4619 }
4620
4621 impl<'a, T> RChunksExact<'a, T> {
4622     /// Return the remainder of the original slice that is not going to be
4623     /// returned by the iterator. The returned slice has at most `chunk_size-1`
4624     /// elements.
4625     #[stable(feature = "rchunks", since = "1.31.0")]
4626     pub fn remainder(&self) -> &'a [T] {
4627         self.rem
4628     }
4629 }
4630
4631 // FIXME(#26925) Remove in favor of `#[derive(Clone)]`
4632 #[stable(feature = "rchunks", since = "1.31.0")]
4633 impl<'a, T> Clone for RChunksExact<'a, T> {
4634     fn clone(&self) -> RChunksExact<'a, T> {
4635         RChunksExact {
4636             v: self.v,
4637             rem: self.rem,
4638             chunk_size: self.chunk_size,
4639         }
4640     }
4641 }
4642
4643 #[stable(feature = "rchunks", since = "1.31.0")]
4644 impl<'a, T> Iterator for RChunksExact<'a, T> {
4645     type Item = &'a [T];
4646
4647     #[inline]
4648     fn next(&mut self) -> Option<&'a [T]> {
4649         if self.v.len() < self.chunk_size {
4650             None
4651         } else {
4652             let (fst, snd) = self.v.split_at(self.v.len() - self.chunk_size);
4653             self.v = fst;
4654             Some(snd)
4655         }
4656     }
4657
4658     #[inline]
4659     fn size_hint(&self) -> (usize, Option<usize>) {
4660         let n = self.v.len() / self.chunk_size;
4661         (n, Some(n))
4662     }
4663
4664     #[inline]
4665     fn count(self) -> usize {
4666         self.len()
4667     }
4668
4669     #[inline]
4670     fn nth(&mut self, n: usize) -> Option<Self::Item> {
4671         let (end, overflow) = n.overflowing_mul(self.chunk_size);
4672         if end >= self.v.len() || overflow {
4673             self.v = &[];
4674             None
4675         } else {
4676             let (fst, _) = self.v.split_at(self.v.len() - end);
4677             self.v = fst;
4678             self.next()
4679         }
4680     }
4681
4682     #[inline]
4683     fn last(mut self) -> Option<Self::Item> {
4684         self.next_back()
4685     }
4686 }
4687
4688 #[stable(feature = "rchunks", since = "1.31.0")]
4689 impl<'a, T> DoubleEndedIterator for RChunksExact<'a, T> {
4690     #[inline]
4691     fn next_back(&mut self) -> Option<&'a [T]> {
4692         if self.v.len() < self.chunk_size {
4693             None
4694         } else {
4695             let (fst, snd) = self.v.split_at(self.chunk_size);
4696             self.v = snd;
4697             Some(fst)
4698         }
4699     }
4700 }
4701
4702 #[stable(feature = "rchunks", since = "1.31.0")]
4703 impl<'a, T> ExactSizeIterator for RChunksExact<'a, T> {
4704     fn is_empty(&self) -> bool {
4705         self.v.is_empty()
4706     }
4707 }
4708
4709 #[unstable(feature = "trusted_len", issue = "37572")]
4710 unsafe impl<'a, T> TrustedLen for RChunksExact<'a, T> {}
4711
4712 #[stable(feature = "rchunks", since = "1.31.0")]
4713 impl<'a, T> FusedIterator for RChunksExact<'a, T> {}
4714
4715 #[doc(hidden)]
4716 #[stable(feature = "rchunks", since = "1.31.0")]
4717 unsafe impl<'a, T> TrustedRandomAccess for RChunksExact<'a, T> {
4718     unsafe fn get_unchecked(&mut self, i: usize) -> &'a [T] {
4719         let end = self.v.len() - i * self.chunk_size;
4720         let start = end - self.chunk_size;
4721         from_raw_parts(self.v.as_ptr().add(start), self.chunk_size)
4722     }
4723     fn may_have_side_effect() -> bool { false }
4724 }
4725
4726 /// An iterator over a slice in (non-overlapping) mutable chunks (`chunk_size`
4727 /// elements at a time), starting at the end of the slice.
4728 ///
4729 /// When the slice len is not evenly divided by the chunk size, the last up to
4730 /// `chunk_size-1` elements will be omitted but can be retrieved from the
4731 /// [`into_remainder`] function from the iterator.
4732 ///
4733 /// This struct is created by the [`rchunks_exact_mut`] method on [slices].
4734 ///
4735 /// [`rchunks_exact_mut`]: ../../std/primitive.slice.html#method.rchunks_exact_mut
4736 /// [`into_remainder`]: ../../std/slice/struct.ChunksExactMut.html#method.into_remainder
4737 /// [slices]: ../../std/primitive.slice.html
4738 #[derive(Debug)]
4739 #[stable(feature = "rchunks", since = "1.31.0")]
4740 pub struct RChunksExactMut<'a, T:'a> {
4741     v: &'a mut [T],
4742     rem: &'a mut [T],
4743     chunk_size: usize
4744 }
4745
4746 impl<'a, T> RChunksExactMut<'a, T> {
4747     /// Return the remainder of the original slice that is not going to be
4748     /// returned by the iterator. The returned slice has at most `chunk_size-1`
4749     /// elements.
4750     #[stable(feature = "rchunks", since = "1.31.0")]
4751     pub fn into_remainder(self) -> &'a mut [T] {
4752         self.rem
4753     }
4754 }
4755
4756 #[stable(feature = "rchunks", since = "1.31.0")]
4757 impl<'a, T> Iterator for RChunksExactMut<'a, T> {
4758     type Item = &'a mut [T];
4759
4760     #[inline]
4761     fn next(&mut self) -> Option<&'a mut [T]> {
4762         if self.v.len() < self.chunk_size {
4763             None
4764         } else {
4765             let tmp = mem::replace(&mut self.v, &mut []);
4766             let tmp_len = tmp.len();
4767             let (head, tail) = tmp.split_at_mut(tmp_len - self.chunk_size);
4768             self.v = head;
4769             Some(tail)
4770         }
4771     }
4772
4773     #[inline]
4774     fn size_hint(&self) -> (usize, Option<usize>) {
4775         let n = self.v.len() / self.chunk_size;
4776         (n, Some(n))
4777     }
4778
4779     #[inline]
4780     fn count(self) -> usize {
4781         self.len()
4782     }
4783
4784     #[inline]
4785     fn nth(&mut self, n: usize) -> Option<&'a mut [T]> {
4786         let (end, overflow) = n.overflowing_mul(self.chunk_size);
4787         if end >= self.v.len() || overflow {
4788             self.v = &mut [];
4789             None
4790         } else {
4791             let tmp = mem::replace(&mut self.v, &mut []);
4792             let tmp_len = tmp.len();
4793             let (fst, _) = tmp.split_at_mut(tmp_len - end);
4794             self.v = fst;
4795             self.next()
4796         }
4797     }
4798
4799     #[inline]
4800     fn last(mut self) -> Option<Self::Item> {
4801         self.next_back()
4802     }
4803 }
4804
4805 #[stable(feature = "rchunks", since = "1.31.0")]
4806 impl<'a, T> DoubleEndedIterator for RChunksExactMut<'a, T> {
4807     #[inline]
4808     fn next_back(&mut self) -> Option<&'a mut [T]> {
4809         if self.v.len() < self.chunk_size {
4810             None
4811         } else {
4812             let tmp = mem::replace(&mut self.v, &mut []);
4813             let (head, tail) = tmp.split_at_mut(self.chunk_size);
4814             self.v = tail;
4815             Some(head)
4816         }
4817     }
4818 }
4819
4820 #[stable(feature = "rchunks", since = "1.31.0")]
4821 impl<'a, T> ExactSizeIterator for RChunksExactMut<'a, T> {
4822     fn is_empty(&self) -> bool {
4823         self.v.is_empty()
4824     }
4825 }
4826
4827 #[unstable(feature = "trusted_len", issue = "37572")]
4828 unsafe impl<'a, T> TrustedLen for RChunksExactMut<'a, T> {}
4829
4830 #[stable(feature = "rchunks", since = "1.31.0")]
4831 impl<'a, T> FusedIterator for RChunksExactMut<'a, T> {}
4832
4833 #[doc(hidden)]
4834 #[stable(feature = "rchunks", since = "1.31.0")]
4835 unsafe impl<'a, T> TrustedRandomAccess for RChunksExactMut<'a, T> {
4836     unsafe fn get_unchecked(&mut self, i: usize) -> &'a mut [T] {
4837         let end = self.v.len() - i * self.chunk_size;
4838         let start = end - self.chunk_size;
4839         from_raw_parts_mut(self.v.as_mut_ptr().add(start), self.chunk_size)
4840     }
4841     fn may_have_side_effect() -> bool { false }
4842 }
4843
4844 //
4845 // Free functions
4846 //
4847
4848 /// Forms a slice from a pointer and a length.
4849 ///
4850 /// The `len` argument is the number of **elements**, not the number of bytes.
4851 ///
4852 /// # Safety
4853 ///
4854 /// This function is unsafe as there is no guarantee that the given pointer is
4855 /// valid for `len` elements, nor whether the lifetime inferred is a suitable
4856 /// lifetime for the returned slice.
4857 ///
4858 /// `data` must be non-null and aligned, even for zero-length slices. One
4859 /// reason for this is that enum layout optimizations may rely on references
4860 /// (including slices of any length) being aligned and non-null to distinguish
4861 /// them from other data. You can obtain a pointer that is usable as `data`
4862 /// for zero-length slices using [`NonNull::dangling()`].
4863 ///
4864 /// The total size of the slice must be no larger than `isize::MAX` **bytes**
4865 /// in memory. See the safety documentation of [`pointer::offset`].
4866 ///
4867 /// # Caveat
4868 ///
4869 /// The lifetime for the returned slice is inferred from its usage. To
4870 /// prevent accidental misuse, it's suggested to tie the lifetime to whichever
4871 /// source lifetime is safe in the context, such as by providing a helper
4872 /// function taking the lifetime of a host value for the slice, or by explicit
4873 /// annotation.
4874 ///
4875 /// # Examples
4876 ///
4877 /// ```
4878 /// use std::slice;
4879 ///
4880 /// // manifest a slice for a single element
4881 /// let x = 42;
4882 /// let ptr = &x as *const _;
4883 /// let slice = unsafe { slice::from_raw_parts(ptr, 1) };
4884 /// assert_eq!(slice[0], 42);
4885 /// ```
4886 ///
4887 /// [`NonNull::dangling()`]: ../../std/ptr/struct.NonNull.html#method.dangling
4888 /// [`pointer::offset`]: ../../std/primitive.pointer.html#method.offset
4889 #[inline]
4890 #[stable(feature = "rust1", since = "1.0.0")]
4891 pub unsafe fn from_raw_parts<'a, T>(data: *const T, len: usize) -> &'a [T] {
4892     debug_assert!(data as usize % mem::align_of::<T>() == 0, "attempt to create unaligned slice");
4893     debug_assert!(mem::size_of::<T>().saturating_mul(len) <= isize::MAX as usize,
4894                   "attempt to create slice covering half the address space");
4895     Repr { raw: FatPtr { data, len } }.rust
4896 }
4897
4898 /// Performs the same functionality as [`from_raw_parts`], except that a
4899 /// mutable slice is returned.
4900 ///
4901 /// This function is unsafe for the same reasons as [`from_raw_parts`], as well
4902 /// as not being able to provide a non-aliasing guarantee of the returned
4903 /// mutable slice. `data` must be non-null and aligned even for zero-length
4904 /// slices as with [`from_raw_parts`]. The total size of the slice must be no
4905 /// larger than `isize::MAX` **bytes** in memory.
4906 ///
4907 /// See the documentation of [`from_raw_parts`] for more details.
4908 ///
4909 /// [`from_raw_parts`]: ../../std/slice/fn.from_raw_parts.html
4910 #[inline]
4911 #[stable(feature = "rust1", since = "1.0.0")]
4912 pub unsafe fn from_raw_parts_mut<'a, T>(data: *mut T, len: usize) -> &'a mut [T] {
4913     debug_assert!(data as usize % mem::align_of::<T>() == 0, "attempt to create unaligned slice");
4914     debug_assert!(mem::size_of::<T>().saturating_mul(len) <= isize::MAX as usize,
4915                   "attempt to create slice covering half the address space");
4916     Repr { raw: FatPtr { data, len } }.rust_mut
4917 }
4918
4919 /// Converts a reference to T into a slice of length 1 (without copying).
4920 #[stable(feature = "from_ref", since = "1.28.0")]
4921 pub fn from_ref<T>(s: &T) -> &[T] {
4922     unsafe {
4923         from_raw_parts(s, 1)
4924     }
4925 }
4926
4927 /// Converts a reference to T into a slice of length 1 (without copying).
4928 #[stable(feature = "from_ref", since = "1.28.0")]
4929 pub fn from_mut<T>(s: &mut T) -> &mut [T] {
4930     unsafe {
4931         from_raw_parts_mut(s, 1)
4932     }
4933 }
4934
4935 // This function is public only because there is no other way to unit test heapsort.
4936 #[unstable(feature = "sort_internals", reason = "internal to sort module", issue = "0")]
4937 #[doc(hidden)]
4938 pub fn heapsort<T, F>(v: &mut [T], mut is_less: F)
4939     where F: FnMut(&T, &T) -> bool
4940 {
4941     sort::heapsort(v, &mut is_less);
4942 }
4943
4944 //
4945 // Comparison traits
4946 //
4947
4948 extern {
4949     /// Calls implementation provided memcmp.
4950     ///
4951     /// Interprets the data as u8.
4952     ///
4953     /// Returns 0 for equal, < 0 for less than and > 0 for greater
4954     /// than.
4955     // FIXME(#32610): Return type should be c_int
4956     fn memcmp(s1: *const u8, s2: *const u8, n: usize) -> i32;
4957 }
4958
4959 #[stable(feature = "rust1", since = "1.0.0")]
4960 impl<A, B> PartialEq<[B]> for [A] where A: PartialEq<B> {
4961     fn eq(&self, other: &[B]) -> bool {
4962         SlicePartialEq::equal(self, other)
4963     }
4964
4965     fn ne(&self, other: &[B]) -> bool {
4966         SlicePartialEq::not_equal(self, other)
4967     }
4968 }
4969
4970 #[stable(feature = "rust1", since = "1.0.0")]
4971 impl<T: Eq> Eq for [T] {}
4972
4973 /// Implements comparison of vectors lexicographically.
4974 #[stable(feature = "rust1", since = "1.0.0")]
4975 impl<T: Ord> Ord for [T] {
4976     fn cmp(&self, other: &[T]) -> Ordering {
4977         SliceOrd::compare(self, other)
4978     }
4979 }
4980
4981 /// Implements comparison of vectors lexicographically.
4982 #[stable(feature = "rust1", since = "1.0.0")]
4983 impl<T: PartialOrd> PartialOrd for [T] {
4984     fn partial_cmp(&self, other: &[T]) -> Option<Ordering> {
4985         SlicePartialOrd::partial_compare(self, other)
4986     }
4987 }
4988
4989 #[doc(hidden)]
4990 // intermediate trait for specialization of slice's PartialEq
4991 trait SlicePartialEq<B> {
4992     fn equal(&self, other: &[B]) -> bool;
4993
4994     fn not_equal(&self, other: &[B]) -> bool { !self.equal(other) }
4995 }
4996
4997 // Generic slice equality
4998 impl<A, B> SlicePartialEq<B> for [A]
4999     where A: PartialEq<B>
5000 {
5001     default fn equal(&self, other: &[B]) -> bool {
5002         if self.len() != other.len() {
5003             return false;
5004         }
5005
5006         for i in 0..self.len() {
5007             if !self[i].eq(&other[i]) {
5008                 return false;
5009             }
5010         }
5011
5012         true
5013     }
5014 }
5015
5016 // Use memcmp for bytewise equality when the types allow
5017 impl<A> SlicePartialEq<A> for [A]
5018     where A: PartialEq<A> + BytewiseEquality
5019 {
5020     fn equal(&self, other: &[A]) -> bool {
5021         if self.len() != other.len() {
5022             return false;
5023         }
5024         if self.as_ptr() == other.as_ptr() {
5025             return true;
5026         }
5027         unsafe {
5028             let size = mem::size_of_val(self);
5029             memcmp(self.as_ptr() as *const u8,
5030                    other.as_ptr() as *const u8, size) == 0
5031         }
5032     }
5033 }
5034
5035 #[doc(hidden)]
5036 // intermediate trait for specialization of slice's PartialOrd
5037 trait SlicePartialOrd<B> {
5038     fn partial_compare(&self, other: &[B]) -> Option<Ordering>;
5039 }
5040
5041 impl<A> SlicePartialOrd<A> for [A]
5042     where A: PartialOrd
5043 {
5044     default fn partial_compare(&self, other: &[A]) -> Option<Ordering> {
5045         let l = cmp::min(self.len(), other.len());
5046
5047         // Slice to the loop iteration range to enable bound check
5048         // elimination in the compiler
5049         let lhs = &self[..l];
5050         let rhs = &other[..l];
5051
5052         for i in 0..l {
5053             match lhs[i].partial_cmp(&rhs[i]) {
5054                 Some(Ordering::Equal) => (),
5055                 non_eq => return non_eq,
5056             }
5057         }
5058
5059         self.len().partial_cmp(&other.len())
5060     }
5061 }
5062
5063 impl<A> SlicePartialOrd<A> for [A]
5064     where A: Ord
5065 {
5066     default fn partial_compare(&self, other: &[A]) -> Option<Ordering> {
5067         Some(SliceOrd::compare(self, other))
5068     }
5069 }
5070
5071 #[doc(hidden)]
5072 // intermediate trait for specialization of slice's Ord
5073 trait SliceOrd<B> {
5074     fn compare(&self, other: &[B]) -> Ordering;
5075 }
5076
5077 impl<A> SliceOrd<A> for [A]
5078     where A: Ord
5079 {
5080     default fn compare(&self, other: &[A]) -> Ordering {
5081         let l = cmp::min(self.len(), other.len());
5082
5083         // Slice to the loop iteration range to enable bound check
5084         // elimination in the compiler
5085         let lhs = &self[..l];
5086         let rhs = &other[..l];
5087
5088         for i in 0..l {
5089             match lhs[i].cmp(&rhs[i]) {
5090                 Ordering::Equal => (),
5091                 non_eq => return non_eq,
5092             }
5093         }
5094
5095         self.len().cmp(&other.len())
5096     }
5097 }
5098
5099 // memcmp compares a sequence of unsigned bytes lexicographically.
5100 // this matches the order we want for [u8], but no others (not even [i8]).
5101 impl SliceOrd<u8> for [u8] {
5102     #[inline]
5103     fn compare(&self, other: &[u8]) -> Ordering {
5104         let order = unsafe {
5105             memcmp(self.as_ptr(), other.as_ptr(),
5106                    cmp::min(self.len(), other.len()))
5107         };
5108         if order == 0 {
5109             self.len().cmp(&other.len())
5110         } else if order < 0 {
5111             Less
5112         } else {
5113             Greater
5114         }
5115     }
5116 }
5117
5118 #[doc(hidden)]
5119 /// Trait implemented for types that can be compared for equality using
5120 /// their bytewise representation
5121 trait BytewiseEquality { }
5122
5123 macro_rules! impl_marker_for {
5124     ($traitname:ident, $($ty:ty)*) => {
5125         $(
5126             impl $traitname for $ty { }
5127         )*
5128     }
5129 }
5130
5131 impl_marker_for!(BytewiseEquality,
5132                  u8 i8 u16 i16 u32 i32 u64 i64 usize isize char bool);
5133
5134 #[doc(hidden)]
5135 unsafe impl<'a, T> TrustedRandomAccess for Iter<'a, T> {
5136     unsafe fn get_unchecked(&mut self, i: usize) -> &'a T {
5137         &*self.ptr.add(i)
5138     }
5139     fn may_have_side_effect() -> bool { false }
5140 }
5141
5142 #[doc(hidden)]
5143 unsafe impl<'a, T> TrustedRandomAccess for IterMut<'a, T> {
5144     unsafe fn get_unchecked(&mut self, i: usize) -> &'a mut T {
5145         &mut *self.ptr.add(i)
5146     }
5147     fn may_have_side_effect() -> bool { false }
5148 }
5149
5150 trait SliceContains: Sized {
5151     fn slice_contains(&self, x: &[Self]) -> bool;
5152 }
5153
5154 impl<T> SliceContains for T where T: PartialEq {
5155     default fn slice_contains(&self, x: &[Self]) -> bool {
5156         x.iter().any(|y| *y == *self)
5157     }
5158 }
5159
5160 impl SliceContains for u8 {
5161     fn slice_contains(&self, x: &[Self]) -> bool {
5162         memchr::memchr(*self, x).is_some()
5163     }
5164 }
5165
5166 impl SliceContains for i8 {
5167     fn slice_contains(&self, x: &[Self]) -> bool {
5168         let byte = *self as u8;
5169         let bytes: &[u8] = unsafe { from_raw_parts(x.as_ptr() as *const u8, x.len()) };
5170         memchr::memchr(byte, bytes).is_some()
5171     }
5172 }