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