]> git.lizzy.rs Git - rust.git/blob - src/libcore/slice/mod.rs
76dcca0257817b6f6917345345827a69cf45ba83
[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 [`Result::Ok`] is returned, containing the
1179     /// index of the matching element. If there are multiple matches, then any
1180     /// one of the matches could be returned. If the value is not found then
1181     /// [`Result::Err`] is returned, containing the index where a matching
1182     /// element could be inserted while maintaining sorted order.
1183     ///
1184     /// # Examples
1185     ///
1186     /// Looks up a series of four elements. The first is found, with a
1187     /// uniquely determined position; the second and third are not
1188     /// found; the fourth could match any position in `[1, 4]`.
1189     ///
1190     /// ```
1191     /// let s = [0, 1, 1, 1, 1, 2, 3, 5, 8, 13, 21, 34, 55];
1192     ///
1193     /// assert_eq!(s.binary_search(&13),  Ok(9));
1194     /// assert_eq!(s.binary_search(&4),   Err(7));
1195     /// assert_eq!(s.binary_search(&100), Err(13));
1196     /// let r = s.binary_search(&1);
1197     /// assert!(match r { Ok(1..=4) => true, _ => false, });
1198     /// ```
1199     #[stable(feature = "rust1", since = "1.0.0")]
1200     pub fn binary_search(&self, x: &T) -> Result<usize, usize>
1201         where T: Ord
1202     {
1203         self.binary_search_by(|p| p.cmp(x))
1204     }
1205
1206     /// Binary searches this sorted slice with a comparator function.
1207     ///
1208     /// The comparator function should implement an order consistent
1209     /// with the sort order of the underlying slice, returning an
1210     /// order code that indicates whether its argument is `Less`,
1211     /// `Equal` or `Greater` the desired target.
1212     ///
1213     /// If the value is found then [`Result::Ok`] is returned, containing the
1214     /// index of the matching element. If there are multiple matches, then any
1215     /// one of the matches could be returned. If the value is not found then
1216     /// [`Result::Err`] is returned, containing the index where a matching
1217     /// element could be inserted while maintaining sorted order.
1218     ///
1219     /// # Examples
1220     ///
1221     /// Looks up a series of four elements. The first is found, with a
1222     /// uniquely determined position; the second and third are not
1223     /// found; the fourth could match any position in `[1, 4]`.
1224     ///
1225     /// ```
1226     /// let s = [0, 1, 1, 1, 1, 2, 3, 5, 8, 13, 21, 34, 55];
1227     ///
1228     /// let seek = 13;
1229     /// assert_eq!(s.binary_search_by(|probe| probe.cmp(&seek)), Ok(9));
1230     /// let seek = 4;
1231     /// assert_eq!(s.binary_search_by(|probe| probe.cmp(&seek)), Err(7));
1232     /// let seek = 100;
1233     /// assert_eq!(s.binary_search_by(|probe| probe.cmp(&seek)), Err(13));
1234     /// let seek = 1;
1235     /// let r = s.binary_search_by(|probe| probe.cmp(&seek));
1236     /// assert!(match r { Ok(1..=4) => true, _ => false, });
1237     /// ```
1238     #[stable(feature = "rust1", since = "1.0.0")]
1239     #[inline]
1240     pub fn binary_search_by<'a, F>(&'a self, mut f: F) -> Result<usize, usize>
1241         where F: FnMut(&'a T) -> Ordering
1242     {
1243         let s = self;
1244         let mut size = s.len();
1245         if size == 0 {
1246             return Err(0);
1247         }
1248         let mut base = 0usize;
1249         while size > 1 {
1250             let half = size / 2;
1251             let mid = base + half;
1252             // mid is always in [0, size), that means mid is >= 0 and < size.
1253             // mid >= 0: by definition
1254             // mid < size: mid = size / 2 + size / 4 + size / 8 ...
1255             let cmp = f(unsafe { s.get_unchecked(mid) });
1256             base = if cmp == Greater { base } else { mid };
1257             size -= half;
1258         }
1259         // base is always in [0, size) because base <= mid.
1260         let cmp = f(unsafe { s.get_unchecked(base) });
1261         if cmp == Equal { Ok(base) } else { Err(base + (cmp == Less) as usize) }
1262
1263     }
1264
1265     /// Binary searches this sorted slice with a key extraction function.
1266     ///
1267     /// Assumes that the slice is sorted by the key, for instance with
1268     /// [`sort_by_key`] using the same key extraction function.
1269     ///
1270     /// If the value is found then [`Result::Ok`] is returned, containing the
1271     /// index of the matching element. If there are multiple matches, then any
1272     /// one of the matches could be returned. If the value is not found then
1273     /// [`Result::Err`] is returned, containing the index where a matching
1274     /// element could be inserted while maintaining sorted order.
1275     ///
1276     /// [`sort_by_key`]: #method.sort_by_key
1277     ///
1278     /// # Examples
1279     ///
1280     /// Looks up a series of four elements in a slice of pairs sorted by
1281     /// their second elements. The first is found, with a uniquely
1282     /// determined position; the second and third are not found; the
1283     /// fourth could match any position in `[1, 4]`.
1284     ///
1285     /// ```
1286     /// let s = [(0, 0), (2, 1), (4, 1), (5, 1), (3, 1),
1287     ///          (1, 2), (2, 3), (4, 5), (5, 8), (3, 13),
1288     ///          (1, 21), (2, 34), (4, 55)];
1289     ///
1290     /// assert_eq!(s.binary_search_by_key(&13, |&(a,b)| b),  Ok(9));
1291     /// assert_eq!(s.binary_search_by_key(&4, |&(a,b)| b),   Err(7));
1292     /// assert_eq!(s.binary_search_by_key(&100, |&(a,b)| b), Err(13));
1293     /// let r = s.binary_search_by_key(&1, |&(a,b)| b);
1294     /// assert!(match r { Ok(1..=4) => true, _ => false, });
1295     /// ```
1296     #[stable(feature = "slice_binary_search_by_key", since = "1.10.0")]
1297     #[inline]
1298     pub fn binary_search_by_key<'a, B, F>(&'a self, b: &B, mut f: F) -> Result<usize, usize>
1299         where F: FnMut(&'a T) -> B,
1300               B: Ord
1301     {
1302         self.binary_search_by(|k| f(k).cmp(b))
1303     }
1304
1305     /// Sorts the slice, but may not preserve the order of equal elements.
1306     ///
1307     /// This sort is unstable (i.e. may reorder equal elements), in-place (i.e. does not allocate),
1308     /// and `O(n log n)` worst-case.
1309     ///
1310     /// # Current implementation
1311     ///
1312     /// The current algorithm is based on [pattern-defeating quicksort][pdqsort] by Orson Peters,
1313     /// which combines the fast average case of randomized quicksort with the fast worst case of
1314     /// heapsort, while achieving linear time on slices with certain patterns. It uses some
1315     /// randomization to avoid degenerate cases, but with a fixed seed to always provide
1316     /// deterministic behavior.
1317     ///
1318     /// It is typically faster than stable sorting, except in a few special cases, e.g. when the
1319     /// slice consists of several concatenated sorted sequences.
1320     ///
1321     /// # Examples
1322     ///
1323     /// ```
1324     /// let mut v = [-5, 4, 1, -3, 2];
1325     ///
1326     /// v.sort_unstable();
1327     /// assert!(v == [-5, -3, 1, 2, 4]);
1328     /// ```
1329     ///
1330     /// [pdqsort]: https://github.com/orlp/pdqsort
1331     #[stable(feature = "sort_unstable", since = "1.20.0")]
1332     #[inline]
1333     pub fn sort_unstable(&mut self)
1334         where T: Ord
1335     {
1336         sort::quicksort(self, |a, b| a.lt(b));
1337     }
1338
1339     /// Sorts the slice with a comparator function, but may not preserve the order of equal
1340     /// elements.
1341     ///
1342     /// This sort is unstable (i.e. may reorder equal elements), in-place (i.e. does not allocate),
1343     /// and `O(n log n)` worst-case.
1344     ///
1345     /// # Current implementation
1346     ///
1347     /// The current algorithm is based on [pattern-defeating quicksort][pdqsort] by Orson Peters,
1348     /// which combines the fast average case of randomized quicksort with the fast worst case of
1349     /// heapsort, while achieving linear time on slices with certain patterns. It uses some
1350     /// randomization to avoid degenerate cases, but with a fixed seed to always provide
1351     /// deterministic behavior.
1352     ///
1353     /// It is typically faster than stable sorting, except in a few special cases, e.g. when the
1354     /// slice consists of several concatenated sorted sequences.
1355     ///
1356     /// # Examples
1357     ///
1358     /// ```
1359     /// let mut v = [5, 4, 1, 3, 2];
1360     /// v.sort_unstable_by(|a, b| a.cmp(b));
1361     /// assert!(v == [1, 2, 3, 4, 5]);
1362     ///
1363     /// // reverse sorting
1364     /// v.sort_unstable_by(|a, b| b.cmp(a));
1365     /// assert!(v == [5, 4, 3, 2, 1]);
1366     /// ```
1367     ///
1368     /// [pdqsort]: https://github.com/orlp/pdqsort
1369     #[stable(feature = "sort_unstable", since = "1.20.0")]
1370     #[inline]
1371     pub fn sort_unstable_by<F>(&mut self, mut compare: F)
1372         where F: FnMut(&T, &T) -> Ordering
1373     {
1374         sort::quicksort(self, |a, b| compare(a, b) == Ordering::Less);
1375     }
1376
1377     /// Sorts the slice with a key extraction function, but may not preserve the order of equal
1378     /// elements.
1379     ///
1380     /// This sort is unstable (i.e. may reorder equal elements), in-place (i.e. does not allocate),
1381     /// and `O(m n log(m n))` worst-case, where the key function is `O(m)`.
1382     ///
1383     /// # Current implementation
1384     ///
1385     /// The current algorithm is based on [pattern-defeating quicksort][pdqsort] by Orson Peters,
1386     /// which combines the fast average case of randomized quicksort with the fast worst case of
1387     /// heapsort, while achieving linear time on slices with certain patterns. It uses some
1388     /// randomization to avoid degenerate cases, but with a fixed seed to always provide
1389     /// deterministic behavior.
1390     ///
1391     /// # Examples
1392     ///
1393     /// ```
1394     /// let mut v = [-5i32, 4, 1, -3, 2];
1395     ///
1396     /// v.sort_unstable_by_key(|k| k.abs());
1397     /// assert!(v == [1, 2, -3, 4, -5]);
1398     /// ```
1399     ///
1400     /// [pdqsort]: https://github.com/orlp/pdqsort
1401     #[stable(feature = "sort_unstable", since = "1.20.0")]
1402     #[inline]
1403     pub fn sort_unstable_by_key<K, F>(&mut self, mut f: F)
1404         where F: FnMut(&T) -> K, K: Ord
1405     {
1406         sort::quicksort(self, |a, b| f(a).lt(&f(b)));
1407     }
1408
1409     /// Moves all consecutive repeated elements to the end of the slice according to the
1410     /// [`PartialEq`] trait implementation.
1411     ///
1412     /// Returns two slices. The first contains no consecutive repeated elements.
1413     /// The second contains all the duplicates in no specified order.
1414     ///
1415     /// If the slice is sorted, the first returned slice contains no duplicates.
1416     ///
1417     /// # Examples
1418     ///
1419     /// ```
1420     /// #![feature(slice_partition_dedup)]
1421     ///
1422     /// let mut slice = [1, 2, 2, 3, 3, 2, 1, 1];
1423     ///
1424     /// let (dedup, duplicates) = slice.partition_dedup();
1425     ///
1426     /// assert_eq!(dedup, [1, 2, 3, 2, 1]);
1427     /// assert_eq!(duplicates, [2, 3, 1]);
1428     /// ```
1429     #[unstable(feature = "slice_partition_dedup", issue = "54279")]
1430     #[inline]
1431     pub fn partition_dedup(&mut self) -> (&mut [T], &mut [T])
1432         where T: PartialEq
1433     {
1434         self.partition_dedup_by(|a, b| a == b)
1435     }
1436
1437     /// Moves all but the first of consecutive elements to the end of the slice satisfying
1438     /// a given equality relation.
1439     ///
1440     /// Returns two slices. The first contains no consecutive repeated elements.
1441     /// The second contains all the duplicates in no specified order.
1442     ///
1443     /// The `same_bucket` function is passed references to two elements from the slice and
1444     /// must determine if the elements compare equal. The elements are passed in opposite order
1445     /// from their order in the slice, so if `same_bucket(a, b)` returns `true`, `a` is moved
1446     /// at the end of the slice.
1447     ///
1448     /// If the slice is sorted, the first returned slice contains no duplicates.
1449     ///
1450     /// # Examples
1451     ///
1452     /// ```
1453     /// #![feature(slice_partition_dedup)]
1454     ///
1455     /// let mut slice = ["foo", "Foo", "BAZ", "Bar", "bar", "baz", "BAZ"];
1456     ///
1457     /// let (dedup, duplicates) = slice.partition_dedup_by(|a, b| a.eq_ignore_ascii_case(b));
1458     ///
1459     /// assert_eq!(dedup, ["foo", "BAZ", "Bar", "baz"]);
1460     /// assert_eq!(duplicates, ["bar", "Foo", "BAZ"]);
1461     /// ```
1462     #[unstable(feature = "slice_partition_dedup", issue = "54279")]
1463     #[inline]
1464     pub fn partition_dedup_by<F>(&mut self, mut same_bucket: F) -> (&mut [T], &mut [T])
1465         where F: FnMut(&mut T, &mut T) -> bool
1466     {
1467         // Although we have a mutable reference to `self`, we cannot make
1468         // *arbitrary* changes. The `same_bucket` calls could panic, so we
1469         // must ensure that the slice is in a valid state at all times.
1470         //
1471         // The way that we handle this is by using swaps; we iterate
1472         // over all the elements, swapping as we go so that at the end
1473         // the elements we wish to keep are in the front, and those we
1474         // wish to reject are at the back. We can then split the slice.
1475         // This operation is still O(n).
1476         //
1477         // Example: We start in this state, where `r` represents "next
1478         // read" and `w` represents "next_write`.
1479         //
1480         //           r
1481         //     +---+---+---+---+---+---+
1482         //     | 0 | 1 | 1 | 2 | 3 | 3 |
1483         //     +---+---+---+---+---+---+
1484         //           w
1485         //
1486         // Comparing self[r] against self[w-1], this is not a duplicate, so
1487         // we swap self[r] and self[w] (no effect as r==w) and then increment both
1488         // r and w, leaving us with:
1489         //
1490         //               r
1491         //     +---+---+---+---+---+---+
1492         //     | 0 | 1 | 1 | 2 | 3 | 3 |
1493         //     +---+---+---+---+---+---+
1494         //               w
1495         //
1496         // Comparing self[r] against self[w-1], this value is a duplicate,
1497         // so we increment `r` but leave everything else unchanged:
1498         //
1499         //                   r
1500         //     +---+---+---+---+---+---+
1501         //     | 0 | 1 | 1 | 2 | 3 | 3 |
1502         //     +---+---+---+---+---+---+
1503         //               w
1504         //
1505         // Comparing self[r] against self[w-1], this is not a duplicate,
1506         // so swap self[r] and self[w] and advance r and w:
1507         //
1508         //                       r
1509         //     +---+---+---+---+---+---+
1510         //     | 0 | 1 | 2 | 1 | 3 | 3 |
1511         //     +---+---+---+---+---+---+
1512         //                   w
1513         //
1514         // Not a duplicate, repeat:
1515         //
1516         //                           r
1517         //     +---+---+---+---+---+---+
1518         //     | 0 | 1 | 2 | 3 | 1 | 3 |
1519         //     +---+---+---+---+---+---+
1520         //                       w
1521         //
1522         // Duplicate, advance r. End of slice. Split at w.
1523
1524         let len = self.len();
1525         if len <= 1 {
1526             return (self, &mut [])
1527         }
1528
1529         let ptr = self.as_mut_ptr();
1530         let mut next_read: usize = 1;
1531         let mut next_write: usize = 1;
1532
1533         unsafe {
1534             // Avoid bounds checks by using raw pointers.
1535             while next_read < len {
1536                 let ptr_read = ptr.add(next_read);
1537                 let prev_ptr_write = ptr.add(next_write - 1);
1538                 if !same_bucket(&mut *ptr_read, &mut *prev_ptr_write) {
1539                     if next_read != next_write {
1540                         let ptr_write = prev_ptr_write.offset(1);
1541                         mem::swap(&mut *ptr_read, &mut *ptr_write);
1542                     }
1543                     next_write += 1;
1544                 }
1545                 next_read += 1;
1546             }
1547         }
1548
1549         self.split_at_mut(next_write)
1550     }
1551
1552     /// Moves all but the first of consecutive elements to the end of the slice that resolve
1553     /// to the same key.
1554     ///
1555     /// Returns two slices. The first contains no consecutive repeated elements.
1556     /// The second contains all the duplicates in no specified order.
1557     ///
1558     /// If the slice is sorted, the first returned slice contains no duplicates.
1559     ///
1560     /// # Examples
1561     ///
1562     /// ```
1563     /// #![feature(slice_partition_dedup)]
1564     ///
1565     /// let mut slice = [10, 20, 21, 30, 30, 20, 11, 13];
1566     ///
1567     /// let (dedup, duplicates) = slice.partition_dedup_by_key(|i| *i / 10);
1568     ///
1569     /// assert_eq!(dedup, [10, 20, 30, 20, 11]);
1570     /// assert_eq!(duplicates, [21, 30, 13]);
1571     /// ```
1572     #[unstable(feature = "slice_partition_dedup", issue = "54279")]
1573     #[inline]
1574     pub fn partition_dedup_by_key<K, F>(&mut self, mut key: F) -> (&mut [T], &mut [T])
1575         where F: FnMut(&mut T) -> K,
1576               K: PartialEq,
1577     {
1578         self.partition_dedup_by(|a, b| key(a) == key(b))
1579     }
1580
1581     /// Rotates the slice in-place such that the first `mid` elements of the
1582     /// slice move to the end while the last `self.len() - mid` elements move to
1583     /// the front. After calling `rotate_left`, the element previously at index
1584     /// `mid` will become the first element in the slice.
1585     ///
1586     /// # Panics
1587     ///
1588     /// This function will panic if `mid` is greater than the length of the
1589     /// slice. Note that `mid == self.len()` does _not_ panic and is a no-op
1590     /// rotation.
1591     ///
1592     /// # Complexity
1593     ///
1594     /// Takes linear (in `self.len()`) time.
1595     ///
1596     /// # Examples
1597     ///
1598     /// ```
1599     /// let mut a = ['a', 'b', 'c', 'd', 'e', 'f'];
1600     /// a.rotate_left(2);
1601     /// assert_eq!(a, ['c', 'd', 'e', 'f', 'a', 'b']);
1602     /// ```
1603     ///
1604     /// Rotating a subslice:
1605     ///
1606     /// ```
1607     /// let mut a = ['a', 'b', 'c', 'd', 'e', 'f'];
1608     /// a[1..5].rotate_left(1);
1609     /// assert_eq!(a, ['a', 'c', 'd', 'e', 'b', 'f']);
1610    /// ```
1611     #[stable(feature = "slice_rotate", since = "1.26.0")]
1612     pub fn rotate_left(&mut self, mid: usize) {
1613         assert!(mid <= self.len());
1614         let k = self.len() - mid;
1615
1616         unsafe {
1617             let p = self.as_mut_ptr();
1618             rotate::ptr_rotate(mid, p.add(mid), k);
1619         }
1620     }
1621
1622     /// Rotates the slice in-place such that the first `self.len() - k`
1623     /// elements of the slice move to the end while the last `k` elements move
1624     /// to the front. After calling `rotate_right`, the element previously at
1625     /// index `self.len() - k` will become the first element in the slice.
1626     ///
1627     /// # Panics
1628     ///
1629     /// This function will panic if `k` is greater than the length of the
1630     /// slice. Note that `k == self.len()` does _not_ panic and is a no-op
1631     /// rotation.
1632     ///
1633     /// # Complexity
1634     ///
1635     /// Takes linear (in `self.len()`) time.
1636     ///
1637     /// # Examples
1638     ///
1639     /// ```
1640     /// let mut a = ['a', 'b', 'c', 'd', 'e', 'f'];
1641     /// a.rotate_right(2);
1642     /// assert_eq!(a, ['e', 'f', 'a', 'b', 'c', 'd']);
1643     /// ```
1644     ///
1645     /// Rotate a subslice:
1646     ///
1647     /// ```
1648     /// let mut a = ['a', 'b', 'c', 'd', 'e', 'f'];
1649     /// a[1..5].rotate_right(1);
1650     /// assert_eq!(a, ['a', 'e', 'b', 'c', 'd', 'f']);
1651     /// ```
1652     #[stable(feature = "slice_rotate", since = "1.26.0")]
1653     pub fn rotate_right(&mut self, k: usize) {
1654         assert!(k <= self.len());
1655         let mid = self.len() - k;
1656
1657         unsafe {
1658             let p = self.as_mut_ptr();
1659             rotate::ptr_rotate(mid, p.add(mid), k);
1660         }
1661     }
1662
1663     /// Copies the elements from `src` into `self`.
1664     ///
1665     /// The length of `src` must be the same as `self`.
1666     ///
1667     /// If `src` implements `Copy`, it can be more performant to use
1668     /// [`copy_from_slice`].
1669     ///
1670     /// # Panics
1671     ///
1672     /// This function will panic if the two slices have different lengths.
1673     ///
1674     /// # Examples
1675     ///
1676     /// Cloning two elements from a slice into another:
1677     ///
1678     /// ```
1679     /// let src = [1, 2, 3, 4];
1680     /// let mut dst = [0, 0];
1681     ///
1682     /// // Because the slices have to be the same length,
1683     /// // we slice the source slice from four elements
1684     /// // to two. It will panic if we don't do this.
1685     /// dst.clone_from_slice(&src[2..]);
1686     ///
1687     /// assert_eq!(src, [1, 2, 3, 4]);
1688     /// assert_eq!(dst, [3, 4]);
1689     /// ```
1690     ///
1691     /// Rust enforces that there can only be one mutable reference with no
1692     /// immutable references to a particular piece of data in a particular
1693     /// scope. Because of this, attempting to use `clone_from_slice` on a
1694     /// single slice will result in a compile failure:
1695     ///
1696     /// ```compile_fail
1697     /// let mut slice = [1, 2, 3, 4, 5];
1698     ///
1699     /// slice[..2].clone_from_slice(&slice[3..]); // compile fail!
1700     /// ```
1701     ///
1702     /// To work around this, we can use [`split_at_mut`] to create two distinct
1703     /// sub-slices from a slice:
1704     ///
1705     /// ```
1706     /// let mut slice = [1, 2, 3, 4, 5];
1707     ///
1708     /// {
1709     ///     let (left, right) = slice.split_at_mut(2);
1710     ///     left.clone_from_slice(&right[1..]);
1711     /// }
1712     ///
1713     /// assert_eq!(slice, [4, 5, 3, 4, 5]);
1714     /// ```
1715     ///
1716     /// [`copy_from_slice`]: #method.copy_from_slice
1717     /// [`split_at_mut`]: #method.split_at_mut
1718     #[stable(feature = "clone_from_slice", since = "1.7.0")]
1719     pub fn clone_from_slice(&mut self, src: &[T]) where T: Clone {
1720         assert!(self.len() == src.len(),
1721                 "destination and source slices have different lengths");
1722         // NOTE: We need to explicitly slice them to the same length
1723         // for bounds checking to be elided, and the optimizer will
1724         // generate memcpy for simple cases (for example T = u8).
1725         let len = self.len();
1726         let src = &src[..len];
1727         for i in 0..len {
1728             self[i].clone_from(&src[i]);
1729         }
1730
1731     }
1732
1733     /// Copies all elements from `src` into `self`, using a memcpy.
1734     ///
1735     /// The length of `src` must be the same as `self`.
1736     ///
1737     /// If `src` does not implement `Copy`, use [`clone_from_slice`].
1738     ///
1739     /// # Panics
1740     ///
1741     /// This function will panic if the two slices have different lengths.
1742     ///
1743     /// # Examples
1744     ///
1745     /// Copying two elements from a slice into another:
1746     ///
1747     /// ```
1748     /// let src = [1, 2, 3, 4];
1749     /// let mut dst = [0, 0];
1750     ///
1751     /// // Because the slices have to be the same length,
1752     /// // we slice the source slice from four elements
1753     /// // to two. It will panic if we don't do this.
1754     /// dst.copy_from_slice(&src[2..]);
1755     ///
1756     /// assert_eq!(src, [1, 2, 3, 4]);
1757     /// assert_eq!(dst, [3, 4]);
1758     /// ```
1759     ///
1760     /// Rust enforces that there can only be one mutable reference with no
1761     /// immutable references to a particular piece of data in a particular
1762     /// scope. Because of this, attempting to use `copy_from_slice` on a
1763     /// single slice will result in a compile failure:
1764     ///
1765     /// ```compile_fail
1766     /// let mut slice = [1, 2, 3, 4, 5];
1767     ///
1768     /// slice[..2].copy_from_slice(&slice[3..]); // compile fail!
1769     /// ```
1770     ///
1771     /// To work around this, we can use [`split_at_mut`] to create two distinct
1772     /// sub-slices from a slice:
1773     ///
1774     /// ```
1775     /// let mut slice = [1, 2, 3, 4, 5];
1776     ///
1777     /// {
1778     ///     let (left, right) = slice.split_at_mut(2);
1779     ///     left.copy_from_slice(&right[1..]);
1780     /// }
1781     ///
1782     /// assert_eq!(slice, [4, 5, 3, 4, 5]);
1783     /// ```
1784     ///
1785     /// [`clone_from_slice`]: #method.clone_from_slice
1786     /// [`split_at_mut`]: #method.split_at_mut
1787     #[stable(feature = "copy_from_slice", since = "1.9.0")]
1788     pub fn copy_from_slice(&mut self, src: &[T]) where T: Copy {
1789         assert_eq!(self.len(), src.len(),
1790                    "destination and source slices have different lengths");
1791         unsafe {
1792             ptr::copy_nonoverlapping(
1793                 src.as_ptr(), self.as_mut_ptr(), self.len());
1794         }
1795     }
1796
1797     /// Copies elements from one part of the slice to another part of itself,
1798     /// using a memmove.
1799     ///
1800     /// `src` is the range within `self` to copy from. `dest` is the starting
1801     /// index of the range within `self` to copy to, which will have the same
1802     /// length as `src`. The two ranges may overlap. The ends of the two ranges
1803     /// must be less than or equal to `self.len()`.
1804     ///
1805     /// # Panics
1806     ///
1807     /// This function will panic if either range exceeds the end of the slice,
1808     /// or if the end of `src` is before the start.
1809     ///
1810     /// # Examples
1811     ///
1812     /// Copying four bytes within a slice:
1813     ///
1814     /// ```
1815     /// # #![feature(copy_within)]
1816     /// let mut bytes = *b"Hello, World!";
1817     ///
1818     /// bytes.copy_within(1..5, 8);
1819     ///
1820     /// assert_eq!(&bytes, b"Hello, Wello!");
1821     /// ```
1822     #[unstable(feature = "copy_within", issue = "54236")]
1823     pub fn copy_within<R: ops::RangeBounds<usize>>(&mut self, src: R, dest: usize)
1824     where
1825         T: Copy,
1826     {
1827         let src_start = match src.start_bound() {
1828             ops::Bound::Included(&n) => n,
1829             ops::Bound::Excluded(&n) => n
1830                 .checked_add(1)
1831                 .unwrap_or_else(|| slice_index_overflow_fail()),
1832             ops::Bound::Unbounded => 0,
1833         };
1834         let src_end = match src.end_bound() {
1835             ops::Bound::Included(&n) => n
1836                 .checked_add(1)
1837                 .unwrap_or_else(|| slice_index_overflow_fail()),
1838             ops::Bound::Excluded(&n) => n,
1839             ops::Bound::Unbounded => self.len(),
1840         };
1841         assert!(src_start <= src_end, "src end is before src start");
1842         assert!(src_end <= self.len(), "src is out of bounds");
1843         let count = src_end - src_start;
1844         assert!(dest <= self.len() - count, "dest is out of bounds");
1845         unsafe {
1846             ptr::copy(
1847                 self.get_unchecked(src_start),
1848                 self.get_unchecked_mut(dest),
1849                 count,
1850             );
1851         }
1852     }
1853
1854     /// Swaps all elements in `self` with those in `other`.
1855     ///
1856     /// The length of `other` must be the same as `self`.
1857     ///
1858     /// # Panics
1859     ///
1860     /// This function will panic if the two slices have different lengths.
1861     ///
1862     /// # Example
1863     ///
1864     /// Swapping two elements across slices:
1865     ///
1866     /// ```
1867     /// let mut slice1 = [0, 0];
1868     /// let mut slice2 = [1, 2, 3, 4];
1869     ///
1870     /// slice1.swap_with_slice(&mut slice2[2..]);
1871     ///
1872     /// assert_eq!(slice1, [3, 4]);
1873     /// assert_eq!(slice2, [1, 2, 0, 0]);
1874     /// ```
1875     ///
1876     /// Rust enforces that there can only be one mutable reference to a
1877     /// particular piece of data in a particular scope. Because of this,
1878     /// attempting to use `swap_with_slice` on a single slice will result in
1879     /// a compile failure:
1880     ///
1881     /// ```compile_fail
1882     /// let mut slice = [1, 2, 3, 4, 5];
1883     /// slice[..2].swap_with_slice(&mut slice[3..]); // compile fail!
1884     /// ```
1885     ///
1886     /// To work around this, we can use [`split_at_mut`] to create two distinct
1887     /// mutable sub-slices from a slice:
1888     ///
1889     /// ```
1890     /// let mut slice = [1, 2, 3, 4, 5];
1891     ///
1892     /// {
1893     ///     let (left, right) = slice.split_at_mut(2);
1894     ///     left.swap_with_slice(&mut right[1..]);
1895     /// }
1896     ///
1897     /// assert_eq!(slice, [4, 5, 3, 1, 2]);
1898     /// ```
1899     ///
1900     /// [`split_at_mut`]: #method.split_at_mut
1901     #[stable(feature = "swap_with_slice", since = "1.27.0")]
1902     pub fn swap_with_slice(&mut self, other: &mut [T]) {
1903         assert!(self.len() == other.len(),
1904                 "destination and source slices have different lengths");
1905         unsafe {
1906             ptr::swap_nonoverlapping(
1907                 self.as_mut_ptr(), other.as_mut_ptr(), self.len());
1908         }
1909     }
1910
1911     /// Function to calculate lengths of the middle and trailing slice for `align_to{,_mut}`.
1912     fn align_to_offsets<U>(&self) -> (usize, usize) {
1913         // What we gonna do about `rest` is figure out what multiple of `U`s we can put in a
1914         // lowest number of `T`s. And how many `T`s we need for each such "multiple".
1915         //
1916         // Consider for example T=u8 U=u16. Then we can put 1 U in 2 Ts. Simple. Now, consider
1917         // for example a case where size_of::<T> = 16, size_of::<U> = 24. We can put 2 Us in
1918         // place of every 3 Ts in the `rest` slice. A bit more complicated.
1919         //
1920         // Formula to calculate this is:
1921         //
1922         // Us = lcm(size_of::<T>, size_of::<U>) / size_of::<U>
1923         // Ts = lcm(size_of::<T>, size_of::<U>) / size_of::<T>
1924         //
1925         // Expanded and simplified:
1926         //
1927         // Us = size_of::<T> / gcd(size_of::<T>, size_of::<U>)
1928         // Ts = size_of::<U> / gcd(size_of::<T>, size_of::<U>)
1929         //
1930         // Luckily since all this is constant-evaluated... performance here matters not!
1931         #[inline]
1932         fn gcd(a: usize, b: usize) -> usize {
1933             // iterative stein’s algorithm
1934             // We should still make this `const fn` (and revert to recursive algorithm if we do)
1935             // because relying on llvm to consteval all this is… well, it makes me
1936             let (ctz_a, mut ctz_b) = unsafe {
1937                 if a == 0 { return b; }
1938                 if b == 0 { return a; }
1939                 (::intrinsics::cttz_nonzero(a), ::intrinsics::cttz_nonzero(b))
1940             };
1941             let k = ctz_a.min(ctz_b);
1942             let mut a = a >> ctz_a;
1943             let mut b = b;
1944             loop {
1945                 // remove all factors of 2 from b
1946                 b >>= ctz_b;
1947                 if a > b {
1948                     ::mem::swap(&mut a, &mut b);
1949                 }
1950                 b = b - a;
1951                 unsafe {
1952                     if b == 0 {
1953                         break;
1954                     }
1955                     ctz_b = ::intrinsics::cttz_nonzero(b);
1956                 }
1957             }
1958             a << k
1959         }
1960         let gcd: usize = gcd(::mem::size_of::<T>(), ::mem::size_of::<U>());
1961         let ts: usize = ::mem::size_of::<U>() / gcd;
1962         let us: usize = ::mem::size_of::<T>() / gcd;
1963
1964         // Armed with this knowledge, we can find how many `U`s we can fit!
1965         let us_len = self.len() / ts * us;
1966         // And how many `T`s will be in the trailing slice!
1967         let ts_len = self.len() % ts;
1968         (us_len, ts_len)
1969     }
1970
1971     /// Transmute the slice to a slice of another type, ensuring alignment of the types is
1972     /// maintained.
1973     ///
1974     /// This method splits the slice into three distinct slices: prefix, correctly aligned middle
1975     /// slice of a new type, and the suffix slice. The method does a best effort to make the
1976     /// middle slice the greatest length possible for a given type and input slice, but only
1977     /// your algorithm's performance should depend on that, not its correctness.
1978     ///
1979     /// This method has no purpose when either input element `T` or output element `U` are
1980     /// zero-sized and will return the original slice without splitting anything.
1981     ///
1982     /// # Unsafety
1983     ///
1984     /// This method is essentially a `transmute` with respect to the elements in the returned
1985     /// middle slice, so all the usual caveats pertaining to `transmute::<T, U>` also apply here.
1986     ///
1987     /// # Examples
1988     ///
1989     /// Basic usage:
1990     ///
1991     /// ```
1992     /// unsafe {
1993     ///     let bytes: [u8; 7] = [1, 2, 3, 4, 5, 6, 7];
1994     ///     let (prefix, shorts, suffix) = bytes.align_to::<u16>();
1995     ///     // less_efficient_algorithm_for_bytes(prefix);
1996     ///     // more_efficient_algorithm_for_aligned_shorts(shorts);
1997     ///     // less_efficient_algorithm_for_bytes(suffix);
1998     /// }
1999     /// ```
2000     #[stable(feature = "slice_align_to", since = "1.30.0")]
2001     pub unsafe fn align_to<U>(&self) -> (&[T], &[U], &[T]) {
2002         // Note that most of this function will be constant-evaluated,
2003         if ::mem::size_of::<U>() == 0 || ::mem::size_of::<T>() == 0 {
2004             // handle ZSTs specially, which is â€“ don't handle them at all.
2005             return (self, &[], &[]);
2006         }
2007
2008         // First, find at what point do we split between the first and 2nd slice. Easy with
2009         // ptr.align_offset.
2010         let ptr = self.as_ptr();
2011         let offset = ::ptr::align_offset(ptr, ::mem::align_of::<U>());
2012         if offset > self.len() {
2013             (self, &[], &[])
2014         } else {
2015             let (left, rest) = self.split_at(offset);
2016             // now `rest` is definitely aligned, so `from_raw_parts_mut` below is okay
2017             let (us_len, ts_len) = rest.align_to_offsets::<U>();
2018             (left,
2019              from_raw_parts(rest.as_ptr() as *const U, us_len),
2020              from_raw_parts(rest.as_ptr().add(rest.len() - ts_len), ts_len))
2021         }
2022     }
2023
2024     /// Transmute the slice to a slice of another type, ensuring alignment of the types is
2025     /// maintained.
2026     ///
2027     /// This method splits the slice into three distinct slices: prefix, correctly aligned middle
2028     /// slice of a new type, and the suffix slice. The method does a best effort to make the
2029     /// middle slice the greatest length possible for a given type and input slice, but only
2030     /// your algorithm's performance should depend on that, not its correctness.
2031     ///
2032     /// This method has no purpose when either input element `T` or output element `U` are
2033     /// zero-sized and will return the original slice without splitting anything.
2034     ///
2035     /// # Unsafety
2036     ///
2037     /// This method is essentially a `transmute` with respect to the elements in the returned
2038     /// middle slice, so all the usual caveats pertaining to `transmute::<T, U>` also apply here.
2039     ///
2040     /// # Examples
2041     ///
2042     /// Basic usage:
2043     ///
2044     /// ```
2045     /// unsafe {
2046     ///     let mut bytes: [u8; 7] = [1, 2, 3, 4, 5, 6, 7];
2047     ///     let (prefix, shorts, suffix) = bytes.align_to_mut::<u16>();
2048     ///     // less_efficient_algorithm_for_bytes(prefix);
2049     ///     // more_efficient_algorithm_for_aligned_shorts(shorts);
2050     ///     // less_efficient_algorithm_for_bytes(suffix);
2051     /// }
2052     /// ```
2053     #[stable(feature = "slice_align_to", since = "1.30.0")]
2054     pub unsafe fn align_to_mut<U>(&mut self) -> (&mut [T], &mut [U], &mut [T]) {
2055         // Note that most of this function will be constant-evaluated,
2056         if ::mem::size_of::<U>() == 0 || ::mem::size_of::<T>() == 0 {
2057             // handle ZSTs specially, which is â€“ don't handle them at all.
2058             return (self, &mut [], &mut []);
2059         }
2060
2061         // First, find at what point do we split between the first and 2nd slice. Easy with
2062         // ptr.align_offset.
2063         let ptr = self.as_ptr();
2064         let offset = ::ptr::align_offset(ptr, ::mem::align_of::<U>());
2065         if offset > self.len() {
2066             (self, &mut [], &mut [])
2067         } else {
2068             let (left, rest) = self.split_at_mut(offset);
2069             // now `rest` is definitely aligned, so `from_raw_parts_mut` below is okay
2070             let (us_len, ts_len) = rest.align_to_offsets::<U>();
2071             let mut_ptr = rest.as_mut_ptr();
2072             (left,
2073              from_raw_parts_mut(mut_ptr as *mut U, us_len),
2074              from_raw_parts_mut(mut_ptr.add(rest.len() - ts_len), ts_len))
2075         }
2076     }
2077 }
2078
2079 #[lang = "slice_u8"]
2080 #[cfg(not(test))]
2081 impl [u8] {
2082     /// Checks if all bytes in this slice are within the ASCII range.
2083     #[stable(feature = "ascii_methods_on_intrinsics", since = "1.23.0")]
2084     #[inline]
2085     pub fn is_ascii(&self) -> bool {
2086         self.iter().all(|b| b.is_ascii())
2087     }
2088
2089     /// Checks that two slices are an ASCII case-insensitive match.
2090     ///
2091     /// Same as `to_ascii_lowercase(a) == to_ascii_lowercase(b)`,
2092     /// but without allocating and copying temporaries.
2093     #[stable(feature = "ascii_methods_on_intrinsics", since = "1.23.0")]
2094     #[inline]
2095     pub fn eq_ignore_ascii_case(&self, other: &[u8]) -> bool {
2096         self.len() == other.len() &&
2097             self.iter().zip(other).all(|(a, b)| {
2098                 a.eq_ignore_ascii_case(b)
2099             })
2100     }
2101
2102     /// Converts this slice to its ASCII upper case equivalent in-place.
2103     ///
2104     /// ASCII letters 'a' to 'z' are mapped to 'A' to 'Z',
2105     /// but non-ASCII letters are unchanged.
2106     ///
2107     /// To return a new uppercased value without modifying the existing one, use
2108     /// [`to_ascii_uppercase`].
2109     ///
2110     /// [`to_ascii_uppercase`]: #method.to_ascii_uppercase
2111     #[stable(feature = "ascii_methods_on_intrinsics", since = "1.23.0")]
2112     #[inline]
2113     pub fn make_ascii_uppercase(&mut self) {
2114         for byte in self {
2115             byte.make_ascii_uppercase();
2116         }
2117     }
2118
2119     /// Converts this slice to its ASCII lower case equivalent in-place.
2120     ///
2121     /// ASCII letters 'A' to 'Z' are mapped to 'a' to 'z',
2122     /// but non-ASCII letters are unchanged.
2123     ///
2124     /// To return a new lowercased value without modifying the existing one, use
2125     /// [`to_ascii_lowercase`].
2126     ///
2127     /// [`to_ascii_lowercase`]: #method.to_ascii_lowercase
2128     #[stable(feature = "ascii_methods_on_intrinsics", since = "1.23.0")]
2129     #[inline]
2130     pub fn make_ascii_lowercase(&mut self) {
2131         for byte in self {
2132             byte.make_ascii_lowercase();
2133         }
2134     }
2135
2136 }
2137
2138 #[stable(feature = "rust1", since = "1.0.0")]
2139 #[rustc_on_unimplemented = "slice indices are of type `usize` or ranges of `usize`"]
2140 impl<T, I> ops::Index<I> for [T]
2141     where I: SliceIndex<[T]>
2142 {
2143     type Output = I::Output;
2144
2145     #[inline]
2146     fn index(&self, index: I) -> &I::Output {
2147         index.index(self)
2148     }
2149 }
2150
2151 #[stable(feature = "rust1", since = "1.0.0")]
2152 #[rustc_on_unimplemented = "slice indices are of type `usize` or ranges of `usize`"]
2153 impl<T, I> ops::IndexMut<I> for [T]
2154     where I: SliceIndex<[T]>
2155 {
2156     #[inline]
2157     fn index_mut(&mut self, index: I) -> &mut I::Output {
2158         index.index_mut(self)
2159     }
2160 }
2161
2162 #[inline(never)]
2163 #[cold]
2164 fn slice_index_len_fail(index: usize, len: usize) -> ! {
2165     panic!("index {} out of range for slice of length {}", index, len);
2166 }
2167
2168 #[inline(never)]
2169 #[cold]
2170 fn slice_index_order_fail(index: usize, end: usize) -> ! {
2171     panic!("slice index starts at {} but ends at {}", index, end);
2172 }
2173
2174 #[inline(never)]
2175 #[cold]
2176 fn slice_index_overflow_fail() -> ! {
2177     panic!("attempted to index slice up to maximum usize");
2178 }
2179
2180 mod private_slice_index {
2181     use super::ops;
2182     #[stable(feature = "slice_get_slice", since = "1.28.0")]
2183     pub trait Sealed {}
2184
2185     #[stable(feature = "slice_get_slice", since = "1.28.0")]
2186     impl Sealed for usize {}
2187     #[stable(feature = "slice_get_slice", since = "1.28.0")]
2188     impl Sealed for ops::Range<usize> {}
2189     #[stable(feature = "slice_get_slice", since = "1.28.0")]
2190     impl Sealed for ops::RangeTo<usize> {}
2191     #[stable(feature = "slice_get_slice", since = "1.28.0")]
2192     impl Sealed for ops::RangeFrom<usize> {}
2193     #[stable(feature = "slice_get_slice", since = "1.28.0")]
2194     impl Sealed for ops::RangeFull {}
2195     #[stable(feature = "slice_get_slice", since = "1.28.0")]
2196     impl Sealed for ops::RangeInclusive<usize> {}
2197     #[stable(feature = "slice_get_slice", since = "1.28.0")]
2198     impl Sealed for ops::RangeToInclusive<usize> {}
2199 }
2200
2201 /// A helper trait used for indexing operations.
2202 #[stable(feature = "slice_get_slice", since = "1.28.0")]
2203 #[rustc_on_unimplemented = "slice indices are of type `usize` or ranges of `usize`"]
2204 pub trait SliceIndex<T: ?Sized>: private_slice_index::Sealed {
2205     /// The output type returned by methods.
2206     #[stable(feature = "slice_get_slice", since = "1.28.0")]
2207     type Output: ?Sized;
2208
2209     /// Returns a shared reference to the output at this location, if in
2210     /// bounds.
2211     #[unstable(feature = "slice_index_methods", issue = "0")]
2212     fn get(self, slice: &T) -> Option<&Self::Output>;
2213
2214     /// Returns a mutable reference to the output at this location, if in
2215     /// bounds.
2216     #[unstable(feature = "slice_index_methods", issue = "0")]
2217     fn get_mut(self, slice: &mut T) -> Option<&mut Self::Output>;
2218
2219     /// Returns a shared reference to the output at this location, without
2220     /// performing any bounds checking.
2221     #[unstable(feature = "slice_index_methods", issue = "0")]
2222     unsafe fn get_unchecked(self, slice: &T) -> &Self::Output;
2223
2224     /// Returns a mutable reference to the output at this location, without
2225     /// performing any bounds checking.
2226     #[unstable(feature = "slice_index_methods", issue = "0")]
2227     unsafe fn get_unchecked_mut(self, slice: &mut T) -> &mut Self::Output;
2228
2229     /// Returns a shared reference to the output at this location, panicking
2230     /// if out of bounds.
2231     #[unstable(feature = "slice_index_methods", issue = "0")]
2232     fn index(self, slice: &T) -> &Self::Output;
2233
2234     /// Returns a mutable reference to the output at this location, panicking
2235     /// if out of bounds.
2236     #[unstable(feature = "slice_index_methods", issue = "0")]
2237     fn index_mut(self, slice: &mut T) -> &mut Self::Output;
2238 }
2239
2240 #[stable(feature = "slice_get_slice_impls", since = "1.15.0")]
2241 impl<T> SliceIndex<[T]> for usize {
2242     type Output = T;
2243
2244     #[inline]
2245     fn get(self, slice: &[T]) -> Option<&T> {
2246         if self < slice.len() {
2247             unsafe {
2248                 Some(self.get_unchecked(slice))
2249             }
2250         } else {
2251             None
2252         }
2253     }
2254
2255     #[inline]
2256     fn get_mut(self, slice: &mut [T]) -> Option<&mut T> {
2257         if self < slice.len() {
2258             unsafe {
2259                 Some(self.get_unchecked_mut(slice))
2260             }
2261         } else {
2262             None
2263         }
2264     }
2265
2266     #[inline]
2267     unsafe fn get_unchecked(self, slice: &[T]) -> &T {
2268         &*slice.as_ptr().add(self)
2269     }
2270
2271     #[inline]
2272     unsafe fn get_unchecked_mut(self, slice: &mut [T]) -> &mut T {
2273         &mut *slice.as_mut_ptr().add(self)
2274     }
2275
2276     #[inline]
2277     fn index(self, slice: &[T]) -> &T {
2278         // NB: use intrinsic indexing
2279         &(*slice)[self]
2280     }
2281
2282     #[inline]
2283     fn index_mut(self, slice: &mut [T]) -> &mut T {
2284         // NB: use intrinsic indexing
2285         &mut (*slice)[self]
2286     }
2287 }
2288
2289 #[stable(feature = "slice_get_slice_impls", since = "1.15.0")]
2290 impl<T> SliceIndex<[T]> for  ops::Range<usize> {
2291     type Output = [T];
2292
2293     #[inline]
2294     fn get(self, slice: &[T]) -> Option<&[T]> {
2295         if self.start > self.end || self.end > slice.len() {
2296             None
2297         } else {
2298             unsafe {
2299                 Some(self.get_unchecked(slice))
2300             }
2301         }
2302     }
2303
2304     #[inline]
2305     fn get_mut(self, slice: &mut [T]) -> Option<&mut [T]> {
2306         if self.start > self.end || self.end > slice.len() {
2307             None
2308         } else {
2309             unsafe {
2310                 Some(self.get_unchecked_mut(slice))
2311             }
2312         }
2313     }
2314
2315     #[inline]
2316     unsafe fn get_unchecked(self, slice: &[T]) -> &[T] {
2317         from_raw_parts(slice.as_ptr().add(self.start), self.end - self.start)
2318     }
2319
2320     #[inline]
2321     unsafe fn get_unchecked_mut(self, slice: &mut [T]) -> &mut [T] {
2322         from_raw_parts_mut(slice.as_mut_ptr().add(self.start), self.end - self.start)
2323     }
2324
2325     #[inline]
2326     fn index(self, slice: &[T]) -> &[T] {
2327         if self.start > self.end {
2328             slice_index_order_fail(self.start, self.end);
2329         } else if self.end > slice.len() {
2330             slice_index_len_fail(self.end, slice.len());
2331         }
2332         unsafe {
2333             self.get_unchecked(slice)
2334         }
2335     }
2336
2337     #[inline]
2338     fn index_mut(self, slice: &mut [T]) -> &mut [T] {
2339         if self.start > self.end {
2340             slice_index_order_fail(self.start, self.end);
2341         } else if self.end > slice.len() {
2342             slice_index_len_fail(self.end, slice.len());
2343         }
2344         unsafe {
2345             self.get_unchecked_mut(slice)
2346         }
2347     }
2348 }
2349
2350 #[stable(feature = "slice_get_slice_impls", since = "1.15.0")]
2351 impl<T> SliceIndex<[T]> for ops::RangeTo<usize> {
2352     type Output = [T];
2353
2354     #[inline]
2355     fn get(self, slice: &[T]) -> Option<&[T]> {
2356         (0..self.end).get(slice)
2357     }
2358
2359     #[inline]
2360     fn get_mut(self, slice: &mut [T]) -> Option<&mut [T]> {
2361         (0..self.end).get_mut(slice)
2362     }
2363
2364     #[inline]
2365     unsafe fn get_unchecked(self, slice: &[T]) -> &[T] {
2366         (0..self.end).get_unchecked(slice)
2367     }
2368
2369     #[inline]
2370     unsafe fn get_unchecked_mut(self, slice: &mut [T]) -> &mut [T] {
2371         (0..self.end).get_unchecked_mut(slice)
2372     }
2373
2374     #[inline]
2375     fn index(self, slice: &[T]) -> &[T] {
2376         (0..self.end).index(slice)
2377     }
2378
2379     #[inline]
2380     fn index_mut(self, slice: &mut [T]) -> &mut [T] {
2381         (0..self.end).index_mut(slice)
2382     }
2383 }
2384
2385 #[stable(feature = "slice_get_slice_impls", since = "1.15.0")]
2386 impl<T> SliceIndex<[T]> for ops::RangeFrom<usize> {
2387     type Output = [T];
2388
2389     #[inline]
2390     fn get(self, slice: &[T]) -> Option<&[T]> {
2391         (self.start..slice.len()).get(slice)
2392     }
2393
2394     #[inline]
2395     fn get_mut(self, slice: &mut [T]) -> Option<&mut [T]> {
2396         (self.start..slice.len()).get_mut(slice)
2397     }
2398
2399     #[inline]
2400     unsafe fn get_unchecked(self, slice: &[T]) -> &[T] {
2401         (self.start..slice.len()).get_unchecked(slice)
2402     }
2403
2404     #[inline]
2405     unsafe fn get_unchecked_mut(self, slice: &mut [T]) -> &mut [T] {
2406         (self.start..slice.len()).get_unchecked_mut(slice)
2407     }
2408
2409     #[inline]
2410     fn index(self, slice: &[T]) -> &[T] {
2411         (self.start..slice.len()).index(slice)
2412     }
2413
2414     #[inline]
2415     fn index_mut(self, slice: &mut [T]) -> &mut [T] {
2416         (self.start..slice.len()).index_mut(slice)
2417     }
2418 }
2419
2420 #[stable(feature = "slice_get_slice_impls", since = "1.15.0")]
2421 impl<T> SliceIndex<[T]> for ops::RangeFull {
2422     type Output = [T];
2423
2424     #[inline]
2425     fn get(self, slice: &[T]) -> Option<&[T]> {
2426         Some(slice)
2427     }
2428
2429     #[inline]
2430     fn get_mut(self, slice: &mut [T]) -> Option<&mut [T]> {
2431         Some(slice)
2432     }
2433
2434     #[inline]
2435     unsafe fn get_unchecked(self, slice: &[T]) -> &[T] {
2436         slice
2437     }
2438
2439     #[inline]
2440     unsafe fn get_unchecked_mut(self, slice: &mut [T]) -> &mut [T] {
2441         slice
2442     }
2443
2444     #[inline]
2445     fn index(self, slice: &[T]) -> &[T] {
2446         slice
2447     }
2448
2449     #[inline]
2450     fn index_mut(self, slice: &mut [T]) -> &mut [T] {
2451         slice
2452     }
2453 }
2454
2455
2456 #[stable(feature = "inclusive_range", since = "1.26.0")]
2457 impl<T> SliceIndex<[T]> for ops::RangeInclusive<usize> {
2458     type Output = [T];
2459
2460     #[inline]
2461     fn get(self, slice: &[T]) -> Option<&[T]> {
2462         if *self.end() == usize::max_value() { None }
2463         else { (*self.start()..self.end() + 1).get(slice) }
2464     }
2465
2466     #[inline]
2467     fn get_mut(self, slice: &mut [T]) -> Option<&mut [T]> {
2468         if *self.end() == usize::max_value() { None }
2469         else { (*self.start()..self.end() + 1).get_mut(slice) }
2470     }
2471
2472     #[inline]
2473     unsafe fn get_unchecked(self, slice: &[T]) -> &[T] {
2474         (*self.start()..self.end() + 1).get_unchecked(slice)
2475     }
2476
2477     #[inline]
2478     unsafe fn get_unchecked_mut(self, slice: &mut [T]) -> &mut [T] {
2479         (*self.start()..self.end() + 1).get_unchecked_mut(slice)
2480     }
2481
2482     #[inline]
2483     fn index(self, slice: &[T]) -> &[T] {
2484         if *self.end() == usize::max_value() { slice_index_overflow_fail(); }
2485         (*self.start()..self.end() + 1).index(slice)
2486     }
2487
2488     #[inline]
2489     fn index_mut(self, slice: &mut [T]) -> &mut [T] {
2490         if *self.end() == usize::max_value() { slice_index_overflow_fail(); }
2491         (*self.start()..self.end() + 1).index_mut(slice)
2492     }
2493 }
2494
2495 #[stable(feature = "inclusive_range", since = "1.26.0")]
2496 impl<T> SliceIndex<[T]> for ops::RangeToInclusive<usize> {
2497     type Output = [T];
2498
2499     #[inline]
2500     fn get(self, slice: &[T]) -> Option<&[T]> {
2501         (0..=self.end).get(slice)
2502     }
2503
2504     #[inline]
2505     fn get_mut(self, slice: &mut [T]) -> Option<&mut [T]> {
2506         (0..=self.end).get_mut(slice)
2507     }
2508
2509     #[inline]
2510     unsafe fn get_unchecked(self, slice: &[T]) -> &[T] {
2511         (0..=self.end).get_unchecked(slice)
2512     }
2513
2514     #[inline]
2515     unsafe fn get_unchecked_mut(self, slice: &mut [T]) -> &mut [T] {
2516         (0..=self.end).get_unchecked_mut(slice)
2517     }
2518
2519     #[inline]
2520     fn index(self, slice: &[T]) -> &[T] {
2521         (0..=self.end).index(slice)
2522     }
2523
2524     #[inline]
2525     fn index_mut(self, slice: &mut [T]) -> &mut [T] {
2526         (0..=self.end).index_mut(slice)
2527     }
2528 }
2529
2530 ////////////////////////////////////////////////////////////////////////////////
2531 // Common traits
2532 ////////////////////////////////////////////////////////////////////////////////
2533
2534 #[stable(feature = "rust1", since = "1.0.0")]
2535 impl<T> Default for &[T] {
2536     /// Creates an empty slice.
2537     fn default() -> Self { &[] }
2538 }
2539
2540 #[stable(feature = "mut_slice_default", since = "1.5.0")]
2541 impl<T> Default for &mut [T] {
2542     /// Creates a mutable empty slice.
2543     fn default() -> Self { &mut [] }
2544 }
2545
2546 //
2547 // Iterators
2548 //
2549
2550 #[stable(feature = "rust1", since = "1.0.0")]
2551 impl<'a, T> IntoIterator for &'a [T] {
2552     type Item = &'a T;
2553     type IntoIter = Iter<'a, T>;
2554
2555     fn into_iter(self) -> Iter<'a, T> {
2556         self.iter()
2557     }
2558 }
2559
2560 #[stable(feature = "rust1", since = "1.0.0")]
2561 impl<'a, T> IntoIterator for &'a mut [T] {
2562     type Item = &'a mut T;
2563     type IntoIter = IterMut<'a, T>;
2564
2565     fn into_iter(self) -> IterMut<'a, T> {
2566         self.iter_mut()
2567     }
2568 }
2569
2570 // Macro helper functions
2571 #[inline(always)]
2572 fn size_from_ptr<T>(_: *const T) -> usize {
2573     mem::size_of::<T>()
2574 }
2575
2576 // Inlining is_empty and len makes a huge performance difference
2577 macro_rules! is_empty {
2578     // The way we encode the length of a ZST iterator, this works both for ZST
2579     // and non-ZST.
2580     ($self: ident) => {$self.ptr == $self.end}
2581 }
2582 // To get rid of some bounds checks (see `position`), we compute the length in a somewhat
2583 // unexpected way. (Tested by `codegen/slice-position-bounds-check`.)
2584 macro_rules! len {
2585     ($self: ident) => {{
2586         let start = $self.ptr;
2587         let diff = ($self.end as usize).wrapping_sub(start as usize);
2588         let size = size_from_ptr(start);
2589         if size == 0 {
2590             diff
2591         } else {
2592             // Using division instead of `offset_from` helps LLVM remove bounds checks
2593             diff / size
2594         }
2595     }}
2596 }
2597
2598 // The shared definition of the `Iter` and `IterMut` iterators
2599 macro_rules! iterator {
2600     (struct $name:ident -> $ptr:ty, $elem:ty, $raw_mut:tt, $( $mut_:tt )*) => {
2601         impl<'a, T> $name<'a, T> {
2602             // Helper function for creating a slice from the iterator.
2603             #[inline(always)]
2604             fn make_slice(&self) -> &'a [T] {
2605                 unsafe { from_raw_parts(self.ptr, len!(self)) }
2606             }
2607
2608             // Helper function for moving the start of the iterator forwards by `offset` elements,
2609             // returning the old start.
2610             // Unsafe because the offset must be in-bounds or one-past-the-end.
2611             #[inline(always)]
2612             unsafe fn post_inc_start(&mut self, offset: isize) -> * $raw_mut T {
2613                 if mem::size_of::<T>() == 0 {
2614                     // This is *reducing* the length.  `ptr` never changes with ZST.
2615                     self.end = (self.end as * $raw_mut u8).wrapping_offset(-offset) as * $raw_mut T;
2616                     self.ptr
2617                 } else {
2618                     let old = self.ptr;
2619                     self.ptr = self.ptr.offset(offset);
2620                     old
2621                 }
2622             }
2623
2624             // Helper function for moving the end of the iterator backwards by `offset` elements,
2625             // returning the new end.
2626             // Unsafe because the offset must be in-bounds or one-past-the-end.
2627             #[inline(always)]
2628             unsafe fn pre_dec_end(&mut self, offset: isize) -> * $raw_mut T {
2629                 if mem::size_of::<T>() == 0 {
2630                     self.end = (self.end as * $raw_mut u8).wrapping_offset(-offset) as * $raw_mut T;
2631                     self.ptr
2632                 } else {
2633                     self.end = self.end.offset(-offset);
2634                     self.end
2635                 }
2636             }
2637         }
2638
2639         #[stable(feature = "rust1", since = "1.0.0")]
2640         impl<'a, T> ExactSizeIterator for $name<'a, T> {
2641             #[inline(always)]
2642             fn len(&self) -> usize {
2643                 len!(self)
2644             }
2645
2646             #[inline(always)]
2647             fn is_empty(&self) -> bool {
2648                 is_empty!(self)
2649             }
2650         }
2651
2652         #[stable(feature = "rust1", since = "1.0.0")]
2653         impl<'a, T> Iterator for $name<'a, T> {
2654             type Item = $elem;
2655
2656             #[inline]
2657             fn next(&mut self) -> Option<$elem> {
2658                 // could be implemented with slices, but this avoids bounds checks
2659                 unsafe {
2660                     assume(!self.ptr.is_null());
2661                     if mem::size_of::<T>() != 0 {
2662                         assume(!self.end.is_null());
2663                     }
2664                     if is_empty!(self) {
2665                         None
2666                     } else {
2667                         Some(& $( $mut_ )* *self.post_inc_start(1))
2668                     }
2669                 }
2670             }
2671
2672             #[inline]
2673             fn size_hint(&self) -> (usize, Option<usize>) {
2674                 let exact = len!(self);
2675                 (exact, Some(exact))
2676             }
2677
2678             #[inline]
2679             fn count(self) -> usize {
2680                 len!(self)
2681             }
2682
2683             #[inline]
2684             fn nth(&mut self, n: usize) -> Option<$elem> {
2685                 if n >= len!(self) {
2686                     // This iterator is now empty.
2687                     if mem::size_of::<T>() == 0 {
2688                         // We have to do it this way as `ptr` may never be 0, but `end`
2689                         // could be (due to wrapping).
2690                         self.end = self.ptr;
2691                     } else {
2692                         self.ptr = self.end;
2693                     }
2694                     return None;
2695                 }
2696                 // We are in bounds. `offset` does the right thing even for ZSTs.
2697                 unsafe {
2698                     let elem = Some(& $( $mut_ )* *self.ptr.add(n));
2699                     self.post_inc_start((n as isize).wrapping_add(1));
2700                     elem
2701                 }
2702             }
2703
2704             #[inline]
2705             fn last(mut self) -> Option<$elem> {
2706                 self.next_back()
2707             }
2708
2709             #[inline]
2710             fn try_fold<B, F, R>(&mut self, init: B, mut f: F) -> R where
2711                 Self: Sized, F: FnMut(B, Self::Item) -> R, R: Try<Ok=B>
2712             {
2713                 // manual unrolling is needed when there are conditional exits from the loop
2714                 let mut accum = init;
2715                 unsafe {
2716                     while len!(self) >= 4 {
2717                         accum = f(accum, & $( $mut_ )* *self.post_inc_start(1))?;
2718                         accum = f(accum, & $( $mut_ )* *self.post_inc_start(1))?;
2719                         accum = f(accum, & $( $mut_ )* *self.post_inc_start(1))?;
2720                         accum = f(accum, & $( $mut_ )* *self.post_inc_start(1))?;
2721                     }
2722                     while !is_empty!(self) {
2723                         accum = f(accum, & $( $mut_ )* *self.post_inc_start(1))?;
2724                     }
2725                 }
2726                 Try::from_ok(accum)
2727             }
2728
2729             #[inline]
2730             fn fold<Acc, Fold>(mut self, init: Acc, mut f: Fold) -> Acc
2731                 where Fold: FnMut(Acc, Self::Item) -> Acc,
2732             {
2733                 // Let LLVM unroll this, rather than using the default
2734                 // impl that would force the manual unrolling above
2735                 let mut accum = init;
2736                 while let Some(x) = self.next() {
2737                     accum = f(accum, x);
2738                 }
2739                 accum
2740             }
2741
2742             #[inline]
2743             #[rustc_inherit_overflow_checks]
2744             fn position<P>(&mut self, mut predicate: P) -> Option<usize> where
2745                 Self: Sized,
2746                 P: FnMut(Self::Item) -> bool,
2747             {
2748                 // The addition might panic on overflow.
2749                 let n = len!(self);
2750                 self.try_fold(0, move |i, x| {
2751                     if predicate(x) { Err(i) }
2752                     else { Ok(i + 1) }
2753                 }).err()
2754                     .map(|i| {
2755                         unsafe { assume(i < n) };
2756                         i
2757                     })
2758             }
2759
2760             #[inline]
2761             fn rposition<P>(&mut self, mut predicate: P) -> Option<usize> where
2762                 P: FnMut(Self::Item) -> bool,
2763                 Self: Sized + ExactSizeIterator + DoubleEndedIterator
2764             {
2765                 // No need for an overflow check here, because `ExactSizeIterator`
2766                 let n = len!(self);
2767                 self.try_rfold(n, move |i, x| {
2768                     let i = i - 1;
2769                     if predicate(x) { Err(i) }
2770                     else { Ok(i) }
2771                 }).err()
2772                     .map(|i| {
2773                         unsafe { assume(i < n) };
2774                         i
2775                     })
2776             }
2777         }
2778
2779         #[stable(feature = "rust1", since = "1.0.0")]
2780         impl<'a, T> DoubleEndedIterator for $name<'a, T> {
2781             #[inline]
2782             fn next_back(&mut self) -> Option<$elem> {
2783                 // could be implemented with slices, but this avoids bounds checks
2784                 unsafe {
2785                     assume(!self.ptr.is_null());
2786                     if mem::size_of::<T>() != 0 {
2787                         assume(!self.end.is_null());
2788                     }
2789                     if is_empty!(self) {
2790                         None
2791                     } else {
2792                         Some(& $( $mut_ )* *self.pre_dec_end(1))
2793                     }
2794                 }
2795             }
2796
2797             #[inline]
2798             fn try_rfold<B, F, R>(&mut self, init: B, mut f: F) -> R where
2799                 Self: Sized, F: FnMut(B, Self::Item) -> R, R: Try<Ok=B>
2800             {
2801                 // manual unrolling is needed when there are conditional exits from the loop
2802                 let mut accum = init;
2803                 unsafe {
2804                     while len!(self) >= 4 {
2805                         accum = f(accum, & $( $mut_ )* *self.pre_dec_end(1))?;
2806                         accum = f(accum, & $( $mut_ )* *self.pre_dec_end(1))?;
2807                         accum = f(accum, & $( $mut_ )* *self.pre_dec_end(1))?;
2808                         accum = f(accum, & $( $mut_ )* *self.pre_dec_end(1))?;
2809                     }
2810                     // inlining is_empty everywhere makes a huge performance difference
2811                     while !is_empty!(self) {
2812                         accum = f(accum, & $( $mut_ )* *self.pre_dec_end(1))?;
2813                     }
2814                 }
2815                 Try::from_ok(accum)
2816             }
2817
2818             #[inline]
2819             fn rfold<Acc, Fold>(mut self, init: Acc, mut f: Fold) -> Acc
2820                 where Fold: FnMut(Acc, Self::Item) -> Acc,
2821             {
2822                 // Let LLVM unroll this, rather than using the default
2823                 // impl that would force the manual unrolling above
2824                 let mut accum = init;
2825                 while let Some(x) = self.next_back() {
2826                     accum = f(accum, x);
2827                 }
2828                 accum
2829             }
2830         }
2831
2832         #[stable(feature = "fused", since = "1.26.0")]
2833         impl<'a, T> FusedIterator for $name<'a, T> {}
2834
2835         #[unstable(feature = "trusted_len", issue = "37572")]
2836         unsafe impl<'a, T> TrustedLen for $name<'a, T> {}
2837     }
2838 }
2839
2840 /// Immutable slice iterator
2841 ///
2842 /// This struct is created by the [`iter`] method on [slices].
2843 ///
2844 /// # Examples
2845 ///
2846 /// Basic usage:
2847 ///
2848 /// ```
2849 /// // First, we declare a type which has `iter` method to get the `Iter` struct (&[usize here]):
2850 /// let slice = &[1, 2, 3];
2851 ///
2852 /// // Then, we iterate over it:
2853 /// for element in slice.iter() {
2854 ///     println!("{}", element);
2855 /// }
2856 /// ```
2857 ///
2858 /// [`iter`]: ../../std/primitive.slice.html#method.iter
2859 /// [slices]: ../../std/primitive.slice.html
2860 #[stable(feature = "rust1", since = "1.0.0")]
2861 pub struct Iter<'a, T: 'a> {
2862     ptr: *const T,
2863     end: *const T, // If T is a ZST, this is actually ptr+len.  This encoding is picked so that
2864                    // ptr == end is a quick test for the Iterator being empty, that works
2865                    // for both ZST and non-ZST.
2866     _marker: marker::PhantomData<&'a T>,
2867 }
2868
2869 #[stable(feature = "core_impl_debug", since = "1.9.0")]
2870 impl<T: fmt::Debug> fmt::Debug for Iter<'_, T> {
2871     fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
2872         f.debug_tuple("Iter")
2873             .field(&self.as_slice())
2874             .finish()
2875     }
2876 }
2877
2878 #[stable(feature = "rust1", since = "1.0.0")]
2879 unsafe impl<T: Sync> Sync for Iter<'_, T> {}
2880 #[stable(feature = "rust1", since = "1.0.0")]
2881 unsafe impl<T: Sync> Send for Iter<'_, T> {}
2882
2883 impl<'a, T> Iter<'a, T> {
2884     /// View the underlying data as a subslice of the original data.
2885     ///
2886     /// This has the same lifetime as the original slice, and so the
2887     /// iterator can continue to be used while this exists.
2888     ///
2889     /// # Examples
2890     ///
2891     /// Basic usage:
2892     ///
2893     /// ```
2894     /// // First, we declare a type which has the `iter` method to get the `Iter`
2895     /// // struct (&[usize here]):
2896     /// let slice = &[1, 2, 3];
2897     ///
2898     /// // Then, we get the iterator:
2899     /// let mut iter = slice.iter();
2900     /// // So if we print what `as_slice` method returns here, we have "[1, 2, 3]":
2901     /// println!("{:?}", iter.as_slice());
2902     ///
2903     /// // Next, we move to the second element of the slice:
2904     /// iter.next();
2905     /// // Now `as_slice` returns "[2, 3]":
2906     /// println!("{:?}", iter.as_slice());
2907     /// ```
2908     #[stable(feature = "iter_to_slice", since = "1.4.0")]
2909     pub fn as_slice(&self) -> &'a [T] {
2910         self.make_slice()
2911     }
2912 }
2913
2914 iterator!{struct Iter -> *const T, &'a T, const, /* no mut */}
2915
2916 #[stable(feature = "rust1", since = "1.0.0")]
2917 impl<T> Clone for Iter<'_, T> {
2918     fn clone(&self) -> Self { Iter { ptr: self.ptr, end: self.end, _marker: self._marker } }
2919 }
2920
2921 #[stable(feature = "slice_iter_as_ref", since = "1.13.0")]
2922 impl<T> AsRef<[T]> for Iter<'_, T> {
2923     fn as_ref(&self) -> &[T] {
2924         self.as_slice()
2925     }
2926 }
2927
2928 /// Mutable slice iterator.
2929 ///
2930 /// This struct is created by the [`iter_mut`] method on [slices].
2931 ///
2932 /// # Examples
2933 ///
2934 /// Basic usage:
2935 ///
2936 /// ```
2937 /// // First, we declare a type which has `iter_mut` method to get the `IterMut`
2938 /// // struct (&[usize here]):
2939 /// let mut slice = &mut [1, 2, 3];
2940 ///
2941 /// // Then, we iterate over it and increment each element value:
2942 /// for element in slice.iter_mut() {
2943 ///     *element += 1;
2944 /// }
2945 ///
2946 /// // We now have "[2, 3, 4]":
2947 /// println!("{:?}", slice);
2948 /// ```
2949 ///
2950 /// [`iter_mut`]: ../../std/primitive.slice.html#method.iter_mut
2951 /// [slices]: ../../std/primitive.slice.html
2952 #[stable(feature = "rust1", since = "1.0.0")]
2953 pub struct IterMut<'a, T: 'a> {
2954     ptr: *mut T,
2955     end: *mut T, // If T is a ZST, this is actually ptr+len.  This encoding is picked so that
2956                  // ptr == end is a quick test for the Iterator being empty, that works
2957                  // for both ZST and non-ZST.
2958     _marker: marker::PhantomData<&'a mut T>,
2959 }
2960
2961 #[stable(feature = "core_impl_debug", since = "1.9.0")]
2962 impl<T: fmt::Debug> fmt::Debug for IterMut<'_, T> {
2963     fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
2964         f.debug_tuple("IterMut")
2965             .field(&self.make_slice())
2966             .finish()
2967     }
2968 }
2969
2970 #[stable(feature = "rust1", since = "1.0.0")]
2971 unsafe impl<T: Sync> Sync for IterMut<'_, T> {}
2972 #[stable(feature = "rust1", since = "1.0.0")]
2973 unsafe impl<T: Send> Send for IterMut<'_, T> {}
2974
2975 impl<'a, T> IterMut<'a, T> {
2976     /// View the underlying data as a subslice of the original data.
2977     ///
2978     /// To avoid creating `&mut` references that alias, this is forced
2979     /// to consume the iterator.
2980     ///
2981     /// # Examples
2982     ///
2983     /// Basic usage:
2984     ///
2985     /// ```
2986     /// // First, we declare a type which has `iter_mut` method to get the `IterMut`
2987     /// // struct (&[usize here]):
2988     /// let mut slice = &mut [1, 2, 3];
2989     ///
2990     /// {
2991     ///     // Then, we get the iterator:
2992     ///     let mut iter = slice.iter_mut();
2993     ///     // We move to next element:
2994     ///     iter.next();
2995     ///     // So if we print what `into_slice` method returns here, we have "[2, 3]":
2996     ///     println!("{:?}", iter.into_slice());
2997     /// }
2998     ///
2999     /// // Now let's modify a value of the slice:
3000     /// {
3001     ///     // First we get back the iterator:
3002     ///     let mut iter = slice.iter_mut();
3003     ///     // We change the value of the first element of the slice returned by the `next` method:
3004     ///     *iter.next().unwrap() += 1;
3005     /// }
3006     /// // Now slice is "[2, 2, 3]":
3007     /// println!("{:?}", slice);
3008     /// ```
3009     #[stable(feature = "iter_to_slice", since = "1.4.0")]
3010     pub fn into_slice(self) -> &'a mut [T] {
3011         unsafe { from_raw_parts_mut(self.ptr, len!(self)) }
3012     }
3013 }
3014
3015 iterator!{struct IterMut -> *mut T, &'a mut T, mut, mut}
3016
3017 /// An internal abstraction over the splitting iterators, so that
3018 /// splitn, splitn_mut etc can be implemented once.
3019 #[doc(hidden)]
3020 trait SplitIter: DoubleEndedIterator {
3021     /// Marks the underlying iterator as complete, extracting the remaining
3022     /// portion of the slice.
3023     fn finish(&mut self) -> Option<Self::Item>;
3024 }
3025
3026 /// An iterator over subslices separated by elements that match a predicate
3027 /// function.
3028 ///
3029 /// This struct is created by the [`split`] method on [slices].
3030 ///
3031 /// [`split`]: ../../std/primitive.slice.html#method.split
3032 /// [slices]: ../../std/primitive.slice.html
3033 #[stable(feature = "rust1", since = "1.0.0")]
3034 pub struct Split<'a, T:'a, P> where P: FnMut(&T) -> bool {
3035     v: &'a [T],
3036     pred: P,
3037     finished: bool
3038 }
3039
3040 #[stable(feature = "core_impl_debug", since = "1.9.0")]
3041 impl<T: fmt::Debug, P> fmt::Debug for Split<'_, T, P> where P: FnMut(&T) -> bool {
3042     fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
3043         f.debug_struct("Split")
3044             .field("v", &self.v)
3045             .field("finished", &self.finished)
3046             .finish()
3047     }
3048 }
3049
3050 // FIXME(#26925) Remove in favor of `#[derive(Clone)]`
3051 #[stable(feature = "rust1", since = "1.0.0")]
3052 impl<T, P> Clone for Split<'_, T, P> where P: Clone + FnMut(&T) -> bool {
3053     fn clone(&self) -> Self {
3054         Split {
3055             v: self.v,
3056             pred: self.pred.clone(),
3057             finished: self.finished,
3058         }
3059     }
3060 }
3061
3062 #[stable(feature = "rust1", since = "1.0.0")]
3063 impl<'a, T, P> Iterator for Split<'a, T, P> where P: FnMut(&T) -> bool {
3064     type Item = &'a [T];
3065
3066     #[inline]
3067     fn next(&mut self) -> Option<&'a [T]> {
3068         if self.finished { return None; }
3069
3070         match self.v.iter().position(|x| (self.pred)(x)) {
3071             None => self.finish(),
3072             Some(idx) => {
3073                 let ret = Some(&self.v[..idx]);
3074                 self.v = &self.v[idx + 1..];
3075                 ret
3076             }
3077         }
3078     }
3079
3080     #[inline]
3081     fn size_hint(&self) -> (usize, Option<usize>) {
3082         if self.finished {
3083             (0, Some(0))
3084         } else {
3085             (1, Some(self.v.len() + 1))
3086         }
3087     }
3088 }
3089
3090 #[stable(feature = "rust1", since = "1.0.0")]
3091 impl<'a, T, P> DoubleEndedIterator for Split<'a, T, P> where P: FnMut(&T) -> bool {
3092     #[inline]
3093     fn next_back(&mut self) -> Option<&'a [T]> {
3094         if self.finished { return None; }
3095
3096         match self.v.iter().rposition(|x| (self.pred)(x)) {
3097             None => self.finish(),
3098             Some(idx) => {
3099                 let ret = Some(&self.v[idx + 1..]);
3100                 self.v = &self.v[..idx];
3101                 ret
3102             }
3103         }
3104     }
3105 }
3106
3107 impl<'a, T, P> SplitIter for Split<'a, T, P> where P: FnMut(&T) -> bool {
3108     #[inline]
3109     fn finish(&mut self) -> Option<&'a [T]> {
3110         if self.finished { None } else { self.finished = true; Some(self.v) }
3111     }
3112 }
3113
3114 #[stable(feature = "fused", since = "1.26.0")]
3115 impl<T, P> FusedIterator for Split<'_, T, P> where P: FnMut(&T) -> bool {}
3116
3117 /// An iterator over the subslices of the vector which are separated
3118 /// by elements that match `pred`.
3119 ///
3120 /// This struct is created by the [`split_mut`] method on [slices].
3121 ///
3122 /// [`split_mut`]: ../../std/primitive.slice.html#method.split_mut
3123 /// [slices]: ../../std/primitive.slice.html
3124 #[stable(feature = "rust1", since = "1.0.0")]
3125 pub struct SplitMut<'a, T:'a, P> where P: FnMut(&T) -> bool {
3126     v: &'a mut [T],
3127     pred: P,
3128     finished: bool
3129 }
3130
3131 #[stable(feature = "core_impl_debug", since = "1.9.0")]
3132 impl<T: fmt::Debug, P> fmt::Debug for SplitMut<'_, T, P> where P: FnMut(&T) -> bool {
3133     fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
3134         f.debug_struct("SplitMut")
3135             .field("v", &self.v)
3136             .field("finished", &self.finished)
3137             .finish()
3138     }
3139 }
3140
3141 impl<'a, T, P> SplitIter for SplitMut<'a, T, P> where P: FnMut(&T) -> bool {
3142     #[inline]
3143     fn finish(&mut self) -> Option<&'a mut [T]> {
3144         if self.finished {
3145             None
3146         } else {
3147             self.finished = true;
3148             Some(mem::replace(&mut self.v, &mut []))
3149         }
3150     }
3151 }
3152
3153 #[stable(feature = "rust1", since = "1.0.0")]
3154 impl<'a, T, P> Iterator for SplitMut<'a, T, P> where P: FnMut(&T) -> bool {
3155     type Item = &'a mut [T];
3156
3157     #[inline]
3158     fn next(&mut self) -> Option<&'a mut [T]> {
3159         if self.finished { return None; }
3160
3161         let idx_opt = { // work around borrowck limitations
3162             let pred = &mut self.pred;
3163             self.v.iter().position(|x| (*pred)(x))
3164         };
3165         match idx_opt {
3166             None => self.finish(),
3167             Some(idx) => {
3168                 let tmp = mem::replace(&mut self.v, &mut []);
3169                 let (head, tail) = tmp.split_at_mut(idx);
3170                 self.v = &mut tail[1..];
3171                 Some(head)
3172             }
3173         }
3174     }
3175
3176     #[inline]
3177     fn size_hint(&self) -> (usize, Option<usize>) {
3178         if self.finished {
3179             (0, Some(0))
3180         } else {
3181             // if the predicate doesn't match anything, we yield one slice
3182             // if it matches every element, we yield len+1 empty slices.
3183             (1, Some(self.v.len() + 1))
3184         }
3185     }
3186 }
3187
3188 #[stable(feature = "rust1", since = "1.0.0")]
3189 impl<'a, T, P> DoubleEndedIterator for SplitMut<'a, T, P> where
3190     P: FnMut(&T) -> bool,
3191 {
3192     #[inline]
3193     fn next_back(&mut self) -> Option<&'a mut [T]> {
3194         if self.finished { return None; }
3195
3196         let idx_opt = { // work around borrowck limitations
3197             let pred = &mut self.pred;
3198             self.v.iter().rposition(|x| (*pred)(x))
3199         };
3200         match idx_opt {
3201             None => self.finish(),
3202             Some(idx) => {
3203                 let tmp = mem::replace(&mut self.v, &mut []);
3204                 let (head, tail) = tmp.split_at_mut(idx);
3205                 self.v = head;
3206                 Some(&mut tail[1..])
3207             }
3208         }
3209     }
3210 }
3211
3212 #[stable(feature = "fused", since = "1.26.0")]
3213 impl<T, P> FusedIterator for SplitMut<'_, T, P> where P: FnMut(&T) -> bool {}
3214
3215 /// An iterator over subslices separated by elements that match a predicate
3216 /// function, starting from the end of the slice.
3217 ///
3218 /// This struct is created by the [`rsplit`] method on [slices].
3219 ///
3220 /// [`rsplit`]: ../../std/primitive.slice.html#method.rsplit
3221 /// [slices]: ../../std/primitive.slice.html
3222 #[stable(feature = "slice_rsplit", since = "1.27.0")]
3223 #[derive(Clone)] // Is this correct, or does it incorrectly require `T: Clone`?
3224 pub struct RSplit<'a, T:'a, P> where P: FnMut(&T) -> bool {
3225     inner: Split<'a, T, P>
3226 }
3227
3228 #[stable(feature = "slice_rsplit", since = "1.27.0")]
3229 impl<T: fmt::Debug, P> fmt::Debug for RSplit<'_, T, P> where P: FnMut(&T) -> bool {
3230     fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
3231         f.debug_struct("RSplit")
3232             .field("v", &self.inner.v)
3233             .field("finished", &self.inner.finished)
3234             .finish()
3235     }
3236 }
3237
3238 #[stable(feature = "slice_rsplit", since = "1.27.0")]
3239 impl<'a, T, P> Iterator for RSplit<'a, T, P> where P: FnMut(&T) -> bool {
3240     type Item = &'a [T];
3241
3242     #[inline]
3243     fn next(&mut self) -> Option<&'a [T]> {
3244         self.inner.next_back()
3245     }
3246
3247     #[inline]
3248     fn size_hint(&self) -> (usize, Option<usize>) {
3249         self.inner.size_hint()
3250     }
3251 }
3252
3253 #[stable(feature = "slice_rsplit", since = "1.27.0")]
3254 impl<'a, T, P> DoubleEndedIterator for RSplit<'a, T, P> where P: FnMut(&T) -> bool {
3255     #[inline]
3256     fn next_back(&mut self) -> Option<&'a [T]> {
3257         self.inner.next()
3258     }
3259 }
3260
3261 #[stable(feature = "slice_rsplit", since = "1.27.0")]
3262 impl<'a, T, P> SplitIter for RSplit<'a, T, P> where P: FnMut(&T) -> bool {
3263     #[inline]
3264     fn finish(&mut self) -> Option<&'a [T]> {
3265         self.inner.finish()
3266     }
3267 }
3268
3269 #[stable(feature = "slice_rsplit", since = "1.27.0")]
3270 impl<T, P> FusedIterator for RSplit<'_, T, P> where P: FnMut(&T) -> bool {}
3271
3272 /// An iterator over the subslices of the vector which are separated
3273 /// by elements that match `pred`, starting from the end of the slice.
3274 ///
3275 /// This struct is created by the [`rsplit_mut`] method on [slices].
3276 ///
3277 /// [`rsplit_mut`]: ../../std/primitive.slice.html#method.rsplit_mut
3278 /// [slices]: ../../std/primitive.slice.html
3279 #[stable(feature = "slice_rsplit", since = "1.27.0")]
3280 pub struct RSplitMut<'a, T:'a, P> where P: FnMut(&T) -> bool {
3281     inner: SplitMut<'a, T, P>
3282 }
3283
3284 #[stable(feature = "slice_rsplit", since = "1.27.0")]
3285 impl<T: fmt::Debug, P> fmt::Debug for RSplitMut<'_, T, P> where P: FnMut(&T) -> bool {
3286     fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
3287         f.debug_struct("RSplitMut")
3288             .field("v", &self.inner.v)
3289             .field("finished", &self.inner.finished)
3290             .finish()
3291     }
3292 }
3293
3294 #[stable(feature = "slice_rsplit", since = "1.27.0")]
3295 impl<'a, T, P> SplitIter for RSplitMut<'a, T, P> where P: FnMut(&T) -> bool {
3296     #[inline]
3297     fn finish(&mut self) -> Option<&'a mut [T]> {
3298         self.inner.finish()
3299     }
3300 }
3301
3302 #[stable(feature = "slice_rsplit", since = "1.27.0")]
3303 impl<'a, T, P> Iterator for RSplitMut<'a, T, P> where P: FnMut(&T) -> bool {
3304     type Item = &'a mut [T];
3305
3306     #[inline]
3307     fn next(&mut self) -> Option<&'a mut [T]> {
3308         self.inner.next_back()
3309     }
3310
3311     #[inline]
3312     fn size_hint(&self) -> (usize, Option<usize>) {
3313         self.inner.size_hint()
3314     }
3315 }
3316
3317 #[stable(feature = "slice_rsplit", since = "1.27.0")]
3318 impl<'a, T, P> DoubleEndedIterator for RSplitMut<'a, T, P> where
3319     P: FnMut(&T) -> bool,
3320 {
3321     #[inline]
3322     fn next_back(&mut self) -> Option<&'a mut [T]> {
3323         self.inner.next()
3324     }
3325 }
3326
3327 #[stable(feature = "slice_rsplit", since = "1.27.0")]
3328 impl<T, P> FusedIterator for RSplitMut<'_, T, P> where P: FnMut(&T) -> bool {}
3329
3330 /// An private iterator over subslices separated by elements that
3331 /// match a predicate function, splitting at most a fixed number of
3332 /// times.
3333 #[derive(Debug)]
3334 struct GenericSplitN<I> {
3335     iter: I,
3336     count: usize,
3337 }
3338
3339 impl<T, I: SplitIter<Item=T>> Iterator for GenericSplitN<I> {
3340     type Item = T;
3341
3342     #[inline]
3343     fn next(&mut self) -> Option<T> {
3344         match self.count {
3345             0 => None,
3346             1 => { self.count -= 1; self.iter.finish() }
3347             _ => { self.count -= 1; self.iter.next() }
3348         }
3349     }
3350
3351     #[inline]
3352     fn size_hint(&self) -> (usize, Option<usize>) {
3353         let (lower, upper_opt) = self.iter.size_hint();
3354         (lower, upper_opt.map(|upper| cmp::min(self.count, upper)))
3355     }
3356 }
3357
3358 /// An iterator over subslices separated by elements that match a predicate
3359 /// function, limited to a given number of splits.
3360 ///
3361 /// This struct is created by the [`splitn`] method on [slices].
3362 ///
3363 /// [`splitn`]: ../../std/primitive.slice.html#method.splitn
3364 /// [slices]: ../../std/primitive.slice.html
3365 #[stable(feature = "rust1", since = "1.0.0")]
3366 pub struct SplitN<'a, T: 'a, P> where P: FnMut(&T) -> bool {
3367     inner: GenericSplitN<Split<'a, T, P>>
3368 }
3369
3370 #[stable(feature = "core_impl_debug", since = "1.9.0")]
3371 impl<T: fmt::Debug, P> fmt::Debug for SplitN<'_, T, P> where P: FnMut(&T) -> bool {
3372     fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
3373         f.debug_struct("SplitN")
3374             .field("inner", &self.inner)
3375             .finish()
3376     }
3377 }
3378
3379 /// An iterator over subslices separated by elements that match a
3380 /// predicate function, limited to a given number of splits, starting
3381 /// from the end of the slice.
3382 ///
3383 /// This struct is created by the [`rsplitn`] method on [slices].
3384 ///
3385 /// [`rsplitn`]: ../../std/primitive.slice.html#method.rsplitn
3386 /// [slices]: ../../std/primitive.slice.html
3387 #[stable(feature = "rust1", since = "1.0.0")]
3388 pub struct RSplitN<'a, T: 'a, P> where P: FnMut(&T) -> bool {
3389     inner: GenericSplitN<RSplit<'a, T, P>>
3390 }
3391
3392 #[stable(feature = "core_impl_debug", since = "1.9.0")]
3393 impl<T: fmt::Debug, P> fmt::Debug for RSplitN<'_, T, P> where P: FnMut(&T) -> bool {
3394     fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
3395         f.debug_struct("RSplitN")
3396             .field("inner", &self.inner)
3397             .finish()
3398     }
3399 }
3400
3401 /// An iterator over subslices separated by elements that match a predicate
3402 /// function, limited to a given number of splits.
3403 ///
3404 /// This struct is created by the [`splitn_mut`] method on [slices].
3405 ///
3406 /// [`splitn_mut`]: ../../std/primitive.slice.html#method.splitn_mut
3407 /// [slices]: ../../std/primitive.slice.html
3408 #[stable(feature = "rust1", since = "1.0.0")]
3409 pub struct SplitNMut<'a, T: 'a, P> where P: FnMut(&T) -> bool {
3410     inner: GenericSplitN<SplitMut<'a, T, P>>
3411 }
3412
3413 #[stable(feature = "core_impl_debug", since = "1.9.0")]
3414 impl<T: fmt::Debug, P> fmt::Debug for SplitNMut<'_, T, P> where P: FnMut(&T) -> bool {
3415     fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
3416         f.debug_struct("SplitNMut")
3417             .field("inner", &self.inner)
3418             .finish()
3419     }
3420 }
3421
3422 /// An iterator over subslices separated by elements that match a
3423 /// predicate function, limited to a given number of splits, starting
3424 /// from the end of the slice.
3425 ///
3426 /// This struct is created by the [`rsplitn_mut`] method on [slices].
3427 ///
3428 /// [`rsplitn_mut`]: ../../std/primitive.slice.html#method.rsplitn_mut
3429 /// [slices]: ../../std/primitive.slice.html
3430 #[stable(feature = "rust1", since = "1.0.0")]
3431 pub struct RSplitNMut<'a, T: 'a, P> where P: FnMut(&T) -> bool {
3432     inner: GenericSplitN<RSplitMut<'a, T, P>>
3433 }
3434
3435 #[stable(feature = "core_impl_debug", since = "1.9.0")]
3436 impl<T: fmt::Debug, P> fmt::Debug for RSplitNMut<'_, T, P> where P: FnMut(&T) -> bool {
3437     fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
3438         f.debug_struct("RSplitNMut")
3439             .field("inner", &self.inner)
3440             .finish()
3441     }
3442 }
3443
3444 macro_rules! forward_iterator {
3445     ($name:ident: $elem:ident, $iter_of:ty) => {
3446         #[stable(feature = "rust1", since = "1.0.0")]
3447         impl<'a, $elem, P> Iterator for $name<'a, $elem, P> where
3448             P: FnMut(&T) -> bool
3449         {
3450             type Item = $iter_of;
3451
3452             #[inline]
3453             fn next(&mut self) -> Option<$iter_of> {
3454                 self.inner.next()
3455             }
3456
3457             #[inline]
3458             fn size_hint(&self) -> (usize, Option<usize>) {
3459                 self.inner.size_hint()
3460             }
3461         }
3462
3463         #[stable(feature = "fused", since = "1.26.0")]
3464         impl<'a, $elem, P> FusedIterator for $name<'a, $elem, P>
3465             where P: FnMut(&T) -> bool {}
3466     }
3467 }
3468
3469 forward_iterator! { SplitN: T, &'a [T] }
3470 forward_iterator! { RSplitN: T, &'a [T] }
3471 forward_iterator! { SplitNMut: T, &'a mut [T] }
3472 forward_iterator! { RSplitNMut: T, &'a mut [T] }
3473
3474 /// An iterator over overlapping subslices of length `size`.
3475 ///
3476 /// This struct is created by the [`windows`] method on [slices].
3477 ///
3478 /// [`windows`]: ../../std/primitive.slice.html#method.windows
3479 /// [slices]: ../../std/primitive.slice.html
3480 #[derive(Debug)]
3481 #[stable(feature = "rust1", since = "1.0.0")]
3482 pub struct Windows<'a, T:'a> {
3483     v: &'a [T],
3484     size: usize
3485 }
3486
3487 // FIXME(#26925) Remove in favor of `#[derive(Clone)]`
3488 #[stable(feature = "rust1", since = "1.0.0")]
3489 impl<T> Clone for Windows<'_, T> {
3490     fn clone(&self) -> Self {
3491         Windows {
3492             v: self.v,
3493             size: self.size,
3494         }
3495     }
3496 }
3497
3498 #[stable(feature = "rust1", since = "1.0.0")]
3499 impl<'a, T> Iterator for Windows<'a, T> {
3500     type Item = &'a [T];
3501
3502     #[inline]
3503     fn next(&mut self) -> Option<&'a [T]> {
3504         if self.size > self.v.len() {
3505             None
3506         } else {
3507             let ret = Some(&self.v[..self.size]);
3508             self.v = &self.v[1..];
3509             ret
3510         }
3511     }
3512
3513     #[inline]
3514     fn size_hint(&self) -> (usize, Option<usize>) {
3515         if self.size > self.v.len() {
3516             (0, Some(0))
3517         } else {
3518             let size = self.v.len() - self.size + 1;
3519             (size, Some(size))
3520         }
3521     }
3522
3523     #[inline]
3524     fn count(self) -> usize {
3525         self.len()
3526     }
3527
3528     #[inline]
3529     fn nth(&mut self, n: usize) -> Option<Self::Item> {
3530         let (end, overflow) = self.size.overflowing_add(n);
3531         if end > self.v.len() || overflow {
3532             self.v = &[];
3533             None
3534         } else {
3535             let nth = &self.v[n..end];
3536             self.v = &self.v[n+1..];
3537             Some(nth)
3538         }
3539     }
3540
3541     #[inline]
3542     fn last(self) -> Option<Self::Item> {
3543         if self.size > self.v.len() {
3544             None
3545         } else {
3546             let start = self.v.len() - self.size;
3547             Some(&self.v[start..])
3548         }
3549     }
3550 }
3551
3552 #[stable(feature = "rust1", since = "1.0.0")]
3553 impl<'a, T> DoubleEndedIterator for Windows<'a, T> {
3554     #[inline]
3555     fn next_back(&mut self) -> Option<&'a [T]> {
3556         if self.size > self.v.len() {
3557             None
3558         } else {
3559             let ret = Some(&self.v[self.v.len()-self.size..]);
3560             self.v = &self.v[..self.v.len()-1];
3561             ret
3562         }
3563     }
3564 }
3565
3566 #[stable(feature = "rust1", since = "1.0.0")]
3567 impl<T> ExactSizeIterator for Windows<'_, T> {}
3568
3569 #[unstable(feature = "trusted_len", issue = "37572")]
3570 unsafe impl<T> TrustedLen for Windows<'_, T> {}
3571
3572 #[stable(feature = "fused", since = "1.26.0")]
3573 impl<T> FusedIterator for Windows<'_, T> {}
3574
3575 #[doc(hidden)]
3576 unsafe impl<'a, T> TrustedRandomAccess for Windows<'a, T> {
3577     unsafe fn get_unchecked(&mut self, i: usize) -> &'a [T] {
3578         from_raw_parts(self.v.as_ptr().add(i), self.size)
3579     }
3580     fn may_have_side_effect() -> bool { false }
3581 }
3582
3583 /// An iterator over a slice in (non-overlapping) chunks (`chunk_size` elements at a
3584 /// time).
3585 ///
3586 /// When the slice len is not evenly divided by the chunk size, the last slice
3587 /// of the iteration will be the remainder.
3588 ///
3589 /// This struct is created by the [`chunks`] method on [slices].
3590 ///
3591 /// [`chunks`]: ../../std/primitive.slice.html#method.chunks
3592 /// [slices]: ../../std/primitive.slice.html
3593 #[derive(Debug)]
3594 #[stable(feature = "rust1", since = "1.0.0")]
3595 pub struct Chunks<'a, T:'a> {
3596     v: &'a [T],
3597     chunk_size: usize
3598 }
3599
3600 // FIXME(#26925) Remove in favor of `#[derive(Clone)]`
3601 #[stable(feature = "rust1", since = "1.0.0")]
3602 impl<T> Clone for Chunks<'_, T> {
3603     fn clone(&self) -> Self {
3604         Chunks {
3605             v: self.v,
3606             chunk_size: self.chunk_size,
3607         }
3608     }
3609 }
3610
3611 #[stable(feature = "rust1", since = "1.0.0")]
3612 impl<'a, T> Iterator for Chunks<'a, T> {
3613     type Item = &'a [T];
3614
3615     #[inline]
3616     fn next(&mut self) -> Option<&'a [T]> {
3617         if self.v.is_empty() {
3618             None
3619         } else {
3620             let chunksz = cmp::min(self.v.len(), self.chunk_size);
3621             let (fst, snd) = self.v.split_at(chunksz);
3622             self.v = snd;
3623             Some(fst)
3624         }
3625     }
3626
3627     #[inline]
3628     fn size_hint(&self) -> (usize, Option<usize>) {
3629         if self.v.is_empty() {
3630             (0, Some(0))
3631         } else {
3632             let n = self.v.len() / self.chunk_size;
3633             let rem = self.v.len() % self.chunk_size;
3634             let n = if rem > 0 { n+1 } else { n };
3635             (n, Some(n))
3636         }
3637     }
3638
3639     #[inline]
3640     fn count(self) -> usize {
3641         self.len()
3642     }
3643
3644     #[inline]
3645     fn nth(&mut self, n: usize) -> Option<Self::Item> {
3646         let (start, overflow) = n.overflowing_mul(self.chunk_size);
3647         if start >= self.v.len() || overflow {
3648             self.v = &[];
3649             None
3650         } else {
3651             let end = match start.checked_add(self.chunk_size) {
3652                 Some(sum) => cmp::min(self.v.len(), sum),
3653                 None => self.v.len(),
3654             };
3655             let nth = &self.v[start..end];
3656             self.v = &self.v[end..];
3657             Some(nth)
3658         }
3659     }
3660
3661     #[inline]
3662     fn last(self) -> Option<Self::Item> {
3663         if self.v.is_empty() {
3664             None
3665         } else {
3666             let start = (self.v.len() - 1) / self.chunk_size * self.chunk_size;
3667             Some(&self.v[start..])
3668         }
3669     }
3670 }
3671
3672 #[stable(feature = "rust1", since = "1.0.0")]
3673 impl<'a, T> DoubleEndedIterator for Chunks<'a, T> {
3674     #[inline]
3675     fn next_back(&mut self) -> Option<&'a [T]> {
3676         if self.v.is_empty() {
3677             None
3678         } else {
3679             let remainder = self.v.len() % self.chunk_size;
3680             let chunksz = if remainder != 0 { remainder } else { self.chunk_size };
3681             let (fst, snd) = self.v.split_at(self.v.len() - chunksz);
3682             self.v = fst;
3683             Some(snd)
3684         }
3685     }
3686 }
3687
3688 #[stable(feature = "rust1", since = "1.0.0")]
3689 impl<T> ExactSizeIterator for Chunks<'_, T> {}
3690
3691 #[unstable(feature = "trusted_len", issue = "37572")]
3692 unsafe impl<T> TrustedLen for Chunks<'_, T> {}
3693
3694 #[stable(feature = "fused", since = "1.26.0")]
3695 impl<T> FusedIterator for Chunks<'_, T> {}
3696
3697 #[doc(hidden)]
3698 unsafe impl<'a, T> TrustedRandomAccess for Chunks<'a, T> {
3699     unsafe fn get_unchecked(&mut self, i: usize) -> &'a [T] {
3700         let start = i * self.chunk_size;
3701         let end = match start.checked_add(self.chunk_size) {
3702             None => self.v.len(),
3703             Some(end) => cmp::min(end, self.v.len()),
3704         };
3705         from_raw_parts(self.v.as_ptr().add(start), end - start)
3706     }
3707     fn may_have_side_effect() -> bool { false }
3708 }
3709
3710 /// An iterator over a slice in (non-overlapping) mutable chunks (`chunk_size`
3711 /// elements at a time). When the slice len is not evenly divided by the chunk
3712 /// size, the last slice of the iteration will be the remainder.
3713 ///
3714 /// This struct is created by the [`chunks_mut`] method on [slices].
3715 ///
3716 /// [`chunks_mut`]: ../../std/primitive.slice.html#method.chunks_mut
3717 /// [slices]: ../../std/primitive.slice.html
3718 #[derive(Debug)]
3719 #[stable(feature = "rust1", since = "1.0.0")]
3720 pub struct ChunksMut<'a, T:'a> {
3721     v: &'a mut [T],
3722     chunk_size: usize
3723 }
3724
3725 #[stable(feature = "rust1", since = "1.0.0")]
3726 impl<'a, T> Iterator for ChunksMut<'a, T> {
3727     type Item = &'a mut [T];
3728
3729     #[inline]
3730     fn next(&mut self) -> Option<&'a mut [T]> {
3731         if self.v.is_empty() {
3732             None
3733         } else {
3734             let sz = cmp::min(self.v.len(), self.chunk_size);
3735             let tmp = mem::replace(&mut self.v, &mut []);
3736             let (head, tail) = tmp.split_at_mut(sz);
3737             self.v = tail;
3738             Some(head)
3739         }
3740     }
3741
3742     #[inline]
3743     fn size_hint(&self) -> (usize, Option<usize>) {
3744         if self.v.is_empty() {
3745             (0, Some(0))
3746         } else {
3747             let n = self.v.len() / self.chunk_size;
3748             let rem = self.v.len() % self.chunk_size;
3749             let n = if rem > 0 { n + 1 } else { n };
3750             (n, Some(n))
3751         }
3752     }
3753
3754     #[inline]
3755     fn count(self) -> usize {
3756         self.len()
3757     }
3758
3759     #[inline]
3760     fn nth(&mut self, n: usize) -> Option<&'a mut [T]> {
3761         let (start, overflow) = n.overflowing_mul(self.chunk_size);
3762         if start >= self.v.len() || overflow {
3763             self.v = &mut [];
3764             None
3765         } else {
3766             let end = match start.checked_add(self.chunk_size) {
3767                 Some(sum) => cmp::min(self.v.len(), sum),
3768                 None => self.v.len(),
3769             };
3770             let tmp = mem::replace(&mut self.v, &mut []);
3771             let (head, tail) = tmp.split_at_mut(end);
3772             let (_, nth) =  head.split_at_mut(start);
3773             self.v = tail;
3774             Some(nth)
3775         }
3776     }
3777
3778     #[inline]
3779     fn last(self) -> Option<Self::Item> {
3780         if self.v.is_empty() {
3781             None
3782         } else {
3783             let start = (self.v.len() - 1) / self.chunk_size * self.chunk_size;
3784             Some(&mut self.v[start..])
3785         }
3786     }
3787 }
3788
3789 #[stable(feature = "rust1", since = "1.0.0")]
3790 impl<'a, T> DoubleEndedIterator for ChunksMut<'a, T> {
3791     #[inline]
3792     fn next_back(&mut self) -> Option<&'a mut [T]> {
3793         if self.v.is_empty() {
3794             None
3795         } else {
3796             let remainder = self.v.len() % self.chunk_size;
3797             let sz = if remainder != 0 { remainder } else { self.chunk_size };
3798             let tmp = mem::replace(&mut self.v, &mut []);
3799             let tmp_len = tmp.len();
3800             let (head, tail) = tmp.split_at_mut(tmp_len - sz);
3801             self.v = head;
3802             Some(tail)
3803         }
3804     }
3805 }
3806
3807 #[stable(feature = "rust1", since = "1.0.0")]
3808 impl<T> ExactSizeIterator for ChunksMut<'_, T> {}
3809
3810 #[unstable(feature = "trusted_len", issue = "37572")]
3811 unsafe impl<T> TrustedLen for ChunksMut<'_, T> {}
3812
3813 #[stable(feature = "fused", since = "1.26.0")]
3814 impl<T> FusedIterator for ChunksMut<'_, T> {}
3815
3816 #[doc(hidden)]
3817 unsafe impl<'a, T> TrustedRandomAccess for ChunksMut<'a, T> {
3818     unsafe fn get_unchecked(&mut self, i: usize) -> &'a mut [T] {
3819         let start = i * self.chunk_size;
3820         let end = match start.checked_add(self.chunk_size) {
3821             None => self.v.len(),
3822             Some(end) => cmp::min(end, self.v.len()),
3823         };
3824         from_raw_parts_mut(self.v.as_mut_ptr().add(start), end - start)
3825     }
3826     fn may_have_side_effect() -> bool { false }
3827 }
3828
3829 /// An iterator over a slice in (non-overlapping) chunks (`chunk_size` elements at a
3830 /// time).
3831 ///
3832 /// When the slice len is not evenly divided by the chunk size, the last
3833 /// up to `chunk_size-1` elements will be omitted but can be retrieved from
3834 /// the [`remainder`] function from the iterator.
3835 ///
3836 /// This struct is created by the [`chunks_exact`] method on [slices].
3837 ///
3838 /// [`chunks_exact`]: ../../std/primitive.slice.html#method.chunks_exact
3839 /// [`remainder`]: ../../std/slice/struct.ChunksExact.html#method.remainder
3840 /// [slices]: ../../std/primitive.slice.html
3841 #[derive(Debug)]
3842 #[unstable(feature = "chunks_exact", issue = "47115")]
3843 pub struct ChunksExact<'a, T:'a> {
3844     v: &'a [T],
3845     rem: &'a [T],
3846     chunk_size: usize
3847 }
3848
3849 #[unstable(feature = "chunks_exact", issue = "47115")]
3850 impl<'a, T> ChunksExact<'a, T> {
3851     /// Return the remainder of the original slice that is not going to be
3852     /// returned by the iterator. The returned slice has at most `chunk_size-1`
3853     /// elements.
3854     pub fn remainder(&self) -> &'a [T] {
3855         self.rem
3856     }
3857 }
3858
3859 // FIXME(#26925) Remove in favor of `#[derive(Clone)]`
3860 #[unstable(feature = "chunks_exact", issue = "47115")]
3861 impl<T> Clone for ChunksExact<'_, T> {
3862     fn clone(&self) -> Self {
3863         ChunksExact {
3864             v: self.v,
3865             rem: self.rem,
3866             chunk_size: self.chunk_size,
3867         }
3868     }
3869 }
3870
3871 #[unstable(feature = "chunks_exact", issue = "47115")]
3872 impl<'a, T> Iterator for ChunksExact<'a, T> {
3873     type Item = &'a [T];
3874
3875     #[inline]
3876     fn next(&mut self) -> Option<&'a [T]> {
3877         if self.v.len() < self.chunk_size {
3878             None
3879         } else {
3880             let (fst, snd) = self.v.split_at(self.chunk_size);
3881             self.v = snd;
3882             Some(fst)
3883         }
3884     }
3885
3886     #[inline]
3887     fn size_hint(&self) -> (usize, Option<usize>) {
3888         let n = self.v.len() / self.chunk_size;
3889         (n, Some(n))
3890     }
3891
3892     #[inline]
3893     fn count(self) -> usize {
3894         self.len()
3895     }
3896
3897     #[inline]
3898     fn nth(&mut self, n: usize) -> Option<Self::Item> {
3899         let (start, overflow) = n.overflowing_mul(self.chunk_size);
3900         if start >= self.v.len() || overflow {
3901             self.v = &[];
3902             None
3903         } else {
3904             let (_, snd) = self.v.split_at(start);
3905             self.v = snd;
3906             self.next()
3907         }
3908     }
3909
3910     #[inline]
3911     fn last(mut self) -> Option<Self::Item> {
3912         self.next_back()
3913     }
3914 }
3915
3916 #[unstable(feature = "chunks_exact", issue = "47115")]
3917 impl<'a, T> DoubleEndedIterator for ChunksExact<'a, T> {
3918     #[inline]
3919     fn next_back(&mut self) -> Option<&'a [T]> {
3920         if self.v.len() < self.chunk_size {
3921             None
3922         } else {
3923             let (fst, snd) = self.v.split_at(self.v.len() - self.chunk_size);
3924             self.v = fst;
3925             Some(snd)
3926         }
3927     }
3928 }
3929
3930 #[unstable(feature = "chunks_exact", issue = "47115")]
3931 impl<T> ExactSizeIterator for ChunksExact<'_, T> {
3932     fn is_empty(&self) -> bool {
3933         self.v.is_empty()
3934     }
3935 }
3936
3937 #[unstable(feature = "trusted_len", issue = "37572")]
3938 unsafe impl<T> TrustedLen for ChunksExact<'_, T> {}
3939
3940 #[unstable(feature = "chunks_exact", issue = "47115")]
3941 impl<T> FusedIterator for ChunksExact<'_, T> {}
3942
3943 #[doc(hidden)]
3944 unsafe impl<'a, T> TrustedRandomAccess for ChunksExact<'a, T> {
3945     unsafe fn get_unchecked(&mut self, i: usize) -> &'a [T] {
3946         let start = i * self.chunk_size;
3947         from_raw_parts(self.v.as_ptr().add(start), self.chunk_size)
3948     }
3949     fn may_have_side_effect() -> bool { false }
3950 }
3951
3952 /// An iterator over a slice in (non-overlapping) mutable chunks (`chunk_size`
3953 /// elements at a time).
3954 ///
3955 /// When the slice len is not evenly divided by the chunk size, the last up to
3956 /// `chunk_size-1` elements will be omitted but can be retrieved from the
3957 /// [`into_remainder`] function from the iterator.
3958 ///
3959 /// This struct is created by the [`chunks_exact_mut`] method on [slices].
3960 ///
3961 /// [`chunks_exact_mut`]: ../../std/primitive.slice.html#method.chunks_exact_mut
3962 /// [`into_remainder`]: ../../std/slice/struct.ChunksExactMut.html#method.into_remainder
3963 /// [slices]: ../../std/primitive.slice.html
3964 #[derive(Debug)]
3965 #[unstable(feature = "chunks_exact", issue = "47115")]
3966 pub struct ChunksExactMut<'a, T:'a> {
3967     v: &'a mut [T],
3968     rem: &'a mut [T],
3969     chunk_size: usize
3970 }
3971
3972 #[unstable(feature = "chunks_exact", issue = "47115")]
3973 impl<'a, T> ChunksExactMut<'a, T> {
3974     /// Return the remainder of the original slice that is not going to be
3975     /// returned by the iterator. The returned slice has at most `chunk_size-1`
3976     /// elements.
3977     pub fn into_remainder(self) -> &'a mut [T] {
3978         self.rem
3979     }
3980 }
3981
3982 #[unstable(feature = "chunks_exact", issue = "47115")]
3983 impl<'a, T> Iterator for ChunksExactMut<'a, T> {
3984     type Item = &'a mut [T];
3985
3986     #[inline]
3987     fn next(&mut self) -> Option<&'a mut [T]> {
3988         if self.v.len() < self.chunk_size {
3989             None
3990         } else {
3991             let tmp = mem::replace(&mut self.v, &mut []);
3992             let (head, tail) = tmp.split_at_mut(self.chunk_size);
3993             self.v = tail;
3994             Some(head)
3995         }
3996     }
3997
3998     #[inline]
3999     fn size_hint(&self) -> (usize, Option<usize>) {
4000         let n = self.v.len() / self.chunk_size;
4001         (n, Some(n))
4002     }
4003
4004     #[inline]
4005     fn count(self) -> usize {
4006         self.len()
4007     }
4008
4009     #[inline]
4010     fn nth(&mut self, n: usize) -> Option<&'a mut [T]> {
4011         let (start, overflow) = n.overflowing_mul(self.chunk_size);
4012         if start >= self.v.len() || overflow {
4013             self.v = &mut [];
4014             None
4015         } else {
4016             let tmp = mem::replace(&mut self.v, &mut []);
4017             let (_, snd) = tmp.split_at_mut(start);
4018             self.v = snd;
4019             self.next()
4020         }
4021     }
4022
4023     #[inline]
4024     fn last(mut self) -> Option<Self::Item> {
4025         self.next_back()
4026     }
4027 }
4028
4029 #[unstable(feature = "chunks_exact", issue = "47115")]
4030 impl<'a, T> DoubleEndedIterator for ChunksExactMut<'a, T> {
4031     #[inline]
4032     fn next_back(&mut self) -> Option<&'a mut [T]> {
4033         if self.v.len() < self.chunk_size {
4034             None
4035         } else {
4036             let tmp = mem::replace(&mut self.v, &mut []);
4037             let tmp_len = tmp.len();
4038             let (head, tail) = tmp.split_at_mut(tmp_len - self.chunk_size);
4039             self.v = head;
4040             Some(tail)
4041         }
4042     }
4043 }
4044
4045 #[unstable(feature = "chunks_exact", issue = "47115")]
4046 impl<T> ExactSizeIterator for ChunksExactMut<'_, T> {
4047     fn is_empty(&self) -> bool {
4048         self.v.is_empty()
4049     }
4050 }
4051
4052 #[unstable(feature = "trusted_len", issue = "37572")]
4053 unsafe impl<T> TrustedLen for ChunksExactMut<'_, T> {}
4054
4055 #[unstable(feature = "chunks_exact", issue = "47115")]
4056 impl<T> FusedIterator for ChunksExactMut<'_, T> {}
4057
4058 #[doc(hidden)]
4059 unsafe impl<'a, T> TrustedRandomAccess for ChunksExactMut<'a, T> {
4060     unsafe fn get_unchecked(&mut self, i: usize) -> &'a mut [T] {
4061         let start = i * self.chunk_size;
4062         from_raw_parts_mut(self.v.as_mut_ptr().add(start), self.chunk_size)
4063     }
4064     fn may_have_side_effect() -> bool { false }
4065 }
4066
4067 //
4068 // Free functions
4069 //
4070
4071 /// Forms a slice from a pointer and a length.
4072 ///
4073 /// The `len` argument is the number of **elements**, not the number of bytes.
4074 ///
4075 /// # Safety
4076 ///
4077 /// This function is unsafe as there is no guarantee that the given pointer is
4078 /// valid for `len` elements, nor whether the lifetime inferred is a suitable
4079 /// lifetime for the returned slice.
4080 ///
4081 /// `data` must be non-null and aligned, even for zero-length slices. One
4082 /// reason for this is that enum layout optimizations may rely on references
4083 /// (including slices of any length) being aligned and non-null to distinguish
4084 /// them from other data. You can obtain a pointer that is usable as `data`
4085 /// for zero-length slices using [`NonNull::dangling()`].
4086 ///
4087 /// The total size of the slice must be no larger than `isize::MAX` **bytes**
4088 /// in memory. See the safety documentation of [`pointer::offset`].
4089 ///
4090 /// # Caveat
4091 ///
4092 /// The lifetime for the returned slice is inferred from its usage. To
4093 /// prevent accidental misuse, it's suggested to tie the lifetime to whichever
4094 /// source lifetime is safe in the context, such as by providing a helper
4095 /// function taking the lifetime of a host value for the slice, or by explicit
4096 /// annotation.
4097 ///
4098 /// # Examples
4099 ///
4100 /// ```
4101 /// use std::slice;
4102 ///
4103 /// // manifest a slice for a single element
4104 /// let x = 42;
4105 /// let ptr = &x as *const _;
4106 /// let slice = unsafe { slice::from_raw_parts(ptr, 1) };
4107 /// assert_eq!(slice[0], 42);
4108 /// ```
4109 ///
4110 /// [`NonNull::dangling()`]: ../../std/ptr/struct.NonNull.html#method.dangling
4111 /// [`pointer::offset`]: ../../std/primitive.pointer.html#method.offset
4112 #[inline]
4113 #[stable(feature = "rust1", since = "1.0.0")]
4114 pub unsafe fn from_raw_parts<'a, T>(data: *const T, len: usize) -> &'a [T] {
4115     debug_assert!(data as usize % mem::align_of::<T>() == 0, "attempt to create unaligned slice");
4116     debug_assert!(mem::size_of::<T>().saturating_mul(len) <= isize::MAX as usize,
4117                   "attempt to create slice covering half the address space");
4118     Repr { raw: FatPtr { data, len } }.rust
4119 }
4120
4121 /// Performs the same functionality as [`from_raw_parts`], except that a
4122 /// mutable slice is returned.
4123 ///
4124 /// This function is unsafe for the same reasons as [`from_raw_parts`], as well
4125 /// as not being able to provide a non-aliasing guarantee of the returned
4126 /// mutable slice. `data` must be non-null and aligned even for zero-length
4127 /// slices as with [`from_raw_parts`]. The total size of the slice must be no
4128 /// larger than `isize::MAX` **bytes** in memory.
4129 ///
4130 /// See the documentation of [`from_raw_parts`] for more details.
4131 ///
4132 /// [`from_raw_parts`]: ../../std/slice/fn.from_raw_parts.html
4133 #[inline]
4134 #[stable(feature = "rust1", since = "1.0.0")]
4135 pub unsafe fn from_raw_parts_mut<'a, T>(data: *mut T, len: usize) -> &'a mut [T] {
4136     debug_assert!(data as usize % mem::align_of::<T>() == 0, "attempt to create unaligned slice");
4137     debug_assert!(mem::size_of::<T>().saturating_mul(len) <= isize::MAX as usize,
4138                   "attempt to create slice covering half the address space");
4139     Repr { raw: FatPtr { data, len } }.rust_mut
4140 }
4141
4142 /// Converts a reference to T into a slice of length 1 (without copying).
4143 #[stable(feature = "from_ref", since = "1.28.0")]
4144 pub fn from_ref<T>(s: &T) -> &[T] {
4145     unsafe {
4146         from_raw_parts(s, 1)
4147     }
4148 }
4149
4150 /// Converts a reference to T into a slice of length 1 (without copying).
4151 #[stable(feature = "from_ref", since = "1.28.0")]
4152 pub fn from_mut<T>(s: &mut T) -> &mut [T] {
4153     unsafe {
4154         from_raw_parts_mut(s, 1)
4155     }
4156 }
4157
4158 // This function is public only because there is no other way to unit test heapsort.
4159 #[unstable(feature = "sort_internals", reason = "internal to sort module", issue = "0")]
4160 #[doc(hidden)]
4161 pub fn heapsort<T, F>(v: &mut [T], mut is_less: F)
4162     where F: FnMut(&T, &T) -> bool
4163 {
4164     sort::heapsort(v, &mut is_less);
4165 }
4166
4167 //
4168 // Comparison traits
4169 //
4170
4171 extern {
4172     /// Calls implementation provided memcmp.
4173     ///
4174     /// Interprets the data as u8.
4175     ///
4176     /// Returns 0 for equal, < 0 for less than and > 0 for greater
4177     /// than.
4178     // FIXME(#32610): Return type should be c_int
4179     fn memcmp(s1: *const u8, s2: *const u8, n: usize) -> i32;
4180 }
4181
4182 #[stable(feature = "rust1", since = "1.0.0")]
4183 impl<A, B> PartialEq<[B]> for [A] where A: PartialEq<B> {
4184     fn eq(&self, other: &[B]) -> bool {
4185         SlicePartialEq::equal(self, other)
4186     }
4187
4188     fn ne(&self, other: &[B]) -> bool {
4189         SlicePartialEq::not_equal(self, other)
4190     }
4191 }
4192
4193 #[stable(feature = "rust1", since = "1.0.0")]
4194 impl<T: Eq> Eq for [T] {}
4195
4196 /// Implements comparison of vectors lexicographically.
4197 #[stable(feature = "rust1", since = "1.0.0")]
4198 impl<T: Ord> Ord for [T] {
4199     fn cmp(&self, other: &[T]) -> Ordering {
4200         SliceOrd::compare(self, other)
4201     }
4202 }
4203
4204 /// Implements comparison of vectors lexicographically.
4205 #[stable(feature = "rust1", since = "1.0.0")]
4206 impl<T: PartialOrd> PartialOrd for [T] {
4207     fn partial_cmp(&self, other: &[T]) -> Option<Ordering> {
4208         SlicePartialOrd::partial_compare(self, other)
4209     }
4210 }
4211
4212 #[doc(hidden)]
4213 // intermediate trait for specialization of slice's PartialEq
4214 trait SlicePartialEq<B> {
4215     fn equal(&self, other: &[B]) -> bool;
4216
4217     fn not_equal(&self, other: &[B]) -> bool { !self.equal(other) }
4218 }
4219
4220 // Generic slice equality
4221 impl<A, B> SlicePartialEq<B> for [A]
4222     where A: PartialEq<B>
4223 {
4224     default fn equal(&self, other: &[B]) -> bool {
4225         if self.len() != other.len() {
4226             return false;
4227         }
4228
4229         for i in 0..self.len() {
4230             if !self[i].eq(&other[i]) {
4231                 return false;
4232             }
4233         }
4234
4235         true
4236     }
4237 }
4238
4239 // Use memcmp for bytewise equality when the types allow
4240 impl<A> SlicePartialEq<A> for [A]
4241     where A: PartialEq<A> + BytewiseEquality
4242 {
4243     fn equal(&self, other: &[A]) -> bool {
4244         if self.len() != other.len() {
4245             return false;
4246         }
4247         if self.as_ptr() == other.as_ptr() {
4248             return true;
4249         }
4250         unsafe {
4251             let size = mem::size_of_val(self);
4252             memcmp(self.as_ptr() as *const u8,
4253                    other.as_ptr() as *const u8, size) == 0
4254         }
4255     }
4256 }
4257
4258 #[doc(hidden)]
4259 // intermediate trait for specialization of slice's PartialOrd
4260 trait SlicePartialOrd<B> {
4261     fn partial_compare(&self, other: &[B]) -> Option<Ordering>;
4262 }
4263
4264 impl<A> SlicePartialOrd<A> for [A]
4265     where A: PartialOrd
4266 {
4267     default fn partial_compare(&self, other: &[A]) -> Option<Ordering> {
4268         let l = cmp::min(self.len(), other.len());
4269
4270         // Slice to the loop iteration range to enable bound check
4271         // elimination in the compiler
4272         let lhs = &self[..l];
4273         let rhs = &other[..l];
4274
4275         for i in 0..l {
4276             match lhs[i].partial_cmp(&rhs[i]) {
4277                 Some(Ordering::Equal) => (),
4278                 non_eq => return non_eq,
4279             }
4280         }
4281
4282         self.len().partial_cmp(&other.len())
4283     }
4284 }
4285
4286 impl<A> SlicePartialOrd<A> for [A]
4287     where A: Ord
4288 {
4289     default fn partial_compare(&self, other: &[A]) -> Option<Ordering> {
4290         Some(SliceOrd::compare(self, other))
4291     }
4292 }
4293
4294 #[doc(hidden)]
4295 // intermediate trait for specialization of slice's Ord
4296 trait SliceOrd<B> {
4297     fn compare(&self, other: &[B]) -> Ordering;
4298 }
4299
4300 impl<A> SliceOrd<A> for [A]
4301     where A: Ord
4302 {
4303     default fn compare(&self, other: &[A]) -> Ordering {
4304         let l = cmp::min(self.len(), other.len());
4305
4306         // Slice to the loop iteration range to enable bound check
4307         // elimination in the compiler
4308         let lhs = &self[..l];
4309         let rhs = &other[..l];
4310
4311         for i in 0..l {
4312             match lhs[i].cmp(&rhs[i]) {
4313                 Ordering::Equal => (),
4314                 non_eq => return non_eq,
4315             }
4316         }
4317
4318         self.len().cmp(&other.len())
4319     }
4320 }
4321
4322 // memcmp compares a sequence of unsigned bytes lexicographically.
4323 // this matches the order we want for [u8], but no others (not even [i8]).
4324 impl SliceOrd<u8> for [u8] {
4325     #[inline]
4326     fn compare(&self, other: &[u8]) -> Ordering {
4327         let order = unsafe {
4328             memcmp(self.as_ptr(), other.as_ptr(),
4329                    cmp::min(self.len(), other.len()))
4330         };
4331         if order == 0 {
4332             self.len().cmp(&other.len())
4333         } else if order < 0 {
4334             Less
4335         } else {
4336             Greater
4337         }
4338     }
4339 }
4340
4341 #[doc(hidden)]
4342 /// Trait implemented for types that can be compared for equality using
4343 /// their bytewise representation
4344 trait BytewiseEquality { }
4345
4346 macro_rules! impl_marker_for {
4347     ($traitname:ident, $($ty:ty)*) => {
4348         $(
4349             impl $traitname for $ty { }
4350         )*
4351     }
4352 }
4353
4354 impl_marker_for!(BytewiseEquality,
4355                  u8 i8 u16 i16 u32 i32 u64 i64 usize isize char bool);
4356
4357 #[doc(hidden)]
4358 unsafe impl<'a, T> TrustedRandomAccess for Iter<'a, T> {
4359     unsafe fn get_unchecked(&mut self, i: usize) -> &'a T {
4360         &*self.ptr.add(i)
4361     }
4362     fn may_have_side_effect() -> bool { false }
4363 }
4364
4365 #[doc(hidden)]
4366 unsafe impl<'a, T> TrustedRandomAccess for IterMut<'a, T> {
4367     unsafe fn get_unchecked(&mut self, i: usize) -> &'a mut T {
4368         &mut *self.ptr.add(i)
4369     }
4370     fn may_have_side_effect() -> bool { false }
4371 }
4372
4373 trait SliceContains: Sized {
4374     fn slice_contains(&self, x: &[Self]) -> bool;
4375 }
4376
4377 impl<T> SliceContains for T where T: PartialEq {
4378     default fn slice_contains(&self, x: &[Self]) -> bool {
4379         x.iter().any(|y| *y == *self)
4380     }
4381 }
4382
4383 impl SliceContains for u8 {
4384     fn slice_contains(&self, x: &[Self]) -> bool {
4385         memchr::memchr(*self, x).is_some()
4386     }
4387 }
4388
4389 impl SliceContains for i8 {
4390     fn slice_contains(&self, x: &[Self]) -> bool {
4391         let byte = *self as u8;
4392         let bytes: &[u8] = unsafe { from_raw_parts(x.as_ptr() as *const u8, x.len()) };
4393         memchr::memchr(byte, bytes).is_some()
4394     }
4395 }