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