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