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