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