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