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