]> git.lizzy.rs Git - rust.git/blob - src/libcore/slice/mod.rs
Auto merge of #50339 - nnethercote:lazy-Printer-buf, r=michaelwoerister
[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 /// A helper trait used for indexing operations.
2266 #[unstable(feature = "slice_get_slice", issue = "35729")]
2267 #[rustc_on_unimplemented = "slice indices are of type `usize` or ranges of `usize`"]
2268 pub trait SliceIndex<T: ?Sized> {
2269     /// The output type returned by methods.
2270     type Output: ?Sized;
2271
2272     /// Returns a shared reference to the output at this location, if in
2273     /// bounds.
2274     fn get(self, slice: &T) -> Option<&Self::Output>;
2275
2276     /// Returns a mutable reference to the output at this location, if in
2277     /// bounds.
2278     fn get_mut(self, slice: &mut T) -> Option<&mut Self::Output>;
2279
2280     /// Returns a shared reference to the output at this location, without
2281     /// performing any bounds checking.
2282     unsafe fn get_unchecked(self, slice: &T) -> &Self::Output;
2283
2284     /// Returns a mutable reference to the output at this location, without
2285     /// performing any bounds checking.
2286     unsafe fn get_unchecked_mut(self, slice: &mut T) -> &mut Self::Output;
2287
2288     /// Returns a shared reference to the output at this location, panicking
2289     /// if out of bounds.
2290     fn index(self, slice: &T) -> &Self::Output;
2291
2292     /// Returns a mutable reference to the output at this location, panicking
2293     /// if out of bounds.
2294     fn index_mut(self, slice: &mut T) -> &mut Self::Output;
2295 }
2296
2297 #[stable(feature = "slice-get-slice-impls", since = "1.15.0")]
2298 impl<T> SliceIndex<[T]> for usize {
2299     type Output = T;
2300
2301     #[inline]
2302     fn get(self, slice: &[T]) -> Option<&T> {
2303         if self < slice.len() {
2304             unsafe {
2305                 Some(self.get_unchecked(slice))
2306             }
2307         } else {
2308             None
2309         }
2310     }
2311
2312     #[inline]
2313     fn get_mut(self, slice: &mut [T]) -> Option<&mut T> {
2314         if self < slice.len() {
2315             unsafe {
2316                 Some(self.get_unchecked_mut(slice))
2317             }
2318         } else {
2319             None
2320         }
2321     }
2322
2323     #[inline]
2324     unsafe fn get_unchecked(self, slice: &[T]) -> &T {
2325         &*slice.as_ptr().offset(self as isize)
2326     }
2327
2328     #[inline]
2329     unsafe fn get_unchecked_mut(self, slice: &mut [T]) -> &mut T {
2330         &mut *slice.as_mut_ptr().offset(self as isize)
2331     }
2332
2333     #[inline]
2334     fn index(self, slice: &[T]) -> &T {
2335         // NB: use intrinsic indexing
2336         &(*slice)[self]
2337     }
2338
2339     #[inline]
2340     fn index_mut(self, slice: &mut [T]) -> &mut T {
2341         // NB: use intrinsic indexing
2342         &mut (*slice)[self]
2343     }
2344 }
2345
2346 #[stable(feature = "slice-get-slice-impls", since = "1.15.0")]
2347 impl<T> SliceIndex<[T]> for  ops::Range<usize> {
2348     type Output = [T];
2349
2350     #[inline]
2351     fn get(self, slice: &[T]) -> Option<&[T]> {
2352         if self.start > self.end || self.end > slice.len() {
2353             None
2354         } else {
2355             unsafe {
2356                 Some(self.get_unchecked(slice))
2357             }
2358         }
2359     }
2360
2361     #[inline]
2362     fn get_mut(self, slice: &mut [T]) -> Option<&mut [T]> {
2363         if self.start > self.end || self.end > slice.len() {
2364             None
2365         } else {
2366             unsafe {
2367                 Some(self.get_unchecked_mut(slice))
2368             }
2369         }
2370     }
2371
2372     #[inline]
2373     unsafe fn get_unchecked(self, slice: &[T]) -> &[T] {
2374         from_raw_parts(slice.as_ptr().offset(self.start as isize), self.end - self.start)
2375     }
2376
2377     #[inline]
2378     unsafe fn get_unchecked_mut(self, slice: &mut [T]) -> &mut [T] {
2379         from_raw_parts_mut(slice.as_mut_ptr().offset(self.start as isize), self.end - self.start)
2380     }
2381
2382     #[inline]
2383     fn index(self, slice: &[T]) -> &[T] {
2384         if self.start > self.end {
2385             slice_index_order_fail(self.start, self.end);
2386         } else if self.end > slice.len() {
2387             slice_index_len_fail(self.end, slice.len());
2388         }
2389         unsafe {
2390             self.get_unchecked(slice)
2391         }
2392     }
2393
2394     #[inline]
2395     fn index_mut(self, slice: &mut [T]) -> &mut [T] {
2396         if self.start > self.end {
2397             slice_index_order_fail(self.start, self.end);
2398         } else if self.end > slice.len() {
2399             slice_index_len_fail(self.end, slice.len());
2400         }
2401         unsafe {
2402             self.get_unchecked_mut(slice)
2403         }
2404     }
2405 }
2406
2407 #[stable(feature = "slice-get-slice-impls", since = "1.15.0")]
2408 impl<T> SliceIndex<[T]> for ops::RangeTo<usize> {
2409     type Output = [T];
2410
2411     #[inline]
2412     fn get(self, slice: &[T]) -> Option<&[T]> {
2413         (0..self.end).get(slice)
2414     }
2415
2416     #[inline]
2417     fn get_mut(self, slice: &mut [T]) -> Option<&mut [T]> {
2418         (0..self.end).get_mut(slice)
2419     }
2420
2421     #[inline]
2422     unsafe fn get_unchecked(self, slice: &[T]) -> &[T] {
2423         (0..self.end).get_unchecked(slice)
2424     }
2425
2426     #[inline]
2427     unsafe fn get_unchecked_mut(self, slice: &mut [T]) -> &mut [T] {
2428         (0..self.end).get_unchecked_mut(slice)
2429     }
2430
2431     #[inline]
2432     fn index(self, slice: &[T]) -> &[T] {
2433         (0..self.end).index(slice)
2434     }
2435
2436     #[inline]
2437     fn index_mut(self, slice: &mut [T]) -> &mut [T] {
2438         (0..self.end).index_mut(slice)
2439     }
2440 }
2441
2442 #[stable(feature = "slice-get-slice-impls", since = "1.15.0")]
2443 impl<T> SliceIndex<[T]> for ops::RangeFrom<usize> {
2444     type Output = [T];
2445
2446     #[inline]
2447     fn get(self, slice: &[T]) -> Option<&[T]> {
2448         (self.start..slice.len()).get(slice)
2449     }
2450
2451     #[inline]
2452     fn get_mut(self, slice: &mut [T]) -> Option<&mut [T]> {
2453         (self.start..slice.len()).get_mut(slice)
2454     }
2455
2456     #[inline]
2457     unsafe fn get_unchecked(self, slice: &[T]) -> &[T] {
2458         (self.start..slice.len()).get_unchecked(slice)
2459     }
2460
2461     #[inline]
2462     unsafe fn get_unchecked_mut(self, slice: &mut [T]) -> &mut [T] {
2463         (self.start..slice.len()).get_unchecked_mut(slice)
2464     }
2465
2466     #[inline]
2467     fn index(self, slice: &[T]) -> &[T] {
2468         (self.start..slice.len()).index(slice)
2469     }
2470
2471     #[inline]
2472     fn index_mut(self, slice: &mut [T]) -> &mut [T] {
2473         (self.start..slice.len()).index_mut(slice)
2474     }
2475 }
2476
2477 #[stable(feature = "slice-get-slice-impls", since = "1.15.0")]
2478 impl<T> SliceIndex<[T]> for ops::RangeFull {
2479     type Output = [T];
2480
2481     #[inline]
2482     fn get(self, slice: &[T]) -> Option<&[T]> {
2483         Some(slice)
2484     }
2485
2486     #[inline]
2487     fn get_mut(self, slice: &mut [T]) -> Option<&mut [T]> {
2488         Some(slice)
2489     }
2490
2491     #[inline]
2492     unsafe fn get_unchecked(self, slice: &[T]) -> &[T] {
2493         slice
2494     }
2495
2496     #[inline]
2497     unsafe fn get_unchecked_mut(self, slice: &mut [T]) -> &mut [T] {
2498         slice
2499     }
2500
2501     #[inline]
2502     fn index(self, slice: &[T]) -> &[T] {
2503         slice
2504     }
2505
2506     #[inline]
2507     fn index_mut(self, slice: &mut [T]) -> &mut [T] {
2508         slice
2509     }
2510 }
2511
2512
2513 #[stable(feature = "inclusive_range", since = "1.26.0")]
2514 impl<T> SliceIndex<[T]> for ops::RangeInclusive<usize> {
2515     type Output = [T];
2516
2517     #[inline]
2518     fn get(self, slice: &[T]) -> Option<&[T]> {
2519         if self.end == usize::max_value() { None }
2520         else { (self.start..self.end + 1).get(slice) }
2521     }
2522
2523     #[inline]
2524     fn get_mut(self, slice: &mut [T]) -> Option<&mut [T]> {
2525         if self.end == usize::max_value() { None }
2526         else { (self.start..self.end + 1).get_mut(slice) }
2527     }
2528
2529     #[inline]
2530     unsafe fn get_unchecked(self, slice: &[T]) -> &[T] {
2531         (self.start..self.end + 1).get_unchecked(slice)
2532     }
2533
2534     #[inline]
2535     unsafe fn get_unchecked_mut(self, slice: &mut [T]) -> &mut [T] {
2536         (self.start..self.end + 1).get_unchecked_mut(slice)
2537     }
2538
2539     #[inline]
2540     fn index(self, slice: &[T]) -> &[T] {
2541         assert!(self.end != usize::max_value(),
2542             "attempted to index slice up to maximum usize");
2543         (self.start..self.end + 1).index(slice)
2544     }
2545
2546     #[inline]
2547     fn index_mut(self, slice: &mut [T]) -> &mut [T] {
2548         assert!(self.end != usize::max_value(),
2549             "attempted to index slice up to maximum usize");
2550         (self.start..self.end + 1).index_mut(slice)
2551     }
2552 }
2553
2554 #[stable(feature = "inclusive_range", since = "1.26.0")]
2555 impl<T> SliceIndex<[T]> for ops::RangeToInclusive<usize> {
2556     type Output = [T];
2557
2558     #[inline]
2559     fn get(self, slice: &[T]) -> Option<&[T]> {
2560         (0..=self.end).get(slice)
2561     }
2562
2563     #[inline]
2564     fn get_mut(self, slice: &mut [T]) -> Option<&mut [T]> {
2565         (0..=self.end).get_mut(slice)
2566     }
2567
2568     #[inline]
2569     unsafe fn get_unchecked(self, slice: &[T]) -> &[T] {
2570         (0..=self.end).get_unchecked(slice)
2571     }
2572
2573     #[inline]
2574     unsafe fn get_unchecked_mut(self, slice: &mut [T]) -> &mut [T] {
2575         (0..=self.end).get_unchecked_mut(slice)
2576     }
2577
2578     #[inline]
2579     fn index(self, slice: &[T]) -> &[T] {
2580         (0..=self.end).index(slice)
2581     }
2582
2583     #[inline]
2584     fn index_mut(self, slice: &mut [T]) -> &mut [T] {
2585         (0..=self.end).index_mut(slice)
2586     }
2587 }
2588
2589 ////////////////////////////////////////////////////////////////////////////////
2590 // Common traits
2591 ////////////////////////////////////////////////////////////////////////////////
2592
2593 #[stable(feature = "rust1", since = "1.0.0")]
2594 impl<'a, T> Default for &'a [T] {
2595     /// Creates an empty slice.
2596     fn default() -> &'a [T] { &[] }
2597 }
2598
2599 #[stable(feature = "mut_slice_default", since = "1.5.0")]
2600 impl<'a, T> Default for &'a mut [T] {
2601     /// Creates a mutable empty slice.
2602     fn default() -> &'a mut [T] { &mut [] }
2603 }
2604
2605 //
2606 // Iterators
2607 //
2608
2609 #[stable(feature = "rust1", since = "1.0.0")]
2610 impl<'a, T> IntoIterator for &'a [T] {
2611     type Item = &'a T;
2612     type IntoIter = Iter<'a, T>;
2613
2614     fn into_iter(self) -> Iter<'a, T> {
2615         self.iter()
2616     }
2617 }
2618
2619 #[stable(feature = "rust1", since = "1.0.0")]
2620 impl<'a, T> IntoIterator for &'a mut [T] {
2621     type Item = &'a mut T;
2622     type IntoIter = IterMut<'a, T>;
2623
2624     fn into_iter(self) -> IterMut<'a, T> {
2625         self.iter_mut()
2626     }
2627 }
2628
2629 #[inline]
2630 fn size_from_ptr<T>(_: *const T) -> usize {
2631     mem::size_of::<T>()
2632 }
2633
2634 // The shared definition of the `Iter` and `IterMut` iterators
2635 macro_rules! iterator {
2636     (struct $name:ident -> $ptr:ty, $elem:ty, $mkref:ident) => {
2637         #[stable(feature = "rust1", since = "1.0.0")]
2638         impl<'a, T> Iterator for $name<'a, T> {
2639             type Item = $elem;
2640
2641             #[inline]
2642             fn next(&mut self) -> Option<$elem> {
2643                 // could be implemented with slices, but this avoids bounds checks
2644                 unsafe {
2645                     if mem::size_of::<T>() != 0 {
2646                         assume(!self.ptr.is_null());
2647                         assume(!self.end.is_null());
2648                     }
2649                     if self.ptr == self.end {
2650                         None
2651                     } else {
2652                         Some($mkref!(self.ptr.post_inc()))
2653                     }
2654                 }
2655             }
2656
2657             #[inline]
2658             fn size_hint(&self) -> (usize, Option<usize>) {
2659                 let exact = unsafe { ptrdistance(self.ptr, self.end) };
2660                 (exact, Some(exact))
2661             }
2662
2663             #[inline]
2664             fn count(self) -> usize {
2665                 self.len()
2666             }
2667
2668             #[inline]
2669             fn nth(&mut self, n: usize) -> Option<$elem> {
2670                 // Call helper method. Can't put the definition here because mut versus const.
2671                 self.iter_nth(n)
2672             }
2673
2674             #[inline]
2675             fn last(mut self) -> Option<$elem> {
2676                 self.next_back()
2677             }
2678
2679             #[inline]
2680             fn try_fold<B, F, R>(&mut self, init: B, mut f: F) -> R where
2681                 Self: Sized, F: FnMut(B, Self::Item) -> R, R: Try<Ok=B>
2682             {
2683                 // manual unrolling is needed when there are conditional exits from the loop
2684                 let mut accum = init;
2685                 unsafe {
2686                     while ptrdistance(self.ptr, self.end) >= 4 {
2687                         accum = f(accum, $mkref!(self.ptr.post_inc()))?;
2688                         accum = f(accum, $mkref!(self.ptr.post_inc()))?;
2689                         accum = f(accum, $mkref!(self.ptr.post_inc()))?;
2690                         accum = f(accum, $mkref!(self.ptr.post_inc()))?;
2691                     }
2692                     while self.ptr != self.end {
2693                         accum = f(accum, $mkref!(self.ptr.post_inc()))?;
2694                     }
2695                 }
2696                 Try::from_ok(accum)
2697             }
2698
2699             #[inline]
2700             fn fold<Acc, Fold>(mut self, init: Acc, mut f: Fold) -> Acc
2701                 where Fold: FnMut(Acc, Self::Item) -> Acc,
2702             {
2703                 // Let LLVM unroll this, rather than using the default
2704                 // impl that would force the manual unrolling above
2705                 let mut accum = init;
2706                 while let Some(x) = self.next() {
2707                     accum = f(accum, x);
2708                 }
2709                 accum
2710             }
2711
2712             #[inline]
2713             #[rustc_inherit_overflow_checks]
2714             fn position<P>(&mut self, mut predicate: P) -> Option<usize> where
2715                 Self: Sized,
2716                 P: FnMut(Self::Item) -> bool,
2717             {
2718                 // The addition might panic on overflow
2719                 // Use the len of the slice to hint optimizer to remove result index bounds check.
2720                 let n = make_slice!(self.ptr, self.end).len();
2721                 self.try_fold(0, move |i, x| {
2722                     if predicate(x) { Err(i) }
2723                     else { Ok(i + 1) }
2724                 }).err()
2725                     .map(|i| {
2726                         unsafe { assume(i < n) };
2727                         i
2728                     })
2729             }
2730
2731             #[inline]
2732             fn rposition<P>(&mut self, mut predicate: P) -> Option<usize> where
2733                 P: FnMut(Self::Item) -> bool,
2734                 Self: Sized + ExactSizeIterator + DoubleEndedIterator
2735             {
2736                 // No need for an overflow check here, because `ExactSizeIterator`
2737                 // implies that the number of elements fits into a `usize`.
2738                 // Use the len of the slice to hint optimizer to remove result index bounds check.
2739                 let n = make_slice!(self.ptr, self.end).len();
2740                 self.try_rfold(n, move |i, x| {
2741                     let i = i - 1;
2742                     if predicate(x) { Err(i) }
2743                     else { Ok(i) }
2744                 }).err()
2745                     .map(|i| {
2746                         unsafe { assume(i < n) };
2747                         i
2748                     })
2749             }
2750         }
2751
2752         #[stable(feature = "rust1", since = "1.0.0")]
2753         impl<'a, T> DoubleEndedIterator for $name<'a, T> {
2754             #[inline]
2755             fn next_back(&mut self) -> Option<$elem> {
2756                 // could be implemented with slices, but this avoids bounds checks
2757                 unsafe {
2758                     if mem::size_of::<T>() != 0 {
2759                         assume(!self.ptr.is_null());
2760                         assume(!self.end.is_null());
2761                     }
2762                     if self.end == self.ptr {
2763                         None
2764                     } else {
2765                         Some($mkref!(self.end.pre_dec()))
2766                     }
2767                 }
2768             }
2769
2770             #[inline]
2771             fn try_rfold<B, F, R>(&mut self, init: B, mut f: F) -> R where
2772                 Self: Sized, F: FnMut(B, Self::Item) -> R, R: Try<Ok=B>
2773             {
2774                 // manual unrolling is needed when there are conditional exits from the loop
2775                 let mut accum = init;
2776                 unsafe {
2777                     while ptrdistance(self.ptr, self.end) >= 4 {
2778                         accum = f(accum, $mkref!(self.end.pre_dec()))?;
2779                         accum = f(accum, $mkref!(self.end.pre_dec()))?;
2780                         accum = f(accum, $mkref!(self.end.pre_dec()))?;
2781                         accum = f(accum, $mkref!(self.end.pre_dec()))?;
2782                     }
2783                     while self.ptr != self.end {
2784                         accum = f(accum, $mkref!(self.end.pre_dec()))?;
2785                     }
2786                 }
2787                 Try::from_ok(accum)
2788             }
2789
2790             #[inline]
2791             fn rfold<Acc, Fold>(mut self, init: Acc, mut f: Fold) -> Acc
2792                 where Fold: FnMut(Acc, Self::Item) -> Acc,
2793             {
2794                 // Let LLVM unroll this, rather than using the default
2795                 // impl that would force the manual unrolling above
2796                 let mut accum = init;
2797                 while let Some(x) = self.next_back() {
2798                     accum = f(accum, x);
2799                 }
2800                 accum
2801             }
2802         }
2803     }
2804 }
2805
2806 macro_rules! make_slice {
2807     ($start: expr, $end: expr) => {{
2808         let start = $start;
2809         let diff = ($end as usize).wrapping_sub(start as usize);
2810         if size_from_ptr(start) == 0 {
2811             // use a non-null pointer value
2812             unsafe { from_raw_parts(1 as *const _, diff) }
2813         } else {
2814             let len = diff / size_from_ptr(start);
2815             unsafe { from_raw_parts(start, len) }
2816         }
2817     }}
2818 }
2819
2820 macro_rules! make_mut_slice {
2821     ($start: expr, $end: expr) => {{
2822         let start = $start;
2823         let diff = ($end as usize).wrapping_sub(start as usize);
2824         if size_from_ptr(start) == 0 {
2825             // use a non-null pointer value
2826             unsafe { from_raw_parts_mut(1 as *mut _, diff) }
2827         } else {
2828             let len = diff / size_from_ptr(start);
2829             unsafe { from_raw_parts_mut(start, len) }
2830         }
2831     }}
2832 }
2833
2834 /// Immutable slice iterator
2835 ///
2836 /// This struct is created by the [`iter`] method on [slices].
2837 ///
2838 /// # Examples
2839 ///
2840 /// Basic usage:
2841 ///
2842 /// ```
2843 /// // First, we declare a type which has `iter` method to get the `Iter` struct (&[usize here]):
2844 /// let slice = &[1, 2, 3];
2845 ///
2846 /// // Then, we iterate over it:
2847 /// for element in slice.iter() {
2848 ///     println!("{}", element);
2849 /// }
2850 /// ```
2851 ///
2852 /// [`iter`]: ../../std/primitive.slice.html#method.iter
2853 /// [slices]: ../../std/primitive.slice.html
2854 #[stable(feature = "rust1", since = "1.0.0")]
2855 pub struct Iter<'a, T: 'a> {
2856     ptr: *const T,
2857     end: *const T,
2858     _marker: marker::PhantomData<&'a T>,
2859 }
2860
2861 #[stable(feature = "core_impl_debug", since = "1.9.0")]
2862 impl<'a, T: 'a + fmt::Debug> fmt::Debug for Iter<'a, T> {
2863     fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
2864         f.debug_tuple("Iter")
2865             .field(&self.as_slice())
2866             .finish()
2867     }
2868 }
2869
2870 #[stable(feature = "rust1", since = "1.0.0")]
2871 unsafe impl<'a, T: Sync> Sync for Iter<'a, T> {}
2872 #[stable(feature = "rust1", since = "1.0.0")]
2873 unsafe impl<'a, T: Sync> Send for Iter<'a, T> {}
2874
2875 impl<'a, T> Iter<'a, T> {
2876     /// View the underlying data as a subslice of the original data.
2877     ///
2878     /// This has the same lifetime as the original slice, and so the
2879     /// iterator can continue to be used while this exists.
2880     ///
2881     /// # Examples
2882     ///
2883     /// Basic usage:
2884     ///
2885     /// ```
2886     /// // First, we declare a type which has the `iter` method to get the `Iter`
2887     /// // struct (&[usize here]):
2888     /// let slice = &[1, 2, 3];
2889     ///
2890     /// // Then, we get the iterator:
2891     /// let mut iter = slice.iter();
2892     /// // So if we print what `as_slice` method returns here, we have "[1, 2, 3]":
2893     /// println!("{:?}", iter.as_slice());
2894     ///
2895     /// // Next, we move to the second element of the slice:
2896     /// iter.next();
2897     /// // Now `as_slice` returns "[2, 3]":
2898     /// println!("{:?}", iter.as_slice());
2899     /// ```
2900     #[stable(feature = "iter_to_slice", since = "1.4.0")]
2901     pub fn as_slice(&self) -> &'a [T] {
2902         make_slice!(self.ptr, self.end)
2903     }
2904
2905     // Helper function for Iter::nth
2906     fn iter_nth(&mut self, n: usize) -> Option<&'a T> {
2907         match self.as_slice().get(n) {
2908             Some(elem_ref) => unsafe {
2909                 self.ptr = slice_offset!(self.ptr, (n as isize).wrapping_add(1));
2910                 Some(elem_ref)
2911             },
2912             None => {
2913                 self.ptr = self.end;
2914                 None
2915             }
2916         }
2917     }
2918 }
2919
2920 iterator!{struct Iter -> *const T, &'a T, make_ref}
2921
2922 #[stable(feature = "rust1", since = "1.0.0")]
2923 impl<'a, T> ExactSizeIterator for Iter<'a, T> {
2924     fn is_empty(&self) -> bool {
2925         self.ptr == self.end
2926     }
2927 }
2928
2929 #[stable(feature = "fused", since = "1.26.0")]
2930 impl<'a, T> FusedIterator for Iter<'a, T> {}
2931
2932 #[unstable(feature = "trusted_len", issue = "37572")]
2933 unsafe impl<'a, T> TrustedLen for Iter<'a, T> {}
2934
2935 #[stable(feature = "rust1", since = "1.0.0")]
2936 impl<'a, T> Clone for Iter<'a, T> {
2937     fn clone(&self) -> Iter<'a, T> { Iter { ptr: self.ptr, end: self.end, _marker: self._marker } }
2938 }
2939
2940 #[stable(feature = "slice_iter_as_ref", since = "1.13.0")]
2941 impl<'a, T> AsRef<[T]> for Iter<'a, T> {
2942     fn as_ref(&self) -> &[T] {
2943         self.as_slice()
2944     }
2945 }
2946
2947 /// Mutable slice iterator.
2948 ///
2949 /// This struct is created by the [`iter_mut`] method on [slices].
2950 ///
2951 /// # Examples
2952 ///
2953 /// Basic usage:
2954 ///
2955 /// ```
2956 /// // First, we declare a type which has `iter_mut` method to get the `IterMut`
2957 /// // struct (&[usize here]):
2958 /// let mut slice = &mut [1, 2, 3];
2959 ///
2960 /// // Then, we iterate over it and increment each element value:
2961 /// for element in slice.iter_mut() {
2962 ///     *element += 1;
2963 /// }
2964 ///
2965 /// // We now have "[2, 3, 4]":
2966 /// println!("{:?}", slice);
2967 /// ```
2968 ///
2969 /// [`iter_mut`]: ../../std/primitive.slice.html#method.iter_mut
2970 /// [slices]: ../../std/primitive.slice.html
2971 #[stable(feature = "rust1", since = "1.0.0")]
2972 pub struct IterMut<'a, T: 'a> {
2973     ptr: *mut T,
2974     end: *mut T,
2975     _marker: marker::PhantomData<&'a mut T>,
2976 }
2977
2978 #[stable(feature = "core_impl_debug", since = "1.9.0")]
2979 impl<'a, T: 'a + fmt::Debug> fmt::Debug for IterMut<'a, T> {
2980     fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
2981         f.debug_tuple("IterMut")
2982             .field(&make_slice!(self.ptr, self.end))
2983             .finish()
2984     }
2985 }
2986
2987 #[stable(feature = "rust1", since = "1.0.0")]
2988 unsafe impl<'a, T: Sync> Sync for IterMut<'a, T> {}
2989 #[stable(feature = "rust1", since = "1.0.0")]
2990 unsafe impl<'a, T: Send> Send for IterMut<'a, T> {}
2991
2992 impl<'a, T> IterMut<'a, T> {
2993     /// View the underlying data as a subslice of the original data.
2994     ///
2995     /// To avoid creating `&mut` references that alias, this is forced
2996     /// to consume the iterator. Consider using the `Slice` and
2997     /// `SliceMut` implementations for obtaining slices with more
2998     /// restricted lifetimes that do not consume the iterator.
2999     ///
3000     /// # Examples
3001     ///
3002     /// Basic usage:
3003     ///
3004     /// ```
3005     /// // First, we declare a type which has `iter_mut` method to get the `IterMut`
3006     /// // struct (&[usize here]):
3007     /// let mut slice = &mut [1, 2, 3];
3008     ///
3009     /// {
3010     ///     // Then, we get the iterator:
3011     ///     let mut iter = slice.iter_mut();
3012     ///     // We move to next element:
3013     ///     iter.next();
3014     ///     // So if we print what `into_slice` method returns here, we have "[2, 3]":
3015     ///     println!("{:?}", iter.into_slice());
3016     /// }
3017     ///
3018     /// // Now let's modify a value of the slice:
3019     /// {
3020     ///     // First we get back the iterator:
3021     ///     let mut iter = slice.iter_mut();
3022     ///     // We change the value of the first element of the slice returned by the `next` method:
3023     ///     *iter.next().unwrap() += 1;
3024     /// }
3025     /// // Now slice is "[2, 2, 3]":
3026     /// println!("{:?}", slice);
3027     /// ```
3028     #[stable(feature = "iter_to_slice", since = "1.4.0")]
3029     pub fn into_slice(self) -> &'a mut [T] {
3030         make_mut_slice!(self.ptr, self.end)
3031     }
3032
3033     // Helper function for IterMut::nth
3034     fn iter_nth(&mut self, n: usize) -> Option<&'a mut T> {
3035         match make_mut_slice!(self.ptr, self.end).get_mut(n) {
3036             Some(elem_ref) => unsafe {
3037                 self.ptr = slice_offset!(self.ptr, (n as isize).wrapping_add(1));
3038                 Some(elem_ref)
3039             },
3040             None => {
3041                 self.ptr = self.end;
3042                 None
3043             }
3044         }
3045     }
3046 }
3047
3048 iterator!{struct IterMut -> *mut T, &'a mut T, make_ref_mut}
3049
3050 #[stable(feature = "rust1", since = "1.0.0")]
3051 impl<'a, T> ExactSizeIterator for IterMut<'a, T> {
3052     fn is_empty(&self) -> bool {
3053         self.ptr == self.end
3054     }
3055 }
3056
3057 #[stable(feature = "fused", since = "1.26.0")]
3058 impl<'a, T> FusedIterator for IterMut<'a, T> {}
3059
3060 #[unstable(feature = "trusted_len", issue = "37572")]
3061 unsafe impl<'a, T> TrustedLen for IterMut<'a, T> {}
3062
3063
3064 // Return the number of elements of `T` from `start` to `end`.
3065 // Return the arithmetic difference if `T` is zero size.
3066 #[inline(always)]
3067 unsafe fn ptrdistance<T>(start: *const T, end: *const T) -> usize {
3068     if mem::size_of::<T>() == 0 {
3069         (end as usize).wrapping_sub(start as usize)
3070     } else {
3071         end.offset_from(start) as usize
3072     }
3073 }
3074
3075 // Extension methods for raw pointers, used by the iterators
3076 trait PointerExt : Copy {
3077     unsafe fn slice_offset(self, i: isize) -> Self;
3078
3079     /// Increments `self` by 1, but returns the old value.
3080     #[inline(always)]
3081     unsafe fn post_inc(&mut self) -> Self {
3082         let current = *self;
3083         *self = self.slice_offset(1);
3084         current
3085     }
3086
3087     /// Decrements `self` by 1, and returns the new value.
3088     #[inline(always)]
3089     unsafe fn pre_dec(&mut self) -> Self {
3090         *self = self.slice_offset(-1);
3091         *self
3092     }
3093 }
3094
3095 impl<T> PointerExt for *const T {
3096     #[inline(always)]
3097     unsafe fn slice_offset(self, i: isize) -> Self {
3098         slice_offset!(self, i)
3099     }
3100 }
3101
3102 impl<T> PointerExt for *mut T {
3103     #[inline(always)]
3104     unsafe fn slice_offset(self, i: isize) -> Self {
3105         slice_offset!(self, i)
3106     }
3107 }
3108
3109 /// An internal abstraction over the splitting iterators, so that
3110 /// splitn, splitn_mut etc can be implemented once.
3111 #[doc(hidden)]
3112 trait SplitIter: DoubleEndedIterator {
3113     /// Marks the underlying iterator as complete, extracting the remaining
3114     /// portion of the slice.
3115     fn finish(&mut self) -> Option<Self::Item>;
3116 }
3117
3118 /// An iterator over subslices separated by elements that match a predicate
3119 /// function.
3120 ///
3121 /// This struct is created by the [`split`] method on [slices].
3122 ///
3123 /// [`split`]: ../../std/primitive.slice.html#method.split
3124 /// [slices]: ../../std/primitive.slice.html
3125 #[stable(feature = "rust1", since = "1.0.0")]
3126 pub struct Split<'a, T:'a, P> where P: FnMut(&T) -> bool {
3127     v: &'a [T],
3128     pred: P,
3129     finished: bool
3130 }
3131
3132 #[stable(feature = "core_impl_debug", since = "1.9.0")]
3133 impl<'a, T: 'a + fmt::Debug, P> fmt::Debug for Split<'a, T, P> where P: FnMut(&T) -> bool {
3134     fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
3135         f.debug_struct("Split")
3136             .field("v", &self.v)
3137             .field("finished", &self.finished)
3138             .finish()
3139     }
3140 }
3141
3142 // FIXME(#26925) Remove in favor of `#[derive(Clone)]`
3143 #[stable(feature = "rust1", since = "1.0.0")]
3144 impl<'a, T, P> Clone for Split<'a, T, P> where P: Clone + FnMut(&T) -> bool {
3145     fn clone(&self) -> Split<'a, T, P> {
3146         Split {
3147             v: self.v,
3148             pred: self.pred.clone(),
3149             finished: self.finished,
3150         }
3151     }
3152 }
3153
3154 #[stable(feature = "rust1", since = "1.0.0")]
3155 impl<'a, T, P> Iterator for Split<'a, T, P> where P: FnMut(&T) -> bool {
3156     type Item = &'a [T];
3157
3158     #[inline]
3159     fn next(&mut self) -> Option<&'a [T]> {
3160         if self.finished { return None; }
3161
3162         match self.v.iter().position(|x| (self.pred)(x)) {
3163             None => self.finish(),
3164             Some(idx) => {
3165                 let ret = Some(&self.v[..idx]);
3166                 self.v = &self.v[idx + 1..];
3167                 ret
3168             }
3169         }
3170     }
3171
3172     #[inline]
3173     fn size_hint(&self) -> (usize, Option<usize>) {
3174         if self.finished {
3175             (0, Some(0))
3176         } else {
3177             (1, Some(self.v.len() + 1))
3178         }
3179     }
3180 }
3181
3182 #[stable(feature = "rust1", since = "1.0.0")]
3183 impl<'a, T, P> DoubleEndedIterator for Split<'a, T, P> where P: FnMut(&T) -> bool {
3184     #[inline]
3185     fn next_back(&mut self) -> Option<&'a [T]> {
3186         if self.finished { return None; }
3187
3188         match self.v.iter().rposition(|x| (self.pred)(x)) {
3189             None => self.finish(),
3190             Some(idx) => {
3191                 let ret = Some(&self.v[idx + 1..]);
3192                 self.v = &self.v[..idx];
3193                 ret
3194             }
3195         }
3196     }
3197 }
3198
3199 impl<'a, T, P> SplitIter for Split<'a, T, P> where P: FnMut(&T) -> bool {
3200     #[inline]
3201     fn finish(&mut self) -> Option<&'a [T]> {
3202         if self.finished { None } else { self.finished = true; Some(self.v) }
3203     }
3204 }
3205
3206 #[stable(feature = "fused", since = "1.26.0")]
3207 impl<'a, T, P> FusedIterator for Split<'a, T, P> where P: FnMut(&T) -> bool {}
3208
3209 /// An iterator over the subslices of the vector which are separated
3210 /// by elements that match `pred`.
3211 ///
3212 /// This struct is created by the [`split_mut`] method on [slices].
3213 ///
3214 /// [`split_mut`]: ../../std/primitive.slice.html#method.split_mut
3215 /// [slices]: ../../std/primitive.slice.html
3216 #[stable(feature = "rust1", since = "1.0.0")]
3217 pub struct SplitMut<'a, T:'a, P> where P: FnMut(&T) -> bool {
3218     v: &'a mut [T],
3219     pred: P,
3220     finished: bool
3221 }
3222
3223 #[stable(feature = "core_impl_debug", since = "1.9.0")]
3224 impl<'a, T: 'a + fmt::Debug, P> fmt::Debug for SplitMut<'a, T, P> where P: FnMut(&T) -> bool {
3225     fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
3226         f.debug_struct("SplitMut")
3227             .field("v", &self.v)
3228             .field("finished", &self.finished)
3229             .finish()
3230     }
3231 }
3232
3233 impl<'a, T, P> SplitIter for SplitMut<'a, T, P> where P: FnMut(&T) -> bool {
3234     #[inline]
3235     fn finish(&mut self) -> Option<&'a mut [T]> {
3236         if self.finished {
3237             None
3238         } else {
3239             self.finished = true;
3240             Some(mem::replace(&mut self.v, &mut []))
3241         }
3242     }
3243 }
3244
3245 #[stable(feature = "rust1", since = "1.0.0")]
3246 impl<'a, T, P> Iterator for SplitMut<'a, T, P> where P: FnMut(&T) -> bool {
3247     type Item = &'a mut [T];
3248
3249     #[inline]
3250     fn next(&mut self) -> Option<&'a mut [T]> {
3251         if self.finished { return None; }
3252
3253         let idx_opt = { // work around borrowck limitations
3254             let pred = &mut self.pred;
3255             self.v.iter().position(|x| (*pred)(x))
3256         };
3257         match idx_opt {
3258             None => self.finish(),
3259             Some(idx) => {
3260                 let tmp = mem::replace(&mut self.v, &mut []);
3261                 let (head, tail) = tmp.split_at_mut(idx);
3262                 self.v = &mut tail[1..];
3263                 Some(head)
3264             }
3265         }
3266     }
3267
3268     #[inline]
3269     fn size_hint(&self) -> (usize, Option<usize>) {
3270         if self.finished {
3271             (0, Some(0))
3272         } else {
3273             // if the predicate doesn't match anything, we yield one slice
3274             // if it matches every element, we yield len+1 empty slices.
3275             (1, Some(self.v.len() + 1))
3276         }
3277     }
3278 }
3279
3280 #[stable(feature = "rust1", since = "1.0.0")]
3281 impl<'a, T, P> DoubleEndedIterator for SplitMut<'a, T, P> where
3282     P: FnMut(&T) -> bool,
3283 {
3284     #[inline]
3285     fn next_back(&mut self) -> Option<&'a mut [T]> {
3286         if self.finished { return None; }
3287
3288         let idx_opt = { // work around borrowck limitations
3289             let pred = &mut self.pred;
3290             self.v.iter().rposition(|x| (*pred)(x))
3291         };
3292         match idx_opt {
3293             None => self.finish(),
3294             Some(idx) => {
3295                 let tmp = mem::replace(&mut self.v, &mut []);
3296                 let (head, tail) = tmp.split_at_mut(idx);
3297                 self.v = head;
3298                 Some(&mut tail[1..])
3299             }
3300         }
3301     }
3302 }
3303
3304 #[stable(feature = "fused", since = "1.26.0")]
3305 impl<'a, T, P> FusedIterator for SplitMut<'a, T, P> where P: FnMut(&T) -> bool {}
3306
3307 /// An iterator over subslices separated by elements that match a predicate
3308 /// function, starting from the end of the slice.
3309 ///
3310 /// This struct is created by the [`rsplit`] method on [slices].
3311 ///
3312 /// [`rsplit`]: ../../std/primitive.slice.html#method.rsplit
3313 /// [slices]: ../../std/primitive.slice.html
3314 #[stable(feature = "slice_rsplit", since = "1.27.0")]
3315 #[derive(Clone)] // Is this correct, or does it incorrectly require `T: Clone`?
3316 pub struct RSplit<'a, T:'a, P> where P: FnMut(&T) -> bool {
3317     inner: Split<'a, T, P>
3318 }
3319
3320 #[stable(feature = "slice_rsplit", since = "1.27.0")]
3321 impl<'a, T: 'a + fmt::Debug, P> fmt::Debug for RSplit<'a, T, P> where P: FnMut(&T) -> bool {
3322     fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
3323         f.debug_struct("RSplit")
3324             .field("v", &self.inner.v)
3325             .field("finished", &self.inner.finished)
3326             .finish()
3327     }
3328 }
3329
3330 #[stable(feature = "slice_rsplit", since = "1.27.0")]
3331 impl<'a, T, P> Iterator for RSplit<'a, T, P> where P: FnMut(&T) -> bool {
3332     type Item = &'a [T];
3333
3334     #[inline]
3335     fn next(&mut self) -> Option<&'a [T]> {
3336         self.inner.next_back()
3337     }
3338
3339     #[inline]
3340     fn size_hint(&self) -> (usize, Option<usize>) {
3341         self.inner.size_hint()
3342     }
3343 }
3344
3345 #[stable(feature = "slice_rsplit", since = "1.27.0")]
3346 impl<'a, T, P> DoubleEndedIterator for RSplit<'a, T, P> where P: FnMut(&T) -> bool {
3347     #[inline]
3348     fn next_back(&mut self) -> Option<&'a [T]> {
3349         self.inner.next()
3350     }
3351 }
3352
3353 #[stable(feature = "slice_rsplit", since = "1.27.0")]
3354 impl<'a, T, P> SplitIter for RSplit<'a, T, P> where P: FnMut(&T) -> bool {
3355     #[inline]
3356     fn finish(&mut self) -> Option<&'a [T]> {
3357         self.inner.finish()
3358     }
3359 }
3360
3361 #[stable(feature = "slice_rsplit", since = "1.27.0")]
3362 impl<'a, T, P> FusedIterator for RSplit<'a, T, P> where P: FnMut(&T) -> bool {}
3363
3364 /// An iterator over the subslices of the vector which are separated
3365 /// by elements that match `pred`, starting from the end of the slice.
3366 ///
3367 /// This struct is created by the [`rsplit_mut`] method on [slices].
3368 ///
3369 /// [`rsplit_mut`]: ../../std/primitive.slice.html#method.rsplit_mut
3370 /// [slices]: ../../std/primitive.slice.html
3371 #[stable(feature = "slice_rsplit", since = "1.27.0")]
3372 pub struct RSplitMut<'a, T:'a, P> where P: FnMut(&T) -> bool {
3373     inner: SplitMut<'a, T, P>
3374 }
3375
3376 #[stable(feature = "slice_rsplit", since = "1.27.0")]
3377 impl<'a, T: 'a + fmt::Debug, P> fmt::Debug for RSplitMut<'a, T, P> where P: FnMut(&T) -> bool {
3378     fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
3379         f.debug_struct("RSplitMut")
3380             .field("v", &self.inner.v)
3381             .field("finished", &self.inner.finished)
3382             .finish()
3383     }
3384 }
3385
3386 #[stable(feature = "slice_rsplit", since = "1.27.0")]
3387 impl<'a, T, P> SplitIter for RSplitMut<'a, T, P> where P: FnMut(&T) -> bool {
3388     #[inline]
3389     fn finish(&mut self) -> Option<&'a mut [T]> {
3390         self.inner.finish()
3391     }
3392 }
3393
3394 #[stable(feature = "slice_rsplit", since = "1.27.0")]
3395 impl<'a, T, P> Iterator for RSplitMut<'a, T, P> where P: FnMut(&T) -> bool {
3396     type Item = &'a mut [T];
3397
3398     #[inline]
3399     fn next(&mut self) -> Option<&'a mut [T]> {
3400         self.inner.next_back()
3401     }
3402
3403     #[inline]
3404     fn size_hint(&self) -> (usize, Option<usize>) {
3405         self.inner.size_hint()
3406     }
3407 }
3408
3409 #[stable(feature = "slice_rsplit", since = "1.27.0")]
3410 impl<'a, T, P> DoubleEndedIterator for RSplitMut<'a, T, P> where
3411     P: FnMut(&T) -> bool,
3412 {
3413     #[inline]
3414     fn next_back(&mut self) -> Option<&'a mut [T]> {
3415         self.inner.next()
3416     }
3417 }
3418
3419 #[stable(feature = "slice_rsplit", since = "1.27.0")]
3420 impl<'a, T, P> FusedIterator for RSplitMut<'a, T, P> where P: FnMut(&T) -> bool {}
3421
3422 /// An private iterator over subslices separated by elements that
3423 /// match a predicate function, splitting at most a fixed number of
3424 /// times.
3425 #[derive(Debug)]
3426 struct GenericSplitN<I> {
3427     iter: I,
3428     count: usize,
3429 }
3430
3431 impl<T, I: SplitIter<Item=T>> Iterator for GenericSplitN<I> {
3432     type Item = T;
3433
3434     #[inline]
3435     fn next(&mut self) -> Option<T> {
3436         match self.count {
3437             0 => None,
3438             1 => { self.count -= 1; self.iter.finish() }
3439             _ => { self.count -= 1; self.iter.next() }
3440         }
3441     }
3442
3443     #[inline]
3444     fn size_hint(&self) -> (usize, Option<usize>) {
3445         let (lower, upper_opt) = self.iter.size_hint();
3446         (lower, upper_opt.map(|upper| cmp::min(self.count, upper)))
3447     }
3448 }
3449
3450 /// An iterator over subslices separated by elements that match a predicate
3451 /// function, limited to a given number of splits.
3452 ///
3453 /// This struct is created by the [`splitn`] method on [slices].
3454 ///
3455 /// [`splitn`]: ../../std/primitive.slice.html#method.splitn
3456 /// [slices]: ../../std/primitive.slice.html
3457 #[stable(feature = "rust1", since = "1.0.0")]
3458 pub struct SplitN<'a, T: 'a, P> where P: FnMut(&T) -> bool {
3459     inner: GenericSplitN<Split<'a, T, P>>
3460 }
3461
3462 #[stable(feature = "core_impl_debug", since = "1.9.0")]
3463 impl<'a, T: 'a + fmt::Debug, P> fmt::Debug for SplitN<'a, T, P> where P: FnMut(&T) -> bool {
3464     fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
3465         f.debug_struct("SplitN")
3466             .field("inner", &self.inner)
3467             .finish()
3468     }
3469 }
3470
3471 /// An iterator over subslices separated by elements that match a
3472 /// predicate function, limited to a given number of splits, starting
3473 /// from the end of the slice.
3474 ///
3475 /// This struct is created by the [`rsplitn`] method on [slices].
3476 ///
3477 /// [`rsplitn`]: ../../std/primitive.slice.html#method.rsplitn
3478 /// [slices]: ../../std/primitive.slice.html
3479 #[stable(feature = "rust1", since = "1.0.0")]
3480 pub struct RSplitN<'a, T: 'a, P> where P: FnMut(&T) -> bool {
3481     inner: GenericSplitN<RSplit<'a, T, P>>
3482 }
3483
3484 #[stable(feature = "core_impl_debug", since = "1.9.0")]
3485 impl<'a, T: 'a + fmt::Debug, P> fmt::Debug for RSplitN<'a, T, P> where P: FnMut(&T) -> bool {
3486     fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
3487         f.debug_struct("RSplitN")
3488             .field("inner", &self.inner)
3489             .finish()
3490     }
3491 }
3492
3493 /// An iterator over subslices separated by elements that match a predicate
3494 /// function, limited to a given number of splits.
3495 ///
3496 /// This struct is created by the [`splitn_mut`] method on [slices].
3497 ///
3498 /// [`splitn_mut`]: ../../std/primitive.slice.html#method.splitn_mut
3499 /// [slices]: ../../std/primitive.slice.html
3500 #[stable(feature = "rust1", since = "1.0.0")]
3501 pub struct SplitNMut<'a, T: 'a, P> where P: FnMut(&T) -> bool {
3502     inner: GenericSplitN<SplitMut<'a, T, P>>
3503 }
3504
3505 #[stable(feature = "core_impl_debug", since = "1.9.0")]
3506 impl<'a, T: 'a + fmt::Debug, P> fmt::Debug for SplitNMut<'a, T, P> where P: FnMut(&T) -> bool {
3507     fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
3508         f.debug_struct("SplitNMut")
3509             .field("inner", &self.inner)
3510             .finish()
3511     }
3512 }
3513
3514 /// An iterator over subslices separated by elements that match a
3515 /// predicate function, limited to a given number of splits, starting
3516 /// from the end of the slice.
3517 ///
3518 /// This struct is created by the [`rsplitn_mut`] method on [slices].
3519 ///
3520 /// [`rsplitn_mut`]: ../../std/primitive.slice.html#method.rsplitn_mut
3521 /// [slices]: ../../std/primitive.slice.html
3522 #[stable(feature = "rust1", since = "1.0.0")]
3523 pub struct RSplitNMut<'a, T: 'a, P> where P: FnMut(&T) -> bool {
3524     inner: GenericSplitN<RSplitMut<'a, T, P>>
3525 }
3526
3527 #[stable(feature = "core_impl_debug", since = "1.9.0")]
3528 impl<'a, T: 'a + fmt::Debug, P> fmt::Debug for RSplitNMut<'a, T, P> where P: FnMut(&T) -> bool {
3529     fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
3530         f.debug_struct("RSplitNMut")
3531             .field("inner", &self.inner)
3532             .finish()
3533     }
3534 }
3535
3536 macro_rules! forward_iterator {
3537     ($name:ident: $elem:ident, $iter_of:ty) => {
3538         #[stable(feature = "rust1", since = "1.0.0")]
3539         impl<'a, $elem, P> Iterator for $name<'a, $elem, P> where
3540             P: FnMut(&T) -> bool
3541         {
3542             type Item = $iter_of;
3543
3544             #[inline]
3545             fn next(&mut self) -> Option<$iter_of> {
3546                 self.inner.next()
3547             }
3548
3549             #[inline]
3550             fn size_hint(&self) -> (usize, Option<usize>) {
3551                 self.inner.size_hint()
3552             }
3553         }
3554
3555         #[stable(feature = "fused", since = "1.26.0")]
3556         impl<'a, $elem, P> FusedIterator for $name<'a, $elem, P>
3557             where P: FnMut(&T) -> bool {}
3558     }
3559 }
3560
3561 forward_iterator! { SplitN: T, &'a [T] }
3562 forward_iterator! { RSplitN: T, &'a [T] }
3563 forward_iterator! { SplitNMut: T, &'a mut [T] }
3564 forward_iterator! { RSplitNMut: T, &'a mut [T] }
3565
3566 /// An iterator over overlapping subslices of length `size`.
3567 ///
3568 /// This struct is created by the [`windows`] method on [slices].
3569 ///
3570 /// [`windows`]: ../../std/primitive.slice.html#method.windows
3571 /// [slices]: ../../std/primitive.slice.html
3572 #[derive(Debug)]
3573 #[stable(feature = "rust1", since = "1.0.0")]
3574 pub struct Windows<'a, T:'a> {
3575     v: &'a [T],
3576     size: usize
3577 }
3578
3579 // FIXME(#26925) Remove in favor of `#[derive(Clone)]`
3580 #[stable(feature = "rust1", since = "1.0.0")]
3581 impl<'a, T> Clone for Windows<'a, T> {
3582     fn clone(&self) -> Windows<'a, T> {
3583         Windows {
3584             v: self.v,
3585             size: self.size,
3586         }
3587     }
3588 }
3589
3590 #[stable(feature = "rust1", since = "1.0.0")]
3591 impl<'a, T> Iterator for Windows<'a, T> {
3592     type Item = &'a [T];
3593
3594     #[inline]
3595     fn next(&mut self) -> Option<&'a [T]> {
3596         if self.size > self.v.len() {
3597             None
3598         } else {
3599             let ret = Some(&self.v[..self.size]);
3600             self.v = &self.v[1..];
3601             ret
3602         }
3603     }
3604
3605     #[inline]
3606     fn size_hint(&self) -> (usize, Option<usize>) {
3607         if self.size > self.v.len() {
3608             (0, Some(0))
3609         } else {
3610             let size = self.v.len() - self.size + 1;
3611             (size, Some(size))
3612         }
3613     }
3614
3615     #[inline]
3616     fn count(self) -> usize {
3617         self.len()
3618     }
3619
3620     #[inline]
3621     fn nth(&mut self, n: usize) -> Option<Self::Item> {
3622         let (end, overflow) = self.size.overflowing_add(n);
3623         if end > self.v.len() || overflow {
3624             self.v = &[];
3625             None
3626         } else {
3627             let nth = &self.v[n..end];
3628             self.v = &self.v[n+1..];
3629             Some(nth)
3630         }
3631     }
3632
3633     #[inline]
3634     fn last(self) -> Option<Self::Item> {
3635         if self.size > self.v.len() {
3636             None
3637         } else {
3638             let start = self.v.len() - self.size;
3639             Some(&self.v[start..])
3640         }
3641     }
3642 }
3643
3644 #[stable(feature = "rust1", since = "1.0.0")]
3645 impl<'a, T> DoubleEndedIterator for Windows<'a, T> {
3646     #[inline]
3647     fn next_back(&mut self) -> Option<&'a [T]> {
3648         if self.size > self.v.len() {
3649             None
3650         } else {
3651             let ret = Some(&self.v[self.v.len()-self.size..]);
3652             self.v = &self.v[..self.v.len()-1];
3653             ret
3654         }
3655     }
3656 }
3657
3658 #[stable(feature = "rust1", since = "1.0.0")]
3659 impl<'a, T> ExactSizeIterator for Windows<'a, T> {}
3660
3661 #[stable(feature = "fused", since = "1.26.0")]
3662 impl<'a, T> FusedIterator for Windows<'a, T> {}
3663
3664 #[doc(hidden)]
3665 unsafe impl<'a, T> TrustedRandomAccess for Windows<'a, T> {
3666     unsafe fn get_unchecked(&mut self, i: usize) -> &'a [T] {
3667         from_raw_parts(self.v.as_ptr().offset(i as isize), self.size)
3668     }
3669     fn may_have_side_effect() -> bool { false }
3670 }
3671
3672 /// An iterator over a slice in (non-overlapping) chunks (`chunk_size` elements at a
3673 /// time).
3674 ///
3675 /// When the slice len is not evenly divided by the chunk size, the last slice
3676 /// of the iteration will be the remainder.
3677 ///
3678 /// This struct is created by the [`chunks`] method on [slices].
3679 ///
3680 /// [`chunks`]: ../../std/primitive.slice.html#method.chunks
3681 /// [slices]: ../../std/primitive.slice.html
3682 #[derive(Debug)]
3683 #[stable(feature = "rust1", since = "1.0.0")]
3684 pub struct Chunks<'a, T:'a> {
3685     v: &'a [T],
3686     chunk_size: usize
3687 }
3688
3689 // FIXME(#26925) Remove in favor of `#[derive(Clone)]`
3690 #[stable(feature = "rust1", since = "1.0.0")]
3691 impl<'a, T> Clone for Chunks<'a, T> {
3692     fn clone(&self) -> Chunks<'a, T> {
3693         Chunks {
3694             v: self.v,
3695             chunk_size: self.chunk_size,
3696         }
3697     }
3698 }
3699
3700 #[stable(feature = "rust1", since = "1.0.0")]
3701 impl<'a, T> Iterator for Chunks<'a, T> {
3702     type Item = &'a [T];
3703
3704     #[inline]
3705     fn next(&mut self) -> Option<&'a [T]> {
3706         if self.v.is_empty() {
3707             None
3708         } else {
3709             let chunksz = cmp::min(self.v.len(), self.chunk_size);
3710             let (fst, snd) = self.v.split_at(chunksz);
3711             self.v = snd;
3712             Some(fst)
3713         }
3714     }
3715
3716     #[inline]
3717     fn size_hint(&self) -> (usize, Option<usize>) {
3718         if self.v.is_empty() {
3719             (0, Some(0))
3720         } else {
3721             let n = self.v.len() / self.chunk_size;
3722             let rem = self.v.len() % self.chunk_size;
3723             let n = if rem > 0 { n+1 } else { n };
3724             (n, Some(n))
3725         }
3726     }
3727
3728     #[inline]
3729     fn count(self) -> usize {
3730         self.len()
3731     }
3732
3733     #[inline]
3734     fn nth(&mut self, n: usize) -> Option<Self::Item> {
3735         let (start, overflow) = n.overflowing_mul(self.chunk_size);
3736         if start >= self.v.len() || overflow {
3737             self.v = &[];
3738             None
3739         } else {
3740             let end = match start.checked_add(self.chunk_size) {
3741                 Some(sum) => cmp::min(self.v.len(), sum),
3742                 None => self.v.len(),
3743             };
3744             let nth = &self.v[start..end];
3745             self.v = &self.v[end..];
3746             Some(nth)
3747         }
3748     }
3749
3750     #[inline]
3751     fn last(self) -> Option<Self::Item> {
3752         if self.v.is_empty() {
3753             None
3754         } else {
3755             let start = (self.v.len() - 1) / self.chunk_size * self.chunk_size;
3756             Some(&self.v[start..])
3757         }
3758     }
3759 }
3760
3761 #[stable(feature = "rust1", since = "1.0.0")]
3762 impl<'a, T> DoubleEndedIterator for Chunks<'a, T> {
3763     #[inline]
3764     fn next_back(&mut self) -> Option<&'a [T]> {
3765         if self.v.is_empty() {
3766             None
3767         } else {
3768             let remainder = self.v.len() % self.chunk_size;
3769             let chunksz = if remainder != 0 { remainder } else { self.chunk_size };
3770             let (fst, snd) = self.v.split_at(self.v.len() - chunksz);
3771             self.v = fst;
3772             Some(snd)
3773         }
3774     }
3775 }
3776
3777 #[stable(feature = "rust1", since = "1.0.0")]
3778 impl<'a, T> ExactSizeIterator for Chunks<'a, T> {}
3779
3780 #[stable(feature = "fused", since = "1.26.0")]
3781 impl<'a, T> FusedIterator for Chunks<'a, T> {}
3782
3783 #[doc(hidden)]
3784 unsafe impl<'a, T> TrustedRandomAccess for Chunks<'a, T> {
3785     unsafe fn get_unchecked(&mut self, i: usize) -> &'a [T] {
3786         let start = i * self.chunk_size;
3787         let end = match start.checked_add(self.chunk_size) {
3788             None => self.v.len(),
3789             Some(end) => cmp::min(end, self.v.len()),
3790         };
3791         from_raw_parts(self.v.as_ptr().offset(start as isize), end - start)
3792     }
3793     fn may_have_side_effect() -> bool { false }
3794 }
3795
3796 /// An iterator over a slice in (non-overlapping) mutable chunks (`chunk_size`
3797 /// elements at a time). When the slice len is not evenly divided by the chunk
3798 /// size, the last slice of the iteration will be the remainder.
3799 ///
3800 /// This struct is created by the [`chunks_mut`] method on [slices].
3801 ///
3802 /// [`chunks_mut`]: ../../std/primitive.slice.html#method.chunks_mut
3803 /// [slices]: ../../std/primitive.slice.html
3804 #[derive(Debug)]
3805 #[stable(feature = "rust1", since = "1.0.0")]
3806 pub struct ChunksMut<'a, T:'a> {
3807     v: &'a mut [T],
3808     chunk_size: usize
3809 }
3810
3811 #[stable(feature = "rust1", since = "1.0.0")]
3812 impl<'a, T> Iterator for ChunksMut<'a, T> {
3813     type Item = &'a mut [T];
3814
3815     #[inline]
3816     fn next(&mut self) -> Option<&'a mut [T]> {
3817         if self.v.is_empty() {
3818             None
3819         } else {
3820             let sz = cmp::min(self.v.len(), self.chunk_size);
3821             let tmp = mem::replace(&mut self.v, &mut []);
3822             let (head, tail) = tmp.split_at_mut(sz);
3823             self.v = tail;
3824             Some(head)
3825         }
3826     }
3827
3828     #[inline]
3829     fn size_hint(&self) -> (usize, Option<usize>) {
3830         if self.v.is_empty() {
3831             (0, Some(0))
3832         } else {
3833             let n = self.v.len() / self.chunk_size;
3834             let rem = self.v.len() % self.chunk_size;
3835             let n = if rem > 0 { n + 1 } else { n };
3836             (n, Some(n))
3837         }
3838     }
3839
3840     #[inline]
3841     fn count(self) -> usize {
3842         self.len()
3843     }
3844
3845     #[inline]
3846     fn nth(&mut self, n: usize) -> Option<&'a mut [T]> {
3847         let (start, overflow) = n.overflowing_mul(self.chunk_size);
3848         if start >= self.v.len() || overflow {
3849             self.v = &mut [];
3850             None
3851         } else {
3852             let end = match start.checked_add(self.chunk_size) {
3853                 Some(sum) => cmp::min(self.v.len(), sum),
3854                 None => self.v.len(),
3855             };
3856             let tmp = mem::replace(&mut self.v, &mut []);
3857             let (head, tail) = tmp.split_at_mut(end);
3858             let (_, nth) =  head.split_at_mut(start);
3859             self.v = tail;
3860             Some(nth)
3861         }
3862     }
3863
3864     #[inline]
3865     fn last(self) -> Option<Self::Item> {
3866         if self.v.is_empty() {
3867             None
3868         } else {
3869             let start = (self.v.len() - 1) / self.chunk_size * self.chunk_size;
3870             Some(&mut self.v[start..])
3871         }
3872     }
3873 }
3874
3875 #[stable(feature = "rust1", since = "1.0.0")]
3876 impl<'a, T> DoubleEndedIterator for ChunksMut<'a, T> {
3877     #[inline]
3878     fn next_back(&mut self) -> Option<&'a mut [T]> {
3879         if self.v.is_empty() {
3880             None
3881         } else {
3882             let remainder = self.v.len() % self.chunk_size;
3883             let sz = if remainder != 0 { remainder } else { self.chunk_size };
3884             let tmp = mem::replace(&mut self.v, &mut []);
3885             let tmp_len = tmp.len();
3886             let (head, tail) = tmp.split_at_mut(tmp_len - sz);
3887             self.v = head;
3888             Some(tail)
3889         }
3890     }
3891 }
3892
3893 #[stable(feature = "rust1", since = "1.0.0")]
3894 impl<'a, T> ExactSizeIterator for ChunksMut<'a, T> {}
3895
3896 #[stable(feature = "fused", since = "1.26.0")]
3897 impl<'a, T> FusedIterator for ChunksMut<'a, T> {}
3898
3899 #[doc(hidden)]
3900 unsafe impl<'a, T> TrustedRandomAccess for ChunksMut<'a, T> {
3901     unsafe fn get_unchecked(&mut self, i: usize) -> &'a mut [T] {
3902         let start = i * self.chunk_size;
3903         let end = match start.checked_add(self.chunk_size) {
3904             None => self.v.len(),
3905             Some(end) => cmp::min(end, self.v.len()),
3906         };
3907         from_raw_parts_mut(self.v.as_mut_ptr().offset(start as isize), end - start)
3908     }
3909     fn may_have_side_effect() -> bool { false }
3910 }
3911
3912 /// An iterator over a slice in (non-overlapping) chunks (`chunk_size` elements at a
3913 /// time).
3914 ///
3915 /// When the slice len is not evenly divided by the chunk size, the last
3916 /// up to `chunk_size-1` elements will be omitted.
3917 ///
3918 /// This struct is created by the [`exact_chunks`] method on [slices].
3919 ///
3920 /// [`exact_chunks`]: ../../std/primitive.slice.html#method.exact_chunks
3921 /// [slices]: ../../std/primitive.slice.html
3922 #[derive(Debug)]
3923 #[unstable(feature = "exact_chunks", issue = "47115")]
3924 pub struct ExactChunks<'a, T:'a> {
3925     v: &'a [T],
3926     chunk_size: usize
3927 }
3928
3929 // FIXME(#26925) Remove in favor of `#[derive(Clone)]`
3930 #[unstable(feature = "exact_chunks", issue = "47115")]
3931 impl<'a, T> Clone for ExactChunks<'a, T> {
3932     fn clone(&self) -> ExactChunks<'a, T> {
3933         ExactChunks {
3934             v: self.v,
3935             chunk_size: self.chunk_size,
3936         }
3937     }
3938 }
3939
3940 #[unstable(feature = "exact_chunks", issue = "47115")]
3941 impl<'a, T> Iterator for ExactChunks<'a, T> {
3942     type Item = &'a [T];
3943
3944     #[inline]
3945     fn next(&mut self) -> Option<&'a [T]> {
3946         if self.v.len() < self.chunk_size {
3947             None
3948         } else {
3949             let (fst, snd) = self.v.split_at(self.chunk_size);
3950             self.v = snd;
3951             Some(fst)
3952         }
3953     }
3954
3955     #[inline]
3956     fn size_hint(&self) -> (usize, Option<usize>) {
3957         let n = self.v.len() / self.chunk_size;
3958         (n, Some(n))
3959     }
3960
3961     #[inline]
3962     fn count(self) -> usize {
3963         self.len()
3964     }
3965
3966     #[inline]
3967     fn nth(&mut self, n: usize) -> Option<Self::Item> {
3968         let (start, overflow) = n.overflowing_mul(self.chunk_size);
3969         if start >= self.v.len() || overflow {
3970             self.v = &[];
3971             None
3972         } else {
3973             let (_, snd) = self.v.split_at(start);
3974             self.v = snd;
3975             self.next()
3976         }
3977     }
3978
3979     #[inline]
3980     fn last(mut self) -> Option<Self::Item> {
3981         self.next_back()
3982     }
3983 }
3984
3985 #[unstable(feature = "exact_chunks", issue = "47115")]
3986 impl<'a, T> DoubleEndedIterator for ExactChunks<'a, T> {
3987     #[inline]
3988     fn next_back(&mut self) -> Option<&'a [T]> {
3989         if self.v.len() < self.chunk_size {
3990             None
3991         } else {
3992             let (fst, snd) = self.v.split_at(self.v.len() - self.chunk_size);
3993             self.v = fst;
3994             Some(snd)
3995         }
3996     }
3997 }
3998
3999 #[unstable(feature = "exact_chunks", issue = "47115")]
4000 impl<'a, T> ExactSizeIterator for ExactChunks<'a, T> {
4001     fn is_empty(&self) -> bool {
4002         self.v.is_empty()
4003     }
4004 }
4005
4006 #[unstable(feature = "exact_chunks", issue = "47115")]
4007 impl<'a, T> FusedIterator for ExactChunks<'a, T> {}
4008
4009 #[doc(hidden)]
4010 unsafe impl<'a, T> TrustedRandomAccess for ExactChunks<'a, T> {
4011     unsafe fn get_unchecked(&mut self, i: usize) -> &'a [T] {
4012         let start = i * self.chunk_size;
4013         from_raw_parts(self.v.as_ptr().offset(start as isize), self.chunk_size)
4014     }
4015     fn may_have_side_effect() -> bool { false }
4016 }
4017
4018 /// An iterator over a slice in (non-overlapping) mutable chunks (`chunk_size`
4019 /// elements at a time). When the slice len is not evenly divided by the chunk
4020 /// size, the last up to `chunk_size-1` elements will be omitted.
4021 ///
4022 /// This struct is created by the [`exact_chunks_mut`] method on [slices].
4023 ///
4024 /// [`exact_chunks_mut`]: ../../std/primitive.slice.html#method.exact_chunks_mut
4025 /// [slices]: ../../std/primitive.slice.html
4026 #[derive(Debug)]
4027 #[unstable(feature = "exact_chunks", issue = "47115")]
4028 pub struct ExactChunksMut<'a, T:'a> {
4029     v: &'a mut [T],
4030     chunk_size: usize
4031 }
4032
4033 #[unstable(feature = "exact_chunks", issue = "47115")]
4034 impl<'a, T> Iterator for ExactChunksMut<'a, T> {
4035     type Item = &'a mut [T];
4036
4037     #[inline]
4038     fn next(&mut self) -> Option<&'a mut [T]> {
4039         if self.v.len() < self.chunk_size {
4040             None
4041         } else {
4042             let tmp = mem::replace(&mut self.v, &mut []);
4043             let (head, tail) = tmp.split_at_mut(self.chunk_size);
4044             self.v = tail;
4045             Some(head)
4046         }
4047     }
4048
4049     #[inline]
4050     fn size_hint(&self) -> (usize, Option<usize>) {
4051         let n = self.v.len() / self.chunk_size;
4052         (n, Some(n))
4053     }
4054
4055     #[inline]
4056     fn count(self) -> usize {
4057         self.len()
4058     }
4059
4060     #[inline]
4061     fn nth(&mut self, n: usize) -> Option<&'a mut [T]> {
4062         let (start, overflow) = n.overflowing_mul(self.chunk_size);
4063         if start >= self.v.len() || overflow {
4064             self.v = &mut [];
4065             None
4066         } else {
4067             let tmp = mem::replace(&mut self.v, &mut []);
4068             let (_, snd) = tmp.split_at_mut(start);
4069             self.v = snd;
4070             self.next()
4071         }
4072     }
4073
4074     #[inline]
4075     fn last(mut self) -> Option<Self::Item> {
4076         self.next_back()
4077     }
4078 }
4079
4080 #[unstable(feature = "exact_chunks", issue = "47115")]
4081 impl<'a, T> DoubleEndedIterator for ExactChunksMut<'a, T> {
4082     #[inline]
4083     fn next_back(&mut self) -> Option<&'a mut [T]> {
4084         if self.v.len() < self.chunk_size {
4085             None
4086         } else {
4087             let tmp = mem::replace(&mut self.v, &mut []);
4088             let tmp_len = tmp.len();
4089             let (head, tail) = tmp.split_at_mut(tmp_len - self.chunk_size);
4090             self.v = head;
4091             Some(tail)
4092         }
4093     }
4094 }
4095
4096 #[unstable(feature = "exact_chunks", issue = "47115")]
4097 impl<'a, T> ExactSizeIterator for ExactChunksMut<'a, T> {
4098     fn is_empty(&self) -> bool {
4099         self.v.is_empty()
4100     }
4101 }
4102
4103 #[unstable(feature = "exact_chunks", issue = "47115")]
4104 impl<'a, T> FusedIterator for ExactChunksMut<'a, T> {}
4105
4106 #[doc(hidden)]
4107 unsafe impl<'a, T> TrustedRandomAccess for ExactChunksMut<'a, T> {
4108     unsafe fn get_unchecked(&mut self, i: usize) -> &'a mut [T] {
4109         let start = i * self.chunk_size;
4110         from_raw_parts_mut(self.v.as_mut_ptr().offset(start as isize), self.chunk_size)
4111     }
4112     fn may_have_side_effect() -> bool { false }
4113 }
4114
4115 //
4116 // Free functions
4117 //
4118
4119 /// Forms a slice from a pointer and a length.
4120 ///
4121 /// The `len` argument is the number of **elements**, not the number of bytes.
4122 ///
4123 /// # Safety
4124 ///
4125 /// This function is unsafe as there is no guarantee that the given pointer is
4126 /// valid for `len` elements, nor whether the lifetime inferred is a suitable
4127 /// lifetime for the returned slice.
4128 ///
4129 /// `p` must be non-null, even for zero-length slices, because non-zero bits
4130 /// are required to distinguish between a zero-length slice within `Some()`
4131 /// from `None`. `p` can be a bogus non-dereferencable pointer, such as `0x1`,
4132 /// for zero-length slices, though.
4133 ///
4134 /// # Caveat
4135 ///
4136 /// The lifetime for the returned slice is inferred from its usage. To
4137 /// prevent accidental misuse, it's suggested to tie the lifetime to whichever
4138 /// source lifetime is safe in the context, such as by providing a helper
4139 /// function taking the lifetime of a host value for the slice, or by explicit
4140 /// annotation.
4141 ///
4142 /// # Examples
4143 ///
4144 /// ```
4145 /// use std::slice;
4146 ///
4147 /// // manifest a slice out of thin air!
4148 /// let ptr = 0x1234 as *const usize;
4149 /// let amt = 10;
4150 /// unsafe {
4151 ///     let slice = slice::from_raw_parts(ptr, amt);
4152 /// }
4153 /// ```
4154 #[inline]
4155 #[stable(feature = "rust1", since = "1.0.0")]
4156 pub unsafe fn from_raw_parts<'a, T>(p: *const T, len: usize) -> &'a [T] {
4157     mem::transmute(Repr { data: p, len: len })
4158 }
4159
4160 /// Performs the same functionality as `from_raw_parts`, except that a mutable
4161 /// slice is returned.
4162 ///
4163 /// This function is unsafe for the same reasons as `from_raw_parts`, as well
4164 /// as not being able to provide a non-aliasing guarantee of the returned
4165 /// mutable slice. `p` must be non-null even for zero-length slices as with
4166 /// `from_raw_parts`.
4167 #[inline]
4168 #[stable(feature = "rust1", since = "1.0.0")]
4169 pub unsafe fn from_raw_parts_mut<'a, T>(p: *mut T, len: usize) -> &'a mut [T] {
4170     mem::transmute(Repr { data: p, len: len })
4171 }
4172
4173 /// Converts a reference to T into a slice of length 1 (without copying).
4174 #[unstable(feature = "from_ref", issue = "45703")]
4175 pub fn from_ref<T>(s: &T) -> &[T] {
4176     unsafe {
4177         from_raw_parts(s, 1)
4178     }
4179 }
4180
4181 /// Converts a reference to T into a slice of length 1 (without copying).
4182 #[unstable(feature = "from_ref", issue = "45703")]
4183 pub fn from_ref_mut<T>(s: &mut T) -> &mut [T] {
4184     unsafe {
4185         from_raw_parts_mut(s, 1)
4186     }
4187 }
4188
4189 // This function is public only because there is no other way to unit test heapsort.
4190 #[unstable(feature = "sort_internals", reason = "internal to sort module", issue = "0")]
4191 #[doc(hidden)]
4192 pub fn heapsort<T, F>(v: &mut [T], mut is_less: F)
4193     where F: FnMut(&T, &T) -> bool
4194 {
4195     sort::heapsort(v, &mut is_less);
4196 }
4197
4198 //
4199 // Comparison traits
4200 //
4201
4202 extern {
4203     /// Calls implementation provided memcmp.
4204     ///
4205     /// Interprets the data as u8.
4206     ///
4207     /// Returns 0 for equal, < 0 for less than and > 0 for greater
4208     /// than.
4209     // FIXME(#32610): Return type should be c_int
4210     fn memcmp(s1: *const u8, s2: *const u8, n: usize) -> i32;
4211 }
4212
4213 #[stable(feature = "rust1", since = "1.0.0")]
4214 impl<A, B> PartialEq<[B]> for [A] where A: PartialEq<B> {
4215     fn eq(&self, other: &[B]) -> bool {
4216         SlicePartialEq::equal(self, other)
4217     }
4218
4219     fn ne(&self, other: &[B]) -> bool {
4220         SlicePartialEq::not_equal(self, other)
4221     }
4222 }
4223
4224 #[stable(feature = "rust1", since = "1.0.0")]
4225 impl<T: Eq> Eq for [T] {}
4226
4227 /// Implements comparison of vectors lexicographically.
4228 #[stable(feature = "rust1", since = "1.0.0")]
4229 impl<T: Ord> Ord for [T] {
4230     fn cmp(&self, other: &[T]) -> Ordering {
4231         SliceOrd::compare(self, other)
4232     }
4233 }
4234
4235 /// Implements comparison of vectors lexicographically.
4236 #[stable(feature = "rust1", since = "1.0.0")]
4237 impl<T: PartialOrd> PartialOrd for [T] {
4238     fn partial_cmp(&self, other: &[T]) -> Option<Ordering> {
4239         SlicePartialOrd::partial_compare(self, other)
4240     }
4241 }
4242
4243 #[doc(hidden)]
4244 // intermediate trait for specialization of slice's PartialEq
4245 trait SlicePartialEq<B> {
4246     fn equal(&self, other: &[B]) -> bool;
4247
4248     fn not_equal(&self, other: &[B]) -> bool { !self.equal(other) }
4249 }
4250
4251 // Generic slice equality
4252 impl<A, B> SlicePartialEq<B> for [A]
4253     where A: PartialEq<B>
4254 {
4255     default fn equal(&self, other: &[B]) -> bool {
4256         if self.len() != other.len() {
4257             return false;
4258         }
4259
4260         for i in 0..self.len() {
4261             if !self[i].eq(&other[i]) {
4262                 return false;
4263             }
4264         }
4265
4266         true
4267     }
4268 }
4269
4270 // Use memcmp for bytewise equality when the types allow
4271 impl<A> SlicePartialEq<A> for [A]
4272     where A: PartialEq<A> + BytewiseEquality
4273 {
4274     fn equal(&self, other: &[A]) -> bool {
4275         if self.len() != other.len() {
4276             return false;
4277         }
4278         if self.as_ptr() == other.as_ptr() {
4279             return true;
4280         }
4281         unsafe {
4282             let size = mem::size_of_val(self);
4283             memcmp(self.as_ptr() as *const u8,
4284                    other.as_ptr() as *const u8, size) == 0
4285         }
4286     }
4287 }
4288
4289 #[doc(hidden)]
4290 // intermediate trait for specialization of slice's PartialOrd
4291 trait SlicePartialOrd<B> {
4292     fn partial_compare(&self, other: &[B]) -> Option<Ordering>;
4293 }
4294
4295 impl<A> SlicePartialOrd<A> for [A]
4296     where A: PartialOrd
4297 {
4298     default fn partial_compare(&self, other: &[A]) -> Option<Ordering> {
4299         let l = cmp::min(self.len(), other.len());
4300
4301         // Slice to the loop iteration range to enable bound check
4302         // elimination in the compiler
4303         let lhs = &self[..l];
4304         let rhs = &other[..l];
4305
4306         for i in 0..l {
4307             match lhs[i].partial_cmp(&rhs[i]) {
4308                 Some(Ordering::Equal) => (),
4309                 non_eq => return non_eq,
4310             }
4311         }
4312
4313         self.len().partial_cmp(&other.len())
4314     }
4315 }
4316
4317 impl<A> SlicePartialOrd<A> for [A]
4318     where A: Ord
4319 {
4320     default fn partial_compare(&self, other: &[A]) -> Option<Ordering> {
4321         Some(SliceOrd::compare(self, other))
4322     }
4323 }
4324
4325 #[doc(hidden)]
4326 // intermediate trait for specialization of slice's Ord
4327 trait SliceOrd<B> {
4328     fn compare(&self, other: &[B]) -> Ordering;
4329 }
4330
4331 impl<A> SliceOrd<A> for [A]
4332     where A: Ord
4333 {
4334     default fn compare(&self, other: &[A]) -> Ordering {
4335         let l = cmp::min(self.len(), other.len());
4336
4337         // Slice to the loop iteration range to enable bound check
4338         // elimination in the compiler
4339         let lhs = &self[..l];
4340         let rhs = &other[..l];
4341
4342         for i in 0..l {
4343             match lhs[i].cmp(&rhs[i]) {
4344                 Ordering::Equal => (),
4345                 non_eq => return non_eq,
4346             }
4347         }
4348
4349         self.len().cmp(&other.len())
4350     }
4351 }
4352
4353 // memcmp compares a sequence of unsigned bytes lexicographically.
4354 // this matches the order we want for [u8], but no others (not even [i8]).
4355 impl SliceOrd<u8> for [u8] {
4356     #[inline]
4357     fn compare(&self, other: &[u8]) -> Ordering {
4358         let order = unsafe {
4359             memcmp(self.as_ptr(), other.as_ptr(),
4360                    cmp::min(self.len(), other.len()))
4361         };
4362         if order == 0 {
4363             self.len().cmp(&other.len())
4364         } else if order < 0 {
4365             Less
4366         } else {
4367             Greater
4368         }
4369     }
4370 }
4371
4372 #[doc(hidden)]
4373 /// Trait implemented for types that can be compared for equality using
4374 /// their bytewise representation
4375 trait BytewiseEquality { }
4376
4377 macro_rules! impl_marker_for {
4378     ($traitname:ident, $($ty:ty)*) => {
4379         $(
4380             impl $traitname for $ty { }
4381         )*
4382     }
4383 }
4384
4385 impl_marker_for!(BytewiseEquality,
4386                  u8 i8 u16 i16 u32 i32 u64 i64 usize isize char bool);
4387
4388 #[doc(hidden)]
4389 unsafe impl<'a, T> TrustedRandomAccess for Iter<'a, T> {
4390     unsafe fn get_unchecked(&mut self, i: usize) -> &'a T {
4391         &*self.ptr.offset(i as isize)
4392     }
4393     fn may_have_side_effect() -> bool { false }
4394 }
4395
4396 #[doc(hidden)]
4397 unsafe impl<'a, T> TrustedRandomAccess for IterMut<'a, T> {
4398     unsafe fn get_unchecked(&mut self, i: usize) -> &'a mut T {
4399         &mut *self.ptr.offset(i as isize)
4400     }
4401     fn may_have_side_effect() -> bool { false }
4402 }
4403
4404 trait SliceContains: Sized {
4405     fn slice_contains(&self, x: &[Self]) -> bool;
4406 }
4407
4408 impl<T> SliceContains for T where T: PartialEq {
4409     default fn slice_contains(&self, x: &[Self]) -> bool {
4410         x.iter().any(|y| *y == *self)
4411     }
4412 }
4413
4414 impl SliceContains for u8 {
4415     fn slice_contains(&self, x: &[Self]) -> bool {
4416         memchr::memchr(*self, x).is_some()
4417     }
4418 }
4419
4420 impl SliceContains for i8 {
4421     fn slice_contains(&self, x: &[Self]) -> bool {
4422         let byte = *self as u8;
4423         let bytes: &[u8] = unsafe { from_raw_parts(x.as_ptr() as *const u8, x.len()) };
4424         memchr::memchr(byte, bytes).is_some()
4425     }
4426 }