]> git.lizzy.rs Git - rust.git/blob - src/libcore/slice/mod.rs
Auto merge of #45538 - nikomatsakis:nll-liveness, r=pnkfelix
[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 // FIXME: after next stage0, change RangeInclusive { ... } back to ..=
20 use ops::RangeInclusive;
21
22 // How this module is organized.
23 //
24 // The library infrastructure for slices is fairly messy. There's
25 // a lot of stuff defined here. Let's keep it clean.
26 //
27 // Since slices don't support inherent methods; all operations
28 // on them are defined on traits, which are then reexported from
29 // the prelude for convenience. So there are a lot of traits here.
30 //
31 // The layout of this file is thus:
32 //
33 // * Slice-specific 'extension' traits and their implementations. This
34 //   is where most of the slice API resides.
35 // * Implementations of a few common traits with important slice ops.
36 // * Definitions of a bunch of iterators.
37 // * Free functions.
38 // * The `raw` and `bytes` submodules.
39 // * Boilerplate trait implementations.
40
41 use cmp::Ordering::{self, Less, Equal, Greater};
42 use cmp;
43 use fmt;
44 use intrinsics::assume;
45 use iter::*;
46 use ops::{FnMut, self};
47 use option::Option;
48 use option::Option::{None, Some};
49 use result::Result;
50 use result::Result::{Ok, Err};
51 use ptr;
52 use mem;
53 use marker::{Copy, Send, Sync, Sized, self};
54 use iter_private::TrustedRandomAccess;
55
56 mod rotate;
57 mod sort;
58
59 #[repr(C)]
60 struct Repr<T> {
61     pub data: *const T,
62     pub len: usize,
63 }
64
65 //
66 // Extension traits
67 //
68
69 /// Extension methods for slices.
70 #[unstable(feature = "core_slice_ext",
71            reason = "stable interface provided by `impl [T]` in later crates",
72            issue = "32110")]
73 #[allow(missing_docs)] // documented elsewhere
74 pub trait SliceExt {
75     type Item;
76
77     #[stable(feature = "core", since = "1.6.0")]
78     fn split_at(&self, mid: usize) -> (&[Self::Item], &[Self::Item]);
79
80     #[stable(feature = "core", since = "1.6.0")]
81     fn iter(&self) -> Iter<Self::Item>;
82
83     #[stable(feature = "core", since = "1.6.0")]
84     fn split<P>(&self, pred: P) -> Split<Self::Item, P>
85         where P: FnMut(&Self::Item) -> bool;
86
87     #[unstable(feature = "slice_rsplit", issue = "41020")]
88     fn rsplit<P>(&self, pred: P) -> RSplit<Self::Item, P>
89         where P: FnMut(&Self::Item) -> bool;
90
91     #[stable(feature = "core", since = "1.6.0")]
92     fn splitn<P>(&self, n: usize, pred: P) -> SplitN<Self::Item, P>
93         where P: FnMut(&Self::Item) -> bool;
94
95     #[stable(feature = "core", since = "1.6.0")]
96     fn rsplitn<P>(&self,  n: usize, pred: P) -> RSplitN<Self::Item, P>
97         where P: FnMut(&Self::Item) -> bool;
98
99     #[stable(feature = "core", since = "1.6.0")]
100     fn windows(&self, size: usize) -> Windows<Self::Item>;
101
102     #[stable(feature = "core", since = "1.6.0")]
103     fn chunks(&self, size: usize) -> Chunks<Self::Item>;
104
105     #[stable(feature = "core", since = "1.6.0")]
106     fn get<I>(&self, index: I) -> Option<&I::Output>
107         where I: SliceIndex<Self>;
108     #[stable(feature = "core", since = "1.6.0")]
109     fn first(&self) -> Option<&Self::Item>;
110
111     #[stable(feature = "core", since = "1.6.0")]
112     fn split_first(&self) -> Option<(&Self::Item, &[Self::Item])>;
113
114     #[stable(feature = "core", since = "1.6.0")]
115     fn split_last(&self) -> Option<(&Self::Item, &[Self::Item])>;
116
117     #[stable(feature = "core", since = "1.6.0")]
118     fn last(&self) -> Option<&Self::Item>;
119
120     #[stable(feature = "core", since = "1.6.0")]
121     unsafe fn get_unchecked<I>(&self, index: I) -> &I::Output
122         where I: SliceIndex<Self>;
123     #[stable(feature = "core", since = "1.6.0")]
124     fn as_ptr(&self) -> *const Self::Item;
125
126     #[stable(feature = "core", since = "1.6.0")]
127     fn binary_search(&self, x: &Self::Item) -> Result<usize, usize>
128         where Self::Item: Ord;
129
130     #[stable(feature = "core", since = "1.6.0")]
131     fn binary_search_by<'a, F>(&'a self, f: F) -> Result<usize, usize>
132         where F: FnMut(&'a Self::Item) -> Ordering;
133
134     #[stable(feature = "slice_binary_search_by_key", since = "1.10.0")]
135     fn binary_search_by_key<'a, B, F>(&'a self, b: &B, f: F) -> Result<usize, usize>
136         where F: FnMut(&'a Self::Item) -> B,
137               B: Ord;
138
139     #[stable(feature = "core", since = "1.6.0")]
140     fn len(&self) -> usize;
141
142     #[stable(feature = "core", since = "1.6.0")]
143     fn is_empty(&self) -> bool { self.len() == 0 }
144
145     #[stable(feature = "core", since = "1.6.0")]
146     fn get_mut<I>(&mut self, index: I) -> Option<&mut I::Output>
147         where I: SliceIndex<Self>;
148     #[stable(feature = "core", since = "1.6.0")]
149     fn iter_mut(&mut self) -> IterMut<Self::Item>;
150
151     #[stable(feature = "core", since = "1.6.0")]
152     fn first_mut(&mut self) -> Option<&mut Self::Item>;
153
154     #[stable(feature = "core", since = "1.6.0")]
155     fn split_first_mut(&mut self) -> Option<(&mut Self::Item, &mut [Self::Item])>;
156
157     #[stable(feature = "core", since = "1.6.0")]
158     fn split_last_mut(&mut self) -> Option<(&mut Self::Item, &mut [Self::Item])>;
159
160     #[stable(feature = "core", since = "1.6.0")]
161     fn last_mut(&mut self) -> Option<&mut Self::Item>;
162
163     #[stable(feature = "core", since = "1.6.0")]
164     fn split_mut<P>(&mut self, pred: P) -> SplitMut<Self::Item, P>
165         where P: FnMut(&Self::Item) -> bool;
166
167     #[unstable(feature = "slice_rsplit", issue = "41020")]
168     fn rsplit_mut<P>(&mut self, pred: P) -> RSplitMut<Self::Item, P>
169         where P: FnMut(&Self::Item) -> bool;
170
171     #[stable(feature = "core", since = "1.6.0")]
172     fn splitn_mut<P>(&mut self, n: usize, pred: P) -> SplitNMut<Self::Item, P>
173         where P: FnMut(&Self::Item) -> bool;
174
175     #[stable(feature = "core", since = "1.6.0")]
176     fn rsplitn_mut<P>(&mut self,  n: usize, pred: P) -> RSplitNMut<Self::Item, P>
177         where P: FnMut(&Self::Item) -> bool;
178
179     #[stable(feature = "core", since = "1.6.0")]
180     fn chunks_mut(&mut self, chunk_size: usize) -> ChunksMut<Self::Item>;
181
182     #[stable(feature = "core", since = "1.6.0")]
183     fn swap(&mut self, a: usize, b: usize);
184
185     #[stable(feature = "core", since = "1.6.0")]
186     fn split_at_mut(&mut self, mid: usize) -> (&mut [Self::Item], &mut [Self::Item]);
187
188     #[stable(feature = "core", since = "1.6.0")]
189     fn reverse(&mut self);
190
191     #[stable(feature = "core", since = "1.6.0")]
192     unsafe fn get_unchecked_mut<I>(&mut self, index: I) -> &mut I::Output
193         where I: SliceIndex<Self>;
194     #[stable(feature = "core", since = "1.6.0")]
195     fn as_mut_ptr(&mut self) -> *mut Self::Item;
196
197     #[stable(feature = "core", since = "1.6.0")]
198     fn contains(&self, x: &Self::Item) -> bool where Self::Item: PartialEq;
199
200     #[stable(feature = "core", since = "1.6.0")]
201     fn starts_with(&self, needle: &[Self::Item]) -> bool where Self::Item: PartialEq;
202
203     #[stable(feature = "core", since = "1.6.0")]
204     fn ends_with(&self, needle: &[Self::Item]) -> bool where Self::Item: PartialEq;
205
206     #[unstable(feature = "slice_rotate", issue = "41891")]
207     fn rotate(&mut self, mid: usize);
208
209     #[stable(feature = "clone_from_slice", since = "1.7.0")]
210     fn clone_from_slice(&mut self, src: &[Self::Item]) where Self::Item: Clone;
211
212     #[stable(feature = "copy_from_slice", since = "1.9.0")]
213     fn copy_from_slice(&mut self, src: &[Self::Item]) where Self::Item: Copy;
214
215     #[unstable(feature = "swap_with_slice", issue = "44030")]
216     fn swap_with_slice(&mut self, src: &mut [Self::Item]);
217
218     #[stable(feature = "sort_unstable", since = "1.20.0")]
219     fn sort_unstable(&mut self)
220         where Self::Item: Ord;
221
222     #[stable(feature = "sort_unstable", since = "1.20.0")]
223     fn sort_unstable_by<F>(&mut self, compare: F)
224         where F: FnMut(&Self::Item, &Self::Item) -> Ordering;
225
226     #[stable(feature = "sort_unstable", since = "1.20.0")]
227     fn sort_unstable_by_key<B, F>(&mut self, f: F)
228         where F: FnMut(&Self::Item) -> B,
229               B: Ord;
230 }
231
232 // Use macros to be generic over const/mut
233 macro_rules! slice_offset {
234     ($ptr:expr, $by:expr) => {{
235         let ptr = $ptr;
236         if size_from_ptr(ptr) == 0 {
237             (ptr as *mut i8).wrapping_offset($by) as _
238         } else {
239             ptr.offset($by)
240         }
241     }};
242 }
243
244 // make a &T from a *const T
245 macro_rules! make_ref {
246     ($ptr:expr) => {{
247         let ptr = $ptr;
248         if size_from_ptr(ptr) == 0 {
249             // Use a non-null pointer value
250             &*(1 as *mut _)
251         } else {
252             &*ptr
253         }
254     }};
255 }
256
257 // make a &mut T from a *mut T
258 macro_rules! make_ref_mut {
259     ($ptr:expr) => {{
260         let ptr = $ptr;
261         if size_from_ptr(ptr) == 0 {
262             // Use a non-null pointer value
263             &mut *(1 as *mut _)
264         } else {
265             &mut *ptr
266         }
267     }};
268 }
269
270 #[unstable(feature = "core_slice_ext",
271            reason = "stable interface provided by `impl [T]` in later crates",
272            issue = "32110")]
273 impl<T> SliceExt for [T] {
274     type Item = T;
275
276     #[inline]
277     fn split_at(&self, mid: usize) -> (&[T], &[T]) {
278         (&self[..mid], &self[mid..])
279     }
280
281     #[inline]
282     fn iter(&self) -> Iter<T> {
283         unsafe {
284             let p = if mem::size_of::<T>() == 0 {
285                 1 as *const _
286             } else {
287                 let p = self.as_ptr();
288                 assume(!p.is_null());
289                 p
290             };
291
292             Iter {
293                 ptr: p,
294                 end: slice_offset!(p, self.len() as isize),
295                 _marker: marker::PhantomData
296             }
297         }
298     }
299
300     #[inline]
301     fn split<P>(&self, pred: P) -> Split<T, P>
302         where P: FnMut(&T) -> bool
303     {
304         Split {
305             v: self,
306             pred,
307             finished: false
308         }
309     }
310
311     #[inline]
312     fn rsplit<P>(&self, pred: P) -> RSplit<T, P>
313         where P: FnMut(&T) -> bool
314     {
315         RSplit { inner: self.split(pred) }
316     }
317
318     #[inline]
319     fn splitn<P>(&self, n: usize, pred: P) -> SplitN<T, P>
320         where P: FnMut(&T) -> bool
321     {
322         SplitN {
323             inner: GenericSplitN {
324                 iter: self.split(pred),
325                 count: n
326             }
327         }
328     }
329
330     #[inline]
331     fn rsplitn<P>(&self, n: usize, pred: P) -> RSplitN<T, P>
332         where P: FnMut(&T) -> bool
333     {
334         RSplitN {
335             inner: GenericSplitN {
336                 iter: self.rsplit(pred),
337                 count: n
338             }
339         }
340     }
341
342     #[inline]
343     fn windows(&self, size: usize) -> Windows<T> {
344         assert!(size != 0);
345         Windows { v: self, size: size }
346     }
347
348     #[inline]
349     fn chunks(&self, size: usize) -> Chunks<T> {
350         assert!(size != 0);
351         Chunks { v: self, size: size }
352     }
353
354     #[inline]
355     fn get<I>(&self, index: I) -> Option<&I::Output>
356         where I: SliceIndex<[T]>
357     {
358         index.get(self)
359     }
360
361     #[inline]
362     fn first(&self) -> Option<&T> {
363         if self.is_empty() { None } else { Some(&self[0]) }
364     }
365
366     #[inline]
367     fn split_first(&self) -> Option<(&T, &[T])> {
368         if self.is_empty() { None } else { Some((&self[0], &self[1..])) }
369     }
370
371     #[inline]
372     fn split_last(&self) -> Option<(&T, &[T])> {
373         let len = self.len();
374         if len == 0 { None } else { Some((&self[len - 1], &self[..(len - 1)])) }
375     }
376
377     #[inline]
378     fn last(&self) -> Option<&T> {
379         if self.is_empty() { None } else { Some(&self[self.len() - 1]) }
380     }
381
382     #[inline]
383     unsafe fn get_unchecked<I>(&self, index: I) -> &I::Output
384         where I: SliceIndex<[T]>
385     {
386         index.get_unchecked(self)
387     }
388
389     #[inline]
390     fn as_ptr(&self) -> *const T {
391         self as *const [T] as *const T
392     }
393
394     fn binary_search_by<'a, F>(&'a self, mut f: F) -> Result<usize, usize>
395         where F: FnMut(&'a T) -> Ordering
396     {
397         let mut base = 0usize;
398         let mut s = self;
399
400         loop {
401             let (head, tail) = s.split_at(s.len() >> 1);
402             if tail.is_empty() {
403                 return Err(base)
404             }
405             match f(&tail[0]) {
406                 Less => {
407                     base += head.len() + 1;
408                     s = &tail[1..];
409                 }
410                 Greater => s = head,
411                 Equal => return Ok(base + head.len()),
412             }
413         }
414     }
415
416     #[inline]
417     fn len(&self) -> usize {
418         unsafe {
419             mem::transmute::<&[T], Repr<T>>(self).len
420         }
421     }
422
423     #[inline]
424     fn get_mut<I>(&mut self, index: I) -> Option<&mut I::Output>
425         where I: SliceIndex<[T]>
426     {
427         index.get_mut(self)
428     }
429
430     #[inline]
431     fn split_at_mut(&mut self, mid: usize) -> (&mut [T], &mut [T]) {
432         let len = self.len();
433         let ptr = self.as_mut_ptr();
434
435         unsafe {
436             assert!(mid <= len);
437
438             (from_raw_parts_mut(ptr, mid),
439              from_raw_parts_mut(ptr.offset(mid as isize), len - mid))
440         }
441     }
442
443     #[inline]
444     fn iter_mut(&mut self) -> IterMut<T> {
445         unsafe {
446             let p = if mem::size_of::<T>() == 0 {
447                 1 as *mut _
448             } else {
449                 let p = self.as_mut_ptr();
450                 assume(!p.is_null());
451                 p
452             };
453
454             IterMut {
455                 ptr: p,
456                 end: slice_offset!(p, self.len() as isize),
457                 _marker: marker::PhantomData
458             }
459         }
460     }
461
462     #[inline]
463     fn last_mut(&mut self) -> Option<&mut T> {
464         let len = self.len();
465         if len == 0 { return None; }
466         Some(&mut self[len - 1])
467     }
468
469     #[inline]
470     fn first_mut(&mut self) -> Option<&mut T> {
471         if self.is_empty() { None } else { Some(&mut self[0]) }
472     }
473
474     #[inline]
475     fn split_first_mut(&mut self) -> Option<(&mut T, &mut [T])> {
476         if self.is_empty() { None } else {
477             let split = self.split_at_mut(1);
478             Some((&mut split.0[0], split.1))
479         }
480     }
481
482     #[inline]
483     fn split_last_mut(&mut self) -> Option<(&mut T, &mut [T])> {
484         let len = self.len();
485         if len == 0 { None } else {
486             let split = self.split_at_mut(len - 1);
487             Some((&mut split.1[0], split.0))
488         }
489     }
490
491     #[inline]
492     fn split_mut<P>(&mut self, pred: P) -> SplitMut<T, P>
493         where P: FnMut(&T) -> bool
494     {
495         SplitMut { v: self, pred: pred, finished: false }
496     }
497
498     #[inline]
499     fn rsplit_mut<P>(&mut self, pred: P) -> RSplitMut<T, P>
500         where P: FnMut(&T) -> bool
501     {
502         RSplitMut { inner: self.split_mut(pred) }
503     }
504
505     #[inline]
506     fn splitn_mut<P>(&mut self, n: usize, pred: P) -> SplitNMut<T, P>
507         where P: FnMut(&T) -> bool
508     {
509         SplitNMut {
510             inner: GenericSplitN {
511                 iter: self.split_mut(pred),
512                 count: n
513             }
514         }
515     }
516
517     #[inline]
518     fn rsplitn_mut<P>(&mut self, n: usize, pred: P) -> RSplitNMut<T, P> where
519         P: FnMut(&T) -> bool,
520     {
521         RSplitNMut {
522             inner: GenericSplitN {
523                 iter: self.rsplit_mut(pred),
524                 count: n
525             }
526         }
527     }
528
529     #[inline]
530     fn chunks_mut(&mut self, chunk_size: usize) -> ChunksMut<T> {
531         assert!(chunk_size > 0);
532         ChunksMut { v: self, chunk_size: chunk_size }
533     }
534
535     #[inline]
536     fn swap(&mut self, a: usize, b: usize) {
537         unsafe {
538             // Can't take two mutable loans from one vector, so instead just cast
539             // them to their raw pointers to do the swap
540             let pa: *mut T = &mut self[a];
541             let pb: *mut T = &mut self[b];
542             ptr::swap(pa, pb);
543         }
544     }
545
546     fn reverse(&mut self) {
547         let mut i: usize = 0;
548         let ln = self.len();
549
550         // For very small types, all the individual reads in the normal
551         // path perform poorly.  We can do better, given efficient unaligned
552         // load/store, by loading a larger chunk and reversing a register.
553
554         // Ideally LLVM would do this for us, as it knows better than we do
555         // whether unaligned reads are efficient (since that changes between
556         // different ARM versions, for example) and what the best chunk size
557         // would be.  Unfortunately, as of LLVM 4.0 (2017-05) it only unrolls
558         // the loop, so we need to do this ourselves.  (Hypothesis: reverse
559         // is troublesome because the sides can be aligned differently --
560         // will be, when the length is odd -- so there's no way of emitting
561         // pre- and postludes to use fully-aligned SIMD in the middle.)
562
563         let fast_unaligned =
564             cfg!(any(target_arch = "x86", target_arch = "x86_64"));
565
566         if fast_unaligned && mem::size_of::<T>() == 1 {
567             // Use the llvm.bswap intrinsic to reverse u8s in a usize
568             let chunk = mem::size_of::<usize>();
569             while i + chunk - 1 < ln / 2 {
570                 unsafe {
571                     let pa: *mut T = self.get_unchecked_mut(i);
572                     let pb: *mut T = self.get_unchecked_mut(ln - i - chunk);
573                     let va = ptr::read_unaligned(pa as *mut usize);
574                     let vb = ptr::read_unaligned(pb as *mut usize);
575                     ptr::write_unaligned(pa as *mut usize, vb.swap_bytes());
576                     ptr::write_unaligned(pb as *mut usize, va.swap_bytes());
577                 }
578                 i += chunk;
579             }
580         }
581
582         if fast_unaligned && mem::size_of::<T>() == 2 {
583             // Use rotate-by-16 to reverse u16s in a u32
584             let chunk = mem::size_of::<u32>() / 2;
585             while i + chunk - 1 < ln / 2 {
586                 unsafe {
587                     let pa: *mut T = self.get_unchecked_mut(i);
588                     let pb: *mut T = self.get_unchecked_mut(ln - i - chunk);
589                     let va = ptr::read_unaligned(pa as *mut u32);
590                     let vb = ptr::read_unaligned(pb as *mut u32);
591                     ptr::write_unaligned(pa as *mut u32, vb.rotate_left(16));
592                     ptr::write_unaligned(pb as *mut u32, va.rotate_left(16));
593                 }
594                 i += chunk;
595             }
596         }
597
598         while i < ln / 2 {
599             // Unsafe swap to avoid the bounds check in safe swap.
600             unsafe {
601                 let pa: *mut T = self.get_unchecked_mut(i);
602                 let pb: *mut T = self.get_unchecked_mut(ln - i - 1);
603                 ptr::swap(pa, pb);
604             }
605             i += 1;
606         }
607     }
608
609     #[inline]
610     unsafe fn get_unchecked_mut<I>(&mut self, index: I) -> &mut I::Output
611         where I: SliceIndex<[T]>
612     {
613         index.get_unchecked_mut(self)
614     }
615
616     #[inline]
617     fn as_mut_ptr(&mut self) -> *mut T {
618         self as *mut [T] as *mut T
619     }
620
621     #[inline]
622     fn contains(&self, x: &T) -> bool where T: PartialEq {
623         self.iter().any(|elt| *x == *elt)
624     }
625
626     #[inline]
627     fn starts_with(&self, needle: &[T]) -> bool where T: PartialEq {
628         let n = needle.len();
629         self.len() >= n && needle == &self[..n]
630     }
631
632     #[inline]
633     fn ends_with(&self, needle: &[T]) -> bool where T: PartialEq {
634         let (m, n) = (self.len(), needle.len());
635         m >= n && needle == &self[m-n..]
636     }
637
638     fn binary_search(&self, x: &T) -> Result<usize, usize>
639         where T: Ord
640     {
641         self.binary_search_by(|p| p.cmp(x))
642     }
643
644     fn rotate(&mut self, mid: usize) {
645         assert!(mid <= self.len());
646         let k = self.len() - mid;
647
648         unsafe {
649             let p = self.as_mut_ptr();
650             rotate::ptr_rotate(mid, p.offset(mid as isize), k);
651         }
652     }
653
654     #[inline]
655     fn clone_from_slice(&mut self, src: &[T]) where T: Clone {
656         assert!(self.len() == src.len(),
657                 "destination and source slices have different lengths");
658         // NOTE: We need to explicitly slice them to the same length
659         // for bounds checking to be elided, and the optimizer will
660         // generate memcpy for simple cases (for example T = u8).
661         let len = self.len();
662         let src = &src[..len];
663         for i in 0..len {
664             self[i].clone_from(&src[i]);
665         }
666     }
667
668     #[inline]
669     fn copy_from_slice(&mut self, src: &[T]) where T: Copy {
670         assert!(self.len() == src.len(),
671                 "destination and source slices have different lengths");
672         unsafe {
673             ptr::copy_nonoverlapping(
674                 src.as_ptr(), self.as_mut_ptr(), self.len());
675         }
676     }
677
678     #[inline]
679     fn swap_with_slice(&mut self, src: &mut [T]) {
680         assert!(self.len() == src.len(),
681                 "destination and source slices have different lengths");
682         unsafe {
683             ptr::swap_nonoverlapping(
684                 self.as_mut_ptr(), src.as_mut_ptr(), self.len());
685         }
686     }
687
688     #[inline]
689     fn binary_search_by_key<'a, B, F>(&'a self, b: &B, mut f: F) -> Result<usize, usize>
690         where F: FnMut(&'a Self::Item) -> B,
691               B: Ord
692     {
693         self.binary_search_by(|k| f(k).cmp(b))
694     }
695
696     #[inline]
697     fn sort_unstable(&mut self)
698         where Self::Item: Ord
699     {
700         sort::quicksort(self, |a, b| a.lt(b));
701     }
702
703     #[inline]
704     fn sort_unstable_by<F>(&mut self, mut compare: F)
705         where F: FnMut(&Self::Item, &Self::Item) -> Ordering
706     {
707         sort::quicksort(self, |a, b| compare(a, b) == Ordering::Less);
708     }
709
710     #[inline]
711     fn sort_unstable_by_key<B, F>(&mut self, mut f: F)
712         where F: FnMut(&Self::Item) -> B,
713               B: Ord
714     {
715         sort::quicksort(self, |a, b| f(a).lt(&f(b)));
716     }
717 }
718
719 #[stable(feature = "rust1", since = "1.0.0")]
720 #[rustc_on_unimplemented = "slice indices are of type `usize` or ranges of `usize`"]
721 impl<T, I> ops::Index<I> for [T]
722     where I: SliceIndex<[T]>
723 {
724     type Output = I::Output;
725
726     #[inline]
727     fn index(&self, index: I) -> &I::Output {
728         index.index(self)
729     }
730 }
731
732 #[stable(feature = "rust1", since = "1.0.0")]
733 #[rustc_on_unimplemented = "slice indices are of type `usize` or ranges of `usize`"]
734 impl<T, I> ops::IndexMut<I> for [T]
735     where I: SliceIndex<[T]>
736 {
737     #[inline]
738     fn index_mut(&mut self, index: I) -> &mut I::Output {
739         index.index_mut(self)
740     }
741 }
742
743 #[inline(never)]
744 #[cold]
745 fn slice_index_len_fail(index: usize, len: usize) -> ! {
746     panic!("index {} out of range for slice of length {}", index, len);
747 }
748
749 #[inline(never)]
750 #[cold]
751 fn slice_index_order_fail(index: usize, end: usize) -> ! {
752     panic!("slice index starts at {} but ends at {}", index, end);
753 }
754
755 /// A helper trait used for indexing operations.
756 #[unstable(feature = "slice_get_slice", issue = "35729")]
757 #[rustc_on_unimplemented = "slice indices are of type `usize` or ranges of `usize`"]
758 pub trait SliceIndex<T: ?Sized> {
759     /// The output type returned by methods.
760     type Output: ?Sized;
761
762     /// Returns a shared reference to the output at this location, if in
763     /// bounds.
764     fn get(self, slice: &T) -> Option<&Self::Output>;
765
766     /// Returns a mutable reference to the output at this location, if in
767     /// bounds.
768     fn get_mut(self, slice: &mut T) -> Option<&mut Self::Output>;
769
770     /// Returns a shared reference to the output at this location, without
771     /// performing any bounds checking.
772     unsafe fn get_unchecked(self, slice: &T) -> &Self::Output;
773
774     /// Returns a mutable reference to the output at this location, without
775     /// performing any bounds checking.
776     unsafe fn get_unchecked_mut(self, slice: &mut T) -> &mut Self::Output;
777
778     /// Returns a shared reference to the output at this location, panicking
779     /// if out of bounds.
780     fn index(self, slice: &T) -> &Self::Output;
781
782     /// Returns a mutable reference to the output at this location, panicking
783     /// if out of bounds.
784     fn index_mut(self, slice: &mut T) -> &mut Self::Output;
785 }
786
787 #[stable(feature = "slice-get-slice-impls", since = "1.15.0")]
788 impl<T> SliceIndex<[T]> for usize {
789     type Output = T;
790
791     #[inline]
792     fn get(self, slice: &[T]) -> Option<&T> {
793         if self < slice.len() {
794             unsafe {
795                 Some(self.get_unchecked(slice))
796             }
797         } else {
798             None
799         }
800     }
801
802     #[inline]
803     fn get_mut(self, slice: &mut [T]) -> Option<&mut T> {
804         if self < slice.len() {
805             unsafe {
806                 Some(self.get_unchecked_mut(slice))
807             }
808         } else {
809             None
810         }
811     }
812
813     #[inline]
814     unsafe fn get_unchecked(self, slice: &[T]) -> &T {
815         &*slice.as_ptr().offset(self as isize)
816     }
817
818     #[inline]
819     unsafe fn get_unchecked_mut(self, slice: &mut [T]) -> &mut T {
820         &mut *slice.as_mut_ptr().offset(self as isize)
821     }
822
823     #[inline]
824     fn index(self, slice: &[T]) -> &T {
825         // NB: use intrinsic indexing
826         &(*slice)[self]
827     }
828
829     #[inline]
830     fn index_mut(self, slice: &mut [T]) -> &mut T {
831         // NB: use intrinsic indexing
832         &mut (*slice)[self]
833     }
834 }
835
836 #[stable(feature = "slice-get-slice-impls", since = "1.15.0")]
837 impl<T> SliceIndex<[T]> for  ops::Range<usize> {
838     type Output = [T];
839
840     #[inline]
841     fn get(self, slice: &[T]) -> Option<&[T]> {
842         if self.start > self.end || self.end > slice.len() {
843             None
844         } else {
845             unsafe {
846                 Some(self.get_unchecked(slice))
847             }
848         }
849     }
850
851     #[inline]
852     fn get_mut(self, slice: &mut [T]) -> Option<&mut [T]> {
853         if self.start > self.end || self.end > slice.len() {
854             None
855         } else {
856             unsafe {
857                 Some(self.get_unchecked_mut(slice))
858             }
859         }
860     }
861
862     #[inline]
863     unsafe fn get_unchecked(self, slice: &[T]) -> &[T] {
864         from_raw_parts(slice.as_ptr().offset(self.start as isize), self.end - self.start)
865     }
866
867     #[inline]
868     unsafe fn get_unchecked_mut(self, slice: &mut [T]) -> &mut [T] {
869         from_raw_parts_mut(slice.as_mut_ptr().offset(self.start as isize), self.end - self.start)
870     }
871
872     #[inline]
873     fn index(self, slice: &[T]) -> &[T] {
874         if self.start > self.end {
875             slice_index_order_fail(self.start, self.end);
876         } else if self.end > slice.len() {
877             slice_index_len_fail(self.end, slice.len());
878         }
879         unsafe {
880             self.get_unchecked(slice)
881         }
882     }
883
884     #[inline]
885     fn index_mut(self, slice: &mut [T]) -> &mut [T] {
886         if self.start > self.end {
887             slice_index_order_fail(self.start, self.end);
888         } else if self.end > slice.len() {
889             slice_index_len_fail(self.end, slice.len());
890         }
891         unsafe {
892             self.get_unchecked_mut(slice)
893         }
894     }
895 }
896
897 #[stable(feature = "slice-get-slice-impls", since = "1.15.0")]
898 impl<T> SliceIndex<[T]> for ops::RangeTo<usize> {
899     type Output = [T];
900
901     #[inline]
902     fn get(self, slice: &[T]) -> Option<&[T]> {
903         (0..self.end).get(slice)
904     }
905
906     #[inline]
907     fn get_mut(self, slice: &mut [T]) -> Option<&mut [T]> {
908         (0..self.end).get_mut(slice)
909     }
910
911     #[inline]
912     unsafe fn get_unchecked(self, slice: &[T]) -> &[T] {
913         (0..self.end).get_unchecked(slice)
914     }
915
916     #[inline]
917     unsafe fn get_unchecked_mut(self, slice: &mut [T]) -> &mut [T] {
918         (0..self.end).get_unchecked_mut(slice)
919     }
920
921     #[inline]
922     fn index(self, slice: &[T]) -> &[T] {
923         (0..self.end).index(slice)
924     }
925
926     #[inline]
927     fn index_mut(self, slice: &mut [T]) -> &mut [T] {
928         (0..self.end).index_mut(slice)
929     }
930 }
931
932 #[stable(feature = "slice-get-slice-impls", since = "1.15.0")]
933 impl<T> SliceIndex<[T]> for ops::RangeFrom<usize> {
934     type Output = [T];
935
936     #[inline]
937     fn get(self, slice: &[T]) -> Option<&[T]> {
938         (self.start..slice.len()).get(slice)
939     }
940
941     #[inline]
942     fn get_mut(self, slice: &mut [T]) -> Option<&mut [T]> {
943         (self.start..slice.len()).get_mut(slice)
944     }
945
946     #[inline]
947     unsafe fn get_unchecked(self, slice: &[T]) -> &[T] {
948         (self.start..slice.len()).get_unchecked(slice)
949     }
950
951     #[inline]
952     unsafe fn get_unchecked_mut(self, slice: &mut [T]) -> &mut [T] {
953         (self.start..slice.len()).get_unchecked_mut(slice)
954     }
955
956     #[inline]
957     fn index(self, slice: &[T]) -> &[T] {
958         (self.start..slice.len()).index(slice)
959     }
960
961     #[inline]
962     fn index_mut(self, slice: &mut [T]) -> &mut [T] {
963         (self.start..slice.len()).index_mut(slice)
964     }
965 }
966
967 #[stable(feature = "slice-get-slice-impls", since = "1.15.0")]
968 impl<T> SliceIndex<[T]> for ops::RangeFull {
969     type Output = [T];
970
971     #[inline]
972     fn get(self, slice: &[T]) -> Option<&[T]> {
973         Some(slice)
974     }
975
976     #[inline]
977     fn get_mut(self, slice: &mut [T]) -> Option<&mut [T]> {
978         Some(slice)
979     }
980
981     #[inline]
982     unsafe fn get_unchecked(self, slice: &[T]) -> &[T] {
983         slice
984     }
985
986     #[inline]
987     unsafe fn get_unchecked_mut(self, slice: &mut [T]) -> &mut [T] {
988         slice
989     }
990
991     #[inline]
992     fn index(self, slice: &[T]) -> &[T] {
993         slice
994     }
995
996     #[inline]
997     fn index_mut(self, slice: &mut [T]) -> &mut [T] {
998         slice
999     }
1000 }
1001
1002
1003 #[unstable(feature = "inclusive_range", reason = "recently added, follows RFC", issue = "28237")]
1004 impl<T> SliceIndex<[T]> for ops::RangeInclusive<usize> {
1005     type Output = [T];
1006
1007     #[inline]
1008     fn get(self, slice: &[T]) -> Option<&[T]> {
1009         if self.end == usize::max_value() { None }
1010         else { (self.start..self.end + 1).get(slice) }
1011     }
1012
1013     #[inline]
1014     fn get_mut(self, slice: &mut [T]) -> Option<&mut [T]> {
1015         if self.end == usize::max_value() { None }
1016         else { (self.start..self.end + 1).get_mut(slice) }
1017     }
1018
1019     #[inline]
1020     unsafe fn get_unchecked(self, slice: &[T]) -> &[T] {
1021         (self.start..self.end + 1).get_unchecked(slice)
1022     }
1023
1024     #[inline]
1025     unsafe fn get_unchecked_mut(self, slice: &mut [T]) -> &mut [T] {
1026         (self.start..self.end + 1).get_unchecked_mut(slice)
1027     }
1028
1029     #[inline]
1030     fn index(self, slice: &[T]) -> &[T] {
1031         assert!(self.end != usize::max_value(),
1032             "attempted to index slice up to maximum usize");
1033         (self.start..self.end + 1).index(slice)
1034     }
1035
1036     #[inline]
1037     fn index_mut(self, slice: &mut [T]) -> &mut [T] {
1038         assert!(self.end != usize::max_value(),
1039             "attempted to index slice up to maximum usize");
1040         (self.start..self.end + 1).index_mut(slice)
1041     }
1042 }
1043
1044 #[unstable(feature = "inclusive_range", reason = "recently added, follows RFC", issue = "28237")]
1045 impl<T> SliceIndex<[T]> for ops::RangeToInclusive<usize> {
1046     type Output = [T];
1047
1048     #[inline]
1049     fn get(self, slice: &[T]) -> Option<&[T]> {
1050         (RangeInclusive { start: 0, end: self.end }).get(slice)
1051     }
1052
1053     #[inline]
1054     fn get_mut(self, slice: &mut [T]) -> Option<&mut [T]> {
1055         (RangeInclusive { start: 0, end: self.end }).get_mut(slice)
1056     }
1057
1058     #[inline]
1059     unsafe fn get_unchecked(self, slice: &[T]) -> &[T] {
1060         (RangeInclusive { start: 0, end: self.end }).get_unchecked(slice)
1061     }
1062
1063     #[inline]
1064     unsafe fn get_unchecked_mut(self, slice: &mut [T]) -> &mut [T] {
1065         (RangeInclusive { start: 0, end: self.end }).get_unchecked_mut(slice)
1066     }
1067
1068     #[inline]
1069     fn index(self, slice: &[T]) -> &[T] {
1070         (RangeInclusive { start: 0, end: self.end }).index(slice)
1071     }
1072
1073     #[inline]
1074     fn index_mut(self, slice: &mut [T]) -> &mut [T] {
1075         (RangeInclusive { start: 0, end: self.end }).index_mut(slice)
1076     }
1077 }
1078
1079 ////////////////////////////////////////////////////////////////////////////////
1080 // Common traits
1081 ////////////////////////////////////////////////////////////////////////////////
1082
1083 #[stable(feature = "rust1", since = "1.0.0")]
1084 impl<'a, T> Default for &'a [T] {
1085     /// Creates an empty slice.
1086     fn default() -> &'a [T] { &[] }
1087 }
1088
1089 #[stable(feature = "mut_slice_default", since = "1.5.0")]
1090 impl<'a, T> Default for &'a mut [T] {
1091     /// Creates a mutable empty slice.
1092     fn default() -> &'a mut [T] { &mut [] }
1093 }
1094
1095 //
1096 // Iterators
1097 //
1098
1099 #[stable(feature = "rust1", since = "1.0.0")]
1100 impl<'a, T> IntoIterator for &'a [T] {
1101     type Item = &'a T;
1102     type IntoIter = Iter<'a, T>;
1103
1104     fn into_iter(self) -> Iter<'a, T> {
1105         self.iter()
1106     }
1107 }
1108
1109 #[stable(feature = "rust1", since = "1.0.0")]
1110 impl<'a, T> IntoIterator for &'a mut [T] {
1111     type Item = &'a mut T;
1112     type IntoIter = IterMut<'a, T>;
1113
1114     fn into_iter(self) -> IterMut<'a, T> {
1115         self.iter_mut()
1116     }
1117 }
1118
1119 #[inline]
1120 fn size_from_ptr<T>(_: *const T) -> usize {
1121     mem::size_of::<T>()
1122 }
1123
1124 // The shared definition of the `Iter` and `IterMut` iterators
1125 macro_rules! iterator {
1126     (struct $name:ident -> $ptr:ty, $elem:ty, $mkref:ident) => {
1127         #[stable(feature = "rust1", since = "1.0.0")]
1128         impl<'a, T> Iterator for $name<'a, T> {
1129             type Item = $elem;
1130
1131             #[inline]
1132             fn next(&mut self) -> Option<$elem> {
1133                 // could be implemented with slices, but this avoids bounds checks
1134                 unsafe {
1135                     if mem::size_of::<T>() != 0 {
1136                         assume(!self.ptr.is_null());
1137                         assume(!self.end.is_null());
1138                     }
1139                     if self.ptr == self.end {
1140                         None
1141                     } else {
1142                         Some($mkref!(self.ptr.post_inc()))
1143                     }
1144                 }
1145             }
1146
1147             #[inline]
1148             fn size_hint(&self) -> (usize, Option<usize>) {
1149                 let exact = ptrdistance(self.ptr, self.end);
1150                 (exact, Some(exact))
1151             }
1152
1153             #[inline]
1154             fn count(self) -> usize {
1155                 self.len()
1156             }
1157
1158             #[inline]
1159             fn nth(&mut self, n: usize) -> Option<$elem> {
1160                 // Call helper method. Can't put the definition here because mut versus const.
1161                 self.iter_nth(n)
1162             }
1163
1164             #[inline]
1165             fn last(mut self) -> Option<$elem> {
1166                 self.next_back()
1167             }
1168
1169             fn all<F>(&mut self, mut predicate: F) -> bool
1170                 where F: FnMut(Self::Item) -> bool,
1171             {
1172                 self.search_while(true, move |elt| {
1173                     if predicate(elt) {
1174                         SearchWhile::Continue
1175                     } else {
1176                         SearchWhile::Done(false)
1177                     }
1178                 })
1179             }
1180
1181             fn any<F>(&mut self, mut predicate: F) -> bool
1182                 where F: FnMut(Self::Item) -> bool,
1183             {
1184                 !self.all(move |elt| !predicate(elt))
1185             }
1186
1187             fn find<F>(&mut self, mut predicate: F) -> Option<Self::Item>
1188                 where F: FnMut(&Self::Item) -> bool,
1189             {
1190                 self.search_while(None, move |elt| {
1191                     if predicate(&elt) {
1192                         SearchWhile::Done(Some(elt))
1193                     } else {
1194                         SearchWhile::Continue
1195                     }
1196                 })
1197             }
1198
1199             fn position<F>(&mut self, mut predicate: F) -> Option<usize>
1200                 where F: FnMut(Self::Item) -> bool,
1201             {
1202                 let mut index = 0;
1203                 self.search_while(None, move |elt| {
1204                     if predicate(elt) {
1205                         SearchWhile::Done(Some(index))
1206                     } else {
1207                         index += 1;
1208                         SearchWhile::Continue
1209                     }
1210                 })
1211             }
1212
1213             fn rposition<F>(&mut self, mut predicate: F) -> Option<usize>
1214                 where F: FnMut(Self::Item) -> bool,
1215             {
1216                 let mut index = self.len();
1217                 self.rsearch_while(None, move |elt| {
1218                     index -= 1;
1219                     if predicate(elt) {
1220                         SearchWhile::Done(Some(index))
1221                     } else {
1222                         SearchWhile::Continue
1223                     }
1224                 })
1225             }
1226         }
1227
1228         #[stable(feature = "rust1", since = "1.0.0")]
1229         impl<'a, T> DoubleEndedIterator for $name<'a, T> {
1230             #[inline]
1231             fn next_back(&mut self) -> Option<$elem> {
1232                 // could be implemented with slices, but this avoids bounds checks
1233                 unsafe {
1234                     if mem::size_of::<T>() != 0 {
1235                         assume(!self.ptr.is_null());
1236                         assume(!self.end.is_null());
1237                     }
1238                     if self.end == self.ptr {
1239                         None
1240                     } else {
1241                         Some($mkref!(self.end.pre_dec()))
1242                     }
1243                 }
1244             }
1245
1246             fn rfind<F>(&mut self, mut predicate: F) -> Option<Self::Item>
1247                 where F: FnMut(&Self::Item) -> bool,
1248             {
1249                 self.rsearch_while(None, move |elt| {
1250                     if predicate(&elt) {
1251                         SearchWhile::Done(Some(elt))
1252                     } else {
1253                         SearchWhile::Continue
1254                     }
1255                 })
1256             }
1257
1258         }
1259
1260         // search_while is a generalization of the internal iteration methods.
1261         impl<'a, T> $name<'a, T> {
1262             // search through the iterator's element using the closure `g`.
1263             // if no element was found, return `default`.
1264             fn search_while<Acc, G>(&mut self, default: Acc, mut g: G) -> Acc
1265                 where Self: Sized,
1266                       G: FnMut($elem) -> SearchWhile<Acc>
1267             {
1268                 // manual unrolling is needed when there are conditional exits from the loop
1269                 unsafe {
1270                     while ptrdistance(self.ptr, self.end) >= 4 {
1271                         search_while!(g($mkref!(self.ptr.post_inc())));
1272                         search_while!(g($mkref!(self.ptr.post_inc())));
1273                         search_while!(g($mkref!(self.ptr.post_inc())));
1274                         search_while!(g($mkref!(self.ptr.post_inc())));
1275                     }
1276                     while self.ptr != self.end {
1277                         search_while!(g($mkref!(self.ptr.post_inc())));
1278                     }
1279                 }
1280                 default
1281             }
1282
1283             fn rsearch_while<Acc, G>(&mut self, default: Acc, mut g: G) -> Acc
1284                 where Self: Sized,
1285                       G: FnMut($elem) -> SearchWhile<Acc>
1286             {
1287                 unsafe {
1288                     while ptrdistance(self.ptr, self.end) >= 4 {
1289                         search_while!(g($mkref!(self.end.pre_dec())));
1290                         search_while!(g($mkref!(self.end.pre_dec())));
1291                         search_while!(g($mkref!(self.end.pre_dec())));
1292                         search_while!(g($mkref!(self.end.pre_dec())));
1293                     }
1294                     while self.ptr != self.end {
1295                         search_while!(g($mkref!(self.end.pre_dec())));
1296                     }
1297                 }
1298                 default
1299             }
1300         }
1301     }
1302 }
1303
1304 macro_rules! make_slice {
1305     ($start: expr, $end: expr) => {{
1306         let start = $start;
1307         let diff = ($end as usize).wrapping_sub(start as usize);
1308         if size_from_ptr(start) == 0 {
1309             // use a non-null pointer value
1310             unsafe { from_raw_parts(1 as *const _, diff) }
1311         } else {
1312             let len = diff / size_from_ptr(start);
1313             unsafe { from_raw_parts(start, len) }
1314         }
1315     }}
1316 }
1317
1318 macro_rules! make_mut_slice {
1319     ($start: expr, $end: expr) => {{
1320         let start = $start;
1321         let diff = ($end as usize).wrapping_sub(start as usize);
1322         if size_from_ptr(start) == 0 {
1323             // use a non-null pointer value
1324             unsafe { from_raw_parts_mut(1 as *mut _, diff) }
1325         } else {
1326             let len = diff / size_from_ptr(start);
1327             unsafe { from_raw_parts_mut(start, len) }
1328         }
1329     }}
1330 }
1331
1332 // An enum used for controlling the execution of `.search_while()`.
1333 enum SearchWhile<T> {
1334     // Continue searching
1335     Continue,
1336     // Fold is complete and will return this value
1337     Done(T),
1338 }
1339
1340 // helper macro for search while's control flow
1341 macro_rules! search_while {
1342     ($e:expr) => {
1343         match $e {
1344             SearchWhile::Continue => { }
1345             SearchWhile::Done(done) => return done,
1346         }
1347     }
1348 }
1349
1350 /// Immutable slice iterator
1351 ///
1352 /// This struct is created by the [`iter`] method on [slices].
1353 ///
1354 /// # Examples
1355 ///
1356 /// Basic usage:
1357 ///
1358 /// ```
1359 /// // First, we declare a type which has `iter` method to get the `Iter` struct (&[usize here]):
1360 /// let slice = &[1, 2, 3];
1361 ///
1362 /// // Then, we iterate over it:
1363 /// for element in slice.iter() {
1364 ///     println!("{}", element);
1365 /// }
1366 /// ```
1367 ///
1368 /// [`iter`]: ../../std/primitive.slice.html#method.iter
1369 /// [slices]: ../../std/primitive.slice.html
1370 #[stable(feature = "rust1", since = "1.0.0")]
1371 pub struct Iter<'a, T: 'a> {
1372     ptr: *const T,
1373     end: *const T,
1374     _marker: marker::PhantomData<&'a T>,
1375 }
1376
1377 #[stable(feature = "core_impl_debug", since = "1.9.0")]
1378 impl<'a, T: 'a + fmt::Debug> fmt::Debug for Iter<'a, T> {
1379     fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
1380         f.debug_tuple("Iter")
1381             .field(&self.as_slice())
1382             .finish()
1383     }
1384 }
1385
1386 #[stable(feature = "rust1", since = "1.0.0")]
1387 unsafe impl<'a, T: Sync> Sync for Iter<'a, T> {}
1388 #[stable(feature = "rust1", since = "1.0.0")]
1389 unsafe impl<'a, T: Sync> Send for Iter<'a, T> {}
1390
1391 impl<'a, T> Iter<'a, T> {
1392     /// View the underlying data as a subslice of the original data.
1393     ///
1394     /// This has the same lifetime as the original slice, and so the
1395     /// iterator can continue to be used while this exists.
1396     ///
1397     /// # Examples
1398     ///
1399     /// Basic usage:
1400     ///
1401     /// ```
1402     /// // First, we declare a type which has the `iter` method to get the `Iter`
1403     /// // struct (&[usize here]):
1404     /// let slice = &[1, 2, 3];
1405     ///
1406     /// // Then, we get the iterator:
1407     /// let mut iter = slice.iter();
1408     /// // So if we print what `as_slice` method returns here, we have "[1, 2, 3]":
1409     /// println!("{:?}", iter.as_slice());
1410     ///
1411     /// // Next, we move to the second element of the slice:
1412     /// iter.next();
1413     /// // Now `as_slice` returns "[2, 3]":
1414     /// println!("{:?}", iter.as_slice());
1415     /// ```
1416     #[stable(feature = "iter_to_slice", since = "1.4.0")]
1417     pub fn as_slice(&self) -> &'a [T] {
1418         make_slice!(self.ptr, self.end)
1419     }
1420
1421     // Helper function for Iter::nth
1422     fn iter_nth(&mut self, n: usize) -> Option<&'a T> {
1423         match self.as_slice().get(n) {
1424             Some(elem_ref) => unsafe {
1425                 self.ptr = slice_offset!(self.ptr, (n as isize).wrapping_add(1));
1426                 Some(elem_ref)
1427             },
1428             None => {
1429                 self.ptr = self.end;
1430                 None
1431             }
1432         }
1433     }
1434 }
1435
1436 iterator!{struct Iter -> *const T, &'a T, make_ref}
1437
1438 #[stable(feature = "rust1", since = "1.0.0")]
1439 impl<'a, T> ExactSizeIterator for Iter<'a, T> {
1440     fn is_empty(&self) -> bool {
1441         self.ptr == self.end
1442     }
1443 }
1444
1445 #[unstable(feature = "fused", issue = "35602")]
1446 impl<'a, T> FusedIterator for Iter<'a, T> {}
1447
1448 #[unstable(feature = "trusted_len", issue = "37572")]
1449 unsafe impl<'a, T> TrustedLen for Iter<'a, T> {}
1450
1451 #[stable(feature = "rust1", since = "1.0.0")]
1452 impl<'a, T> Clone for Iter<'a, T> {
1453     fn clone(&self) -> Iter<'a, T> { Iter { ptr: self.ptr, end: self.end, _marker: self._marker } }
1454 }
1455
1456 #[stable(feature = "slice_iter_as_ref", since = "1.13.0")]
1457 impl<'a, T> AsRef<[T]> for Iter<'a, T> {
1458     fn as_ref(&self) -> &[T] {
1459         self.as_slice()
1460     }
1461 }
1462
1463 /// Mutable slice iterator.
1464 ///
1465 /// This struct is created by the [`iter_mut`] method on [slices].
1466 ///
1467 /// # Examples
1468 ///
1469 /// Basic usage:
1470 ///
1471 /// ```
1472 /// // First, we declare a type which has `iter_mut` method to get the `IterMut`
1473 /// // struct (&[usize here]):
1474 /// let mut slice = &mut [1, 2, 3];
1475 ///
1476 /// // Then, we iterate over it and increment each element value:
1477 /// for element in slice.iter_mut() {
1478 ///     *element += 1;
1479 /// }
1480 ///
1481 /// // We now have "[2, 3, 4]":
1482 /// println!("{:?}", slice);
1483 /// ```
1484 ///
1485 /// [`iter_mut`]: ../../std/primitive.slice.html#method.iter_mut
1486 /// [slices]: ../../std/primitive.slice.html
1487 #[stable(feature = "rust1", since = "1.0.0")]
1488 pub struct IterMut<'a, T: 'a> {
1489     ptr: *mut T,
1490     end: *mut T,
1491     _marker: marker::PhantomData<&'a mut T>,
1492 }
1493
1494 #[stable(feature = "core_impl_debug", since = "1.9.0")]
1495 impl<'a, T: 'a + fmt::Debug> fmt::Debug for IterMut<'a, T> {
1496     fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
1497         f.debug_tuple("IterMut")
1498             .field(&make_slice!(self.ptr, self.end))
1499             .finish()
1500     }
1501 }
1502
1503 #[stable(feature = "rust1", since = "1.0.0")]
1504 unsafe impl<'a, T: Sync> Sync for IterMut<'a, T> {}
1505 #[stable(feature = "rust1", since = "1.0.0")]
1506 unsafe impl<'a, T: Send> Send for IterMut<'a, T> {}
1507
1508 impl<'a, T> IterMut<'a, T> {
1509     /// View the underlying data as a subslice of the original data.
1510     ///
1511     /// To avoid creating `&mut` references that alias, this is forced
1512     /// to consume the iterator. Consider using the `Slice` and
1513     /// `SliceMut` implementations for obtaining slices with more
1514     /// restricted lifetimes that do not consume the iterator.
1515     ///
1516     /// # Examples
1517     ///
1518     /// Basic usage:
1519     ///
1520     /// ```
1521     /// // First, we declare a type which has `iter_mut` method to get the `IterMut`
1522     /// // struct (&[usize here]):
1523     /// let mut slice = &mut [1, 2, 3];
1524     ///
1525     /// {
1526     ///     // Then, we get the iterator:
1527     ///     let mut iter = slice.iter_mut();
1528     ///     // We move to next element:
1529     ///     iter.next();
1530     ///     // So if we print what `into_slice` method returns here, we have "[2, 3]":
1531     ///     println!("{:?}", iter.into_slice());
1532     /// }
1533     ///
1534     /// // Now let's modify a value of the slice:
1535     /// {
1536     ///     // First we get back the iterator:
1537     ///     let mut iter = slice.iter_mut();
1538     ///     // We change the value of the first element of the slice returned by the `next` method:
1539     ///     *iter.next().unwrap() += 1;
1540     /// }
1541     /// // Now slice is "[2, 2, 3]":
1542     /// println!("{:?}", slice);
1543     /// ```
1544     #[stable(feature = "iter_to_slice", since = "1.4.0")]
1545     pub fn into_slice(self) -> &'a mut [T] {
1546         make_mut_slice!(self.ptr, self.end)
1547     }
1548
1549     // Helper function for IterMut::nth
1550     fn iter_nth(&mut self, n: usize) -> Option<&'a mut T> {
1551         match make_mut_slice!(self.ptr, self.end).get_mut(n) {
1552             Some(elem_ref) => unsafe {
1553                 self.ptr = slice_offset!(self.ptr, (n as isize).wrapping_add(1));
1554                 Some(elem_ref)
1555             },
1556             None => {
1557                 self.ptr = self.end;
1558                 None
1559             }
1560         }
1561     }
1562 }
1563
1564 iterator!{struct IterMut -> *mut T, &'a mut T, make_ref_mut}
1565
1566 #[stable(feature = "rust1", since = "1.0.0")]
1567 impl<'a, T> ExactSizeIterator for IterMut<'a, T> {
1568     fn is_empty(&self) -> bool {
1569         self.ptr == self.end
1570     }
1571 }
1572
1573 #[unstable(feature = "fused", issue = "35602")]
1574 impl<'a, T> FusedIterator for IterMut<'a, T> {}
1575
1576 #[unstable(feature = "trusted_len", issue = "37572")]
1577 unsafe impl<'a, T> TrustedLen for IterMut<'a, T> {}
1578
1579
1580 // Return the number of elements of `T` from `start` to `end`.
1581 // Return the arithmetic difference if `T` is zero size.
1582 #[inline(always)]
1583 fn ptrdistance<T>(start: *const T, end: *const T) -> usize {
1584     match start.offset_to(end) {
1585         Some(x) => x as usize,
1586         None => (end as usize).wrapping_sub(start as usize),
1587     }
1588 }
1589
1590 // Extension methods for raw pointers, used by the iterators
1591 trait PointerExt : Copy {
1592     unsafe fn slice_offset(self, i: isize) -> Self;
1593
1594     /// Increments `self` by 1, but returns the old value.
1595     #[inline(always)]
1596     unsafe fn post_inc(&mut self) -> Self {
1597         let current = *self;
1598         *self = self.slice_offset(1);
1599         current
1600     }
1601
1602     /// Decrements `self` by 1, and returns the new value.
1603     #[inline(always)]
1604     unsafe fn pre_dec(&mut self) -> Self {
1605         *self = self.slice_offset(-1);
1606         *self
1607     }
1608 }
1609
1610 impl<T> PointerExt for *const T {
1611     #[inline(always)]
1612     unsafe fn slice_offset(self, i: isize) -> Self {
1613         slice_offset!(self, i)
1614     }
1615 }
1616
1617 impl<T> PointerExt for *mut T {
1618     #[inline(always)]
1619     unsafe fn slice_offset(self, i: isize) -> Self {
1620         slice_offset!(self, i)
1621     }
1622 }
1623
1624 /// An internal abstraction over the splitting iterators, so that
1625 /// splitn, splitn_mut etc can be implemented once.
1626 #[doc(hidden)]
1627 trait SplitIter: DoubleEndedIterator {
1628     /// Marks the underlying iterator as complete, extracting the remaining
1629     /// portion of the slice.
1630     fn finish(&mut self) -> Option<Self::Item>;
1631 }
1632
1633 /// An iterator over subslices separated by elements that match a predicate
1634 /// function.
1635 ///
1636 /// This struct is created by the [`split`] method on [slices].
1637 ///
1638 /// [`split`]: ../../std/primitive.slice.html#method.split
1639 /// [slices]: ../../std/primitive.slice.html
1640 #[stable(feature = "rust1", since = "1.0.0")]
1641 pub struct Split<'a, T:'a, P> where P: FnMut(&T) -> bool {
1642     v: &'a [T],
1643     pred: P,
1644     finished: bool
1645 }
1646
1647 #[stable(feature = "core_impl_debug", since = "1.9.0")]
1648 impl<'a, T: 'a + fmt::Debug, P> fmt::Debug for Split<'a, T, P> where P: FnMut(&T) -> bool {
1649     fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
1650         f.debug_struct("Split")
1651             .field("v", &self.v)
1652             .field("finished", &self.finished)
1653             .finish()
1654     }
1655 }
1656
1657 // FIXME(#26925) Remove in favor of `#[derive(Clone)]`
1658 #[stable(feature = "rust1", since = "1.0.0")]
1659 impl<'a, T, P> Clone for Split<'a, T, P> where P: Clone + FnMut(&T) -> bool {
1660     fn clone(&self) -> Split<'a, T, P> {
1661         Split {
1662             v: self.v,
1663             pred: self.pred.clone(),
1664             finished: self.finished,
1665         }
1666     }
1667 }
1668
1669 #[stable(feature = "rust1", since = "1.0.0")]
1670 impl<'a, T, P> Iterator for Split<'a, T, P> where P: FnMut(&T) -> bool {
1671     type Item = &'a [T];
1672
1673     #[inline]
1674     fn next(&mut self) -> Option<&'a [T]> {
1675         if self.finished { return None; }
1676
1677         match self.v.iter().position(|x| (self.pred)(x)) {
1678             None => self.finish(),
1679             Some(idx) => {
1680                 let ret = Some(&self.v[..idx]);
1681                 self.v = &self.v[idx + 1..];
1682                 ret
1683             }
1684         }
1685     }
1686
1687     #[inline]
1688     fn size_hint(&self) -> (usize, Option<usize>) {
1689         if self.finished {
1690             (0, Some(0))
1691         } else {
1692             (1, Some(self.v.len() + 1))
1693         }
1694     }
1695 }
1696
1697 #[stable(feature = "rust1", since = "1.0.0")]
1698 impl<'a, T, P> DoubleEndedIterator for Split<'a, T, P> where P: FnMut(&T) -> bool {
1699     #[inline]
1700     fn next_back(&mut self) -> Option<&'a [T]> {
1701         if self.finished { return None; }
1702
1703         match self.v.iter().rposition(|x| (self.pred)(x)) {
1704             None => self.finish(),
1705             Some(idx) => {
1706                 let ret = Some(&self.v[idx + 1..]);
1707                 self.v = &self.v[..idx];
1708                 ret
1709             }
1710         }
1711     }
1712 }
1713
1714 impl<'a, T, P> SplitIter for Split<'a, T, P> where P: FnMut(&T) -> bool {
1715     #[inline]
1716     fn finish(&mut self) -> Option<&'a [T]> {
1717         if self.finished { None } else { self.finished = true; Some(self.v) }
1718     }
1719 }
1720
1721 #[unstable(feature = "fused", issue = "35602")]
1722 impl<'a, T, P> FusedIterator for Split<'a, T, P> where P: FnMut(&T) -> bool {}
1723
1724 /// An iterator over the subslices of the vector which are separated
1725 /// by elements that match `pred`.
1726 ///
1727 /// This struct is created by the [`split_mut`] method on [slices].
1728 ///
1729 /// [`split_mut`]: ../../std/primitive.slice.html#method.split_mut
1730 /// [slices]: ../../std/primitive.slice.html
1731 #[stable(feature = "rust1", since = "1.0.0")]
1732 pub struct SplitMut<'a, T:'a, P> where P: FnMut(&T) -> bool {
1733     v: &'a mut [T],
1734     pred: P,
1735     finished: bool
1736 }
1737
1738 #[stable(feature = "core_impl_debug", since = "1.9.0")]
1739 impl<'a, T: 'a + fmt::Debug, P> fmt::Debug for SplitMut<'a, T, P> where P: FnMut(&T) -> bool {
1740     fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
1741         f.debug_struct("SplitMut")
1742             .field("v", &self.v)
1743             .field("finished", &self.finished)
1744             .finish()
1745     }
1746 }
1747
1748 impl<'a, T, P> SplitIter for SplitMut<'a, T, P> where P: FnMut(&T) -> bool {
1749     #[inline]
1750     fn finish(&mut self) -> Option<&'a mut [T]> {
1751         if self.finished {
1752             None
1753         } else {
1754             self.finished = true;
1755             Some(mem::replace(&mut self.v, &mut []))
1756         }
1757     }
1758 }
1759
1760 #[stable(feature = "rust1", since = "1.0.0")]
1761 impl<'a, T, P> Iterator for SplitMut<'a, T, P> where P: FnMut(&T) -> bool {
1762     type Item = &'a mut [T];
1763
1764     #[inline]
1765     fn next(&mut self) -> Option<&'a mut [T]> {
1766         if self.finished { return None; }
1767
1768         let idx_opt = { // work around borrowck limitations
1769             let pred = &mut self.pred;
1770             self.v.iter().position(|x| (*pred)(x))
1771         };
1772         match idx_opt {
1773             None => self.finish(),
1774             Some(idx) => {
1775                 let tmp = mem::replace(&mut self.v, &mut []);
1776                 let (head, tail) = tmp.split_at_mut(idx);
1777                 self.v = &mut tail[1..];
1778                 Some(head)
1779             }
1780         }
1781     }
1782
1783     #[inline]
1784     fn size_hint(&self) -> (usize, Option<usize>) {
1785         if self.finished {
1786             (0, Some(0))
1787         } else {
1788             // if the predicate doesn't match anything, we yield one slice
1789             // if it matches every element, we yield len+1 empty slices.
1790             (1, Some(self.v.len() + 1))
1791         }
1792     }
1793 }
1794
1795 #[stable(feature = "rust1", since = "1.0.0")]
1796 impl<'a, T, P> DoubleEndedIterator for SplitMut<'a, T, P> where
1797     P: FnMut(&T) -> bool,
1798 {
1799     #[inline]
1800     fn next_back(&mut self) -> Option<&'a mut [T]> {
1801         if self.finished { return None; }
1802
1803         let idx_opt = { // work around borrowck limitations
1804             let pred = &mut self.pred;
1805             self.v.iter().rposition(|x| (*pred)(x))
1806         };
1807         match idx_opt {
1808             None => self.finish(),
1809             Some(idx) => {
1810                 let tmp = mem::replace(&mut self.v, &mut []);
1811                 let (head, tail) = tmp.split_at_mut(idx);
1812                 self.v = head;
1813                 Some(&mut tail[1..])
1814             }
1815         }
1816     }
1817 }
1818
1819 #[unstable(feature = "fused", issue = "35602")]
1820 impl<'a, T, P> FusedIterator for SplitMut<'a, T, P> where P: FnMut(&T) -> bool {}
1821
1822 /// An iterator over subslices separated by elements that match a predicate
1823 /// function, starting from the end of the slice.
1824 ///
1825 /// This struct is created by the [`rsplit`] method on [slices].
1826 ///
1827 /// [`rsplit`]: ../../std/primitive.slice.html#method.rsplit
1828 /// [slices]: ../../std/primitive.slice.html
1829 #[unstable(feature = "slice_rsplit", issue = "41020")]
1830 #[derive(Clone)] // Is this correct, or does it incorrectly require `T: Clone`?
1831 pub struct RSplit<'a, T:'a, P> where P: FnMut(&T) -> bool {
1832     inner: Split<'a, T, P>
1833 }
1834
1835 #[unstable(feature = "slice_rsplit", issue = "41020")]
1836 impl<'a, T: 'a + fmt::Debug, P> fmt::Debug for RSplit<'a, T, P> where P: FnMut(&T) -> bool {
1837     fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
1838         f.debug_struct("RSplit")
1839             .field("v", &self.inner.v)
1840             .field("finished", &self.inner.finished)
1841             .finish()
1842     }
1843 }
1844
1845 #[unstable(feature = "slice_rsplit", issue = "41020")]
1846 impl<'a, T, P> Iterator for RSplit<'a, T, P> where P: FnMut(&T) -> bool {
1847     type Item = &'a [T];
1848
1849     #[inline]
1850     fn next(&mut self) -> Option<&'a [T]> {
1851         self.inner.next_back()
1852     }
1853
1854     #[inline]
1855     fn size_hint(&self) -> (usize, Option<usize>) {
1856         self.inner.size_hint()
1857     }
1858 }
1859
1860 #[unstable(feature = "slice_rsplit", issue = "41020")]
1861 impl<'a, T, P> DoubleEndedIterator for RSplit<'a, T, P> where P: FnMut(&T) -> bool {
1862     #[inline]
1863     fn next_back(&mut self) -> Option<&'a [T]> {
1864         self.inner.next()
1865     }
1866 }
1867
1868 #[unstable(feature = "slice_rsplit", issue = "41020")]
1869 impl<'a, T, P> SplitIter for RSplit<'a, T, P> where P: FnMut(&T) -> bool {
1870     #[inline]
1871     fn finish(&mut self) -> Option<&'a [T]> {
1872         self.inner.finish()
1873     }
1874 }
1875
1876 //#[unstable(feature = "fused", issue = "35602")]
1877 #[unstable(feature = "slice_rsplit", issue = "41020")]
1878 impl<'a, T, P> FusedIterator for RSplit<'a, T, P> where P: FnMut(&T) -> bool {}
1879
1880 /// An iterator over the subslices of the vector which are separated
1881 /// by elements that match `pred`, starting from the end of the slice.
1882 ///
1883 /// This struct is created by the [`rsplit_mut`] method on [slices].
1884 ///
1885 /// [`rsplit_mut`]: ../../std/primitive.slice.html#method.rsplit_mut
1886 /// [slices]: ../../std/primitive.slice.html
1887 #[unstable(feature = "slice_rsplit", issue = "41020")]
1888 pub struct RSplitMut<'a, T:'a, P> where P: FnMut(&T) -> bool {
1889     inner: SplitMut<'a, T, P>
1890 }
1891
1892 #[unstable(feature = "slice_rsplit", issue = "41020")]
1893 impl<'a, T: 'a + fmt::Debug, P> fmt::Debug for RSplitMut<'a, T, P> where P: FnMut(&T) -> bool {
1894     fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
1895         f.debug_struct("RSplitMut")
1896             .field("v", &self.inner.v)
1897             .field("finished", &self.inner.finished)
1898             .finish()
1899     }
1900 }
1901
1902 #[unstable(feature = "slice_rsplit", issue = "41020")]
1903 impl<'a, T, P> SplitIter for RSplitMut<'a, T, P> where P: FnMut(&T) -> bool {
1904     #[inline]
1905     fn finish(&mut self) -> Option<&'a mut [T]> {
1906         self.inner.finish()
1907     }
1908 }
1909
1910 #[unstable(feature = "slice_rsplit", issue = "41020")]
1911 impl<'a, T, P> Iterator for RSplitMut<'a, T, P> where P: FnMut(&T) -> bool {
1912     type Item = &'a mut [T];
1913
1914     #[inline]
1915     fn next(&mut self) -> Option<&'a mut [T]> {
1916         self.inner.next_back()
1917     }
1918
1919     #[inline]
1920     fn size_hint(&self) -> (usize, Option<usize>) {
1921         self.inner.size_hint()
1922     }
1923 }
1924
1925 #[unstable(feature = "slice_rsplit", issue = "41020")]
1926 impl<'a, T, P> DoubleEndedIterator for RSplitMut<'a, T, P> where
1927     P: FnMut(&T) -> bool,
1928 {
1929     #[inline]
1930     fn next_back(&mut self) -> Option<&'a mut [T]> {
1931         self.inner.next()
1932     }
1933 }
1934
1935 //#[unstable(feature = "fused", issue = "35602")]
1936 #[unstable(feature = "slice_rsplit", issue = "41020")]
1937 impl<'a, T, P> FusedIterator for RSplitMut<'a, T, P> where P: FnMut(&T) -> bool {}
1938
1939 /// An private iterator over subslices separated by elements that
1940 /// match a predicate function, splitting at most a fixed number of
1941 /// times.
1942 #[derive(Debug)]
1943 struct GenericSplitN<I> {
1944     iter: I,
1945     count: usize,
1946 }
1947
1948 impl<T, I: SplitIter<Item=T>> Iterator for GenericSplitN<I> {
1949     type Item = T;
1950
1951     #[inline]
1952     fn next(&mut self) -> Option<T> {
1953         match self.count {
1954             0 => None,
1955             1 => { self.count -= 1; self.iter.finish() }
1956             _ => { self.count -= 1; self.iter.next() }
1957         }
1958     }
1959
1960     #[inline]
1961     fn size_hint(&self) -> (usize, Option<usize>) {
1962         let (lower, upper_opt) = self.iter.size_hint();
1963         (lower, upper_opt.map(|upper| cmp::min(self.count, upper)))
1964     }
1965 }
1966
1967 /// An iterator over subslices separated by elements that match a predicate
1968 /// function, limited to a given number of splits.
1969 ///
1970 /// This struct is created by the [`splitn`] method on [slices].
1971 ///
1972 /// [`splitn`]: ../../std/primitive.slice.html#method.splitn
1973 /// [slices]: ../../std/primitive.slice.html
1974 #[stable(feature = "rust1", since = "1.0.0")]
1975 pub struct SplitN<'a, T: 'a, P> where P: FnMut(&T) -> bool {
1976     inner: GenericSplitN<Split<'a, T, P>>
1977 }
1978
1979 #[stable(feature = "core_impl_debug", since = "1.9.0")]
1980 impl<'a, T: 'a + fmt::Debug, P> fmt::Debug for SplitN<'a, T, P> where P: FnMut(&T) -> bool {
1981     fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
1982         f.debug_struct("SplitN")
1983             .field("inner", &self.inner)
1984             .finish()
1985     }
1986 }
1987
1988 /// An iterator over subslices separated by elements that match a
1989 /// predicate function, limited to a given number of splits, starting
1990 /// from the end of the slice.
1991 ///
1992 /// This struct is created by the [`rsplitn`] method on [slices].
1993 ///
1994 /// [`rsplitn`]: ../../std/primitive.slice.html#method.rsplitn
1995 /// [slices]: ../../std/primitive.slice.html
1996 #[stable(feature = "rust1", since = "1.0.0")]
1997 pub struct RSplitN<'a, T: 'a, P> where P: FnMut(&T) -> bool {
1998     inner: GenericSplitN<RSplit<'a, T, P>>
1999 }
2000
2001 #[stable(feature = "core_impl_debug", since = "1.9.0")]
2002 impl<'a, T: 'a + fmt::Debug, P> fmt::Debug for RSplitN<'a, T, P> where P: FnMut(&T) -> bool {
2003     fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
2004         f.debug_struct("RSplitN")
2005             .field("inner", &self.inner)
2006             .finish()
2007     }
2008 }
2009
2010 /// An iterator over subslices separated by elements that match a predicate
2011 /// function, limited to a given number of splits.
2012 ///
2013 /// This struct is created by the [`splitn_mut`] method on [slices].
2014 ///
2015 /// [`splitn_mut`]: ../../std/primitive.slice.html#method.splitn_mut
2016 /// [slices]: ../../std/primitive.slice.html
2017 #[stable(feature = "rust1", since = "1.0.0")]
2018 pub struct SplitNMut<'a, T: 'a, P> where P: FnMut(&T) -> bool {
2019     inner: GenericSplitN<SplitMut<'a, T, P>>
2020 }
2021
2022 #[stable(feature = "core_impl_debug", since = "1.9.0")]
2023 impl<'a, T: 'a + fmt::Debug, P> fmt::Debug for SplitNMut<'a, T, P> where P: FnMut(&T) -> bool {
2024     fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
2025         f.debug_struct("SplitNMut")
2026             .field("inner", &self.inner)
2027             .finish()
2028     }
2029 }
2030
2031 /// An iterator over subslices separated by elements that match a
2032 /// predicate function, limited to a given number of splits, starting
2033 /// from the end of the slice.
2034 ///
2035 /// This struct is created by the [`rsplitn_mut`] method on [slices].
2036 ///
2037 /// [`rsplitn_mut`]: ../../std/primitive.slice.html#method.rsplitn_mut
2038 /// [slices]: ../../std/primitive.slice.html
2039 #[stable(feature = "rust1", since = "1.0.0")]
2040 pub struct RSplitNMut<'a, T: 'a, P> where P: FnMut(&T) -> bool {
2041     inner: GenericSplitN<RSplitMut<'a, T, P>>
2042 }
2043
2044 #[stable(feature = "core_impl_debug", since = "1.9.0")]
2045 impl<'a, T: 'a + fmt::Debug, P> fmt::Debug for RSplitNMut<'a, T, P> where P: FnMut(&T) -> bool {
2046     fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
2047         f.debug_struct("RSplitNMut")
2048             .field("inner", &self.inner)
2049             .finish()
2050     }
2051 }
2052
2053 macro_rules! forward_iterator {
2054     ($name:ident: $elem:ident, $iter_of:ty) => {
2055         #[stable(feature = "rust1", since = "1.0.0")]
2056         impl<'a, $elem, P> Iterator for $name<'a, $elem, P> where
2057             P: FnMut(&T) -> bool
2058         {
2059             type Item = $iter_of;
2060
2061             #[inline]
2062             fn next(&mut self) -> Option<$iter_of> {
2063                 self.inner.next()
2064             }
2065
2066             #[inline]
2067             fn size_hint(&self) -> (usize, Option<usize>) {
2068                 self.inner.size_hint()
2069             }
2070         }
2071
2072         #[unstable(feature = "fused", issue = "35602")]
2073         impl<'a, $elem, P> FusedIterator for $name<'a, $elem, P>
2074             where P: FnMut(&T) -> bool {}
2075     }
2076 }
2077
2078 forward_iterator! { SplitN: T, &'a [T] }
2079 forward_iterator! { RSplitN: T, &'a [T] }
2080 forward_iterator! { SplitNMut: T, &'a mut [T] }
2081 forward_iterator! { RSplitNMut: T, &'a mut [T] }
2082
2083 /// An iterator over overlapping subslices of length `size`.
2084 ///
2085 /// This struct is created by the [`windows`] method on [slices].
2086 ///
2087 /// [`windows`]: ../../std/primitive.slice.html#method.windows
2088 /// [slices]: ../../std/primitive.slice.html
2089 #[derive(Debug)]
2090 #[stable(feature = "rust1", since = "1.0.0")]
2091 pub struct Windows<'a, T:'a> {
2092     v: &'a [T],
2093     size: usize
2094 }
2095
2096 // FIXME(#26925) Remove in favor of `#[derive(Clone)]`
2097 #[stable(feature = "rust1", since = "1.0.0")]
2098 impl<'a, T> Clone for Windows<'a, T> {
2099     fn clone(&self) -> Windows<'a, T> {
2100         Windows {
2101             v: self.v,
2102             size: self.size,
2103         }
2104     }
2105 }
2106
2107 #[stable(feature = "rust1", since = "1.0.0")]
2108 impl<'a, T> Iterator for Windows<'a, T> {
2109     type Item = &'a [T];
2110
2111     #[inline]
2112     fn next(&mut self) -> Option<&'a [T]> {
2113         if self.size > self.v.len() {
2114             None
2115         } else {
2116             let ret = Some(&self.v[..self.size]);
2117             self.v = &self.v[1..];
2118             ret
2119         }
2120     }
2121
2122     #[inline]
2123     fn size_hint(&self) -> (usize, Option<usize>) {
2124         if self.size > self.v.len() {
2125             (0, Some(0))
2126         } else {
2127             let size = self.v.len() - self.size + 1;
2128             (size, Some(size))
2129         }
2130     }
2131
2132     #[inline]
2133     fn count(self) -> usize {
2134         self.len()
2135     }
2136
2137     #[inline]
2138     fn nth(&mut self, n: usize) -> Option<Self::Item> {
2139         let (end, overflow) = self.size.overflowing_add(n);
2140         if end > self.v.len() || overflow {
2141             self.v = &[];
2142             None
2143         } else {
2144             let nth = &self.v[n..end];
2145             self.v = &self.v[n+1..];
2146             Some(nth)
2147         }
2148     }
2149
2150     #[inline]
2151     fn last(self) -> Option<Self::Item> {
2152         if self.size > self.v.len() {
2153             None
2154         } else {
2155             let start = self.v.len() - self.size;
2156             Some(&self.v[start..])
2157         }
2158     }
2159 }
2160
2161 #[stable(feature = "rust1", since = "1.0.0")]
2162 impl<'a, T> DoubleEndedIterator for Windows<'a, T> {
2163     #[inline]
2164     fn next_back(&mut self) -> Option<&'a [T]> {
2165         if self.size > self.v.len() {
2166             None
2167         } else {
2168             let ret = Some(&self.v[self.v.len()-self.size..]);
2169             self.v = &self.v[..self.v.len()-1];
2170             ret
2171         }
2172     }
2173 }
2174
2175 #[stable(feature = "rust1", since = "1.0.0")]
2176 impl<'a, T> ExactSizeIterator for Windows<'a, T> {}
2177
2178 #[unstable(feature = "fused", issue = "35602")]
2179 impl<'a, T> FusedIterator for Windows<'a, T> {}
2180
2181 /// An iterator over a slice in (non-overlapping) chunks (`size` elements at a
2182 /// time).
2183 ///
2184 /// When the slice len is not evenly divided by the chunk size, the last slice
2185 /// of the iteration will be the remainder.
2186 ///
2187 /// This struct is created by the [`chunks`] method on [slices].
2188 ///
2189 /// [`chunks`]: ../../std/primitive.slice.html#method.chunks
2190 /// [slices]: ../../std/primitive.slice.html
2191 #[derive(Debug)]
2192 #[stable(feature = "rust1", since = "1.0.0")]
2193 pub struct Chunks<'a, T:'a> {
2194     v: &'a [T],
2195     size: usize
2196 }
2197
2198 // FIXME(#26925) Remove in favor of `#[derive(Clone)]`
2199 #[stable(feature = "rust1", since = "1.0.0")]
2200 impl<'a, T> Clone for Chunks<'a, T> {
2201     fn clone(&self) -> Chunks<'a, T> {
2202         Chunks {
2203             v: self.v,
2204             size: self.size,
2205         }
2206     }
2207 }
2208
2209 #[stable(feature = "rust1", since = "1.0.0")]
2210 impl<'a, T> Iterator for Chunks<'a, T> {
2211     type Item = &'a [T];
2212
2213     #[inline]
2214     fn next(&mut self) -> Option<&'a [T]> {
2215         if self.v.is_empty() {
2216             None
2217         } else {
2218             let chunksz = cmp::min(self.v.len(), self.size);
2219             let (fst, snd) = self.v.split_at(chunksz);
2220             self.v = snd;
2221             Some(fst)
2222         }
2223     }
2224
2225     #[inline]
2226     fn size_hint(&self) -> (usize, Option<usize>) {
2227         if self.v.is_empty() {
2228             (0, Some(0))
2229         } else {
2230             let n = self.v.len() / self.size;
2231             let rem = self.v.len() % self.size;
2232             let n = if rem > 0 { n+1 } else { n };
2233             (n, Some(n))
2234         }
2235     }
2236
2237     #[inline]
2238     fn count(self) -> usize {
2239         self.len()
2240     }
2241
2242     #[inline]
2243     fn nth(&mut self, n: usize) -> Option<Self::Item> {
2244         let (start, overflow) = n.overflowing_mul(self.size);
2245         if start >= self.v.len() || overflow {
2246             self.v = &[];
2247             None
2248         } else {
2249             let end = match start.checked_add(self.size) {
2250                 Some(sum) => cmp::min(self.v.len(), sum),
2251                 None => self.v.len(),
2252             };
2253             let nth = &self.v[start..end];
2254             self.v = &self.v[end..];
2255             Some(nth)
2256         }
2257     }
2258
2259     #[inline]
2260     fn last(self) -> Option<Self::Item> {
2261         if self.v.is_empty() {
2262             None
2263         } else {
2264             let start = (self.v.len() - 1) / self.size * self.size;
2265             Some(&self.v[start..])
2266         }
2267     }
2268 }
2269
2270 #[stable(feature = "rust1", since = "1.0.0")]
2271 impl<'a, T> DoubleEndedIterator for Chunks<'a, T> {
2272     #[inline]
2273     fn next_back(&mut self) -> Option<&'a [T]> {
2274         if self.v.is_empty() {
2275             None
2276         } else {
2277             let remainder = self.v.len() % self.size;
2278             let chunksz = if remainder != 0 { remainder } else { self.size };
2279             let (fst, snd) = self.v.split_at(self.v.len() - chunksz);
2280             self.v = fst;
2281             Some(snd)
2282         }
2283     }
2284 }
2285
2286 #[stable(feature = "rust1", since = "1.0.0")]
2287 impl<'a, T> ExactSizeIterator for Chunks<'a, T> {}
2288
2289 #[unstable(feature = "fused", issue = "35602")]
2290 impl<'a, T> FusedIterator for Chunks<'a, T> {}
2291
2292 /// An iterator over a slice in (non-overlapping) mutable chunks (`size`
2293 /// elements at a time). When the slice len is not evenly divided by the chunk
2294 /// size, the last slice of the iteration will be the remainder.
2295 ///
2296 /// This struct is created by the [`chunks_mut`] method on [slices].
2297 ///
2298 /// [`chunks_mut`]: ../../std/primitive.slice.html#method.chunks_mut
2299 /// [slices]: ../../std/primitive.slice.html
2300 #[derive(Debug)]
2301 #[stable(feature = "rust1", since = "1.0.0")]
2302 pub struct ChunksMut<'a, T:'a> {
2303     v: &'a mut [T],
2304     chunk_size: usize
2305 }
2306
2307 #[stable(feature = "rust1", since = "1.0.0")]
2308 impl<'a, T> Iterator for ChunksMut<'a, T> {
2309     type Item = &'a mut [T];
2310
2311     #[inline]
2312     fn next(&mut self) -> Option<&'a mut [T]> {
2313         if self.v.is_empty() {
2314             None
2315         } else {
2316             let sz = cmp::min(self.v.len(), self.chunk_size);
2317             let tmp = mem::replace(&mut self.v, &mut []);
2318             let (head, tail) = tmp.split_at_mut(sz);
2319             self.v = tail;
2320             Some(head)
2321         }
2322     }
2323
2324     #[inline]
2325     fn size_hint(&self) -> (usize, Option<usize>) {
2326         if self.v.is_empty() {
2327             (0, Some(0))
2328         } else {
2329             let n = self.v.len() / self.chunk_size;
2330             let rem = self.v.len() % self.chunk_size;
2331             let n = if rem > 0 { n + 1 } else { n };
2332             (n, Some(n))
2333         }
2334     }
2335
2336     #[inline]
2337     fn count(self) -> usize {
2338         self.len()
2339     }
2340
2341     #[inline]
2342     fn nth(&mut self, n: usize) -> Option<&'a mut [T]> {
2343         let (start, overflow) = n.overflowing_mul(self.chunk_size);
2344         if start >= self.v.len() || overflow {
2345             self.v = &mut [];
2346             None
2347         } else {
2348             let end = match start.checked_add(self.chunk_size) {
2349                 Some(sum) => cmp::min(self.v.len(), sum),
2350                 None => self.v.len(),
2351             };
2352             let tmp = mem::replace(&mut self.v, &mut []);
2353             let (head, tail) = tmp.split_at_mut(end);
2354             let (_, nth) =  head.split_at_mut(start);
2355             self.v = tail;
2356             Some(nth)
2357         }
2358     }
2359
2360     #[inline]
2361     fn last(self) -> Option<Self::Item> {
2362         if self.v.is_empty() {
2363             None
2364         } else {
2365             let start = (self.v.len() - 1) / self.chunk_size * self.chunk_size;
2366             Some(&mut self.v[start..])
2367         }
2368     }
2369 }
2370
2371 #[stable(feature = "rust1", since = "1.0.0")]
2372 impl<'a, T> DoubleEndedIterator for ChunksMut<'a, T> {
2373     #[inline]
2374     fn next_back(&mut self) -> Option<&'a mut [T]> {
2375         if self.v.is_empty() {
2376             None
2377         } else {
2378             let remainder = self.v.len() % self.chunk_size;
2379             let sz = if remainder != 0 { remainder } else { self.chunk_size };
2380             let tmp = mem::replace(&mut self.v, &mut []);
2381             let tmp_len = tmp.len();
2382             let (head, tail) = tmp.split_at_mut(tmp_len - sz);
2383             self.v = head;
2384             Some(tail)
2385         }
2386     }
2387 }
2388
2389 #[stable(feature = "rust1", since = "1.0.0")]
2390 impl<'a, T> ExactSizeIterator for ChunksMut<'a, T> {}
2391
2392 #[unstable(feature = "fused", issue = "35602")]
2393 impl<'a, T> FusedIterator for ChunksMut<'a, T> {}
2394
2395 //
2396 // Free functions
2397 //
2398
2399 /// Forms a slice from a pointer and a length.
2400 ///
2401 /// The `len` argument is the number of **elements**, not the number of bytes.
2402 ///
2403 /// # Safety
2404 ///
2405 /// This function is unsafe as there is no guarantee that the given pointer is
2406 /// valid for `len` elements, nor whether the lifetime inferred is a suitable
2407 /// lifetime for the returned slice.
2408 ///
2409 /// `p` must be non-null, even for zero-length slices, because non-zero bits
2410 /// are required to distinguish between a zero-length slice within `Some()`
2411 /// from `None`. `p` can be a bogus non-dereferencable pointer, such as `0x1`,
2412 /// for zero-length slices, though.
2413 ///
2414 /// # Caveat
2415 ///
2416 /// The lifetime for the returned slice is inferred from its usage. To
2417 /// prevent accidental misuse, it's suggested to tie the lifetime to whichever
2418 /// source lifetime is safe in the context, such as by providing a helper
2419 /// function taking the lifetime of a host value for the slice, or by explicit
2420 /// annotation.
2421 ///
2422 /// # Examples
2423 ///
2424 /// ```
2425 /// use std::slice;
2426 ///
2427 /// // manifest a slice out of thin air!
2428 /// let ptr = 0x1234 as *const usize;
2429 /// let amt = 10;
2430 /// unsafe {
2431 ///     let slice = slice::from_raw_parts(ptr, amt);
2432 /// }
2433 /// ```
2434 #[inline]
2435 #[stable(feature = "rust1", since = "1.0.0")]
2436 pub unsafe fn from_raw_parts<'a, T>(p: *const T, len: usize) -> &'a [T] {
2437     mem::transmute(Repr { data: p, len: len })
2438 }
2439
2440 /// Performs the same functionality as `from_raw_parts`, except that a mutable
2441 /// slice is returned.
2442 ///
2443 /// This function is unsafe for the same reasons as `from_raw_parts`, as well
2444 /// as not being able to provide a non-aliasing guarantee of the returned
2445 /// mutable slice. `p` must be non-null even for zero-length slices as with
2446 /// `from_raw_parts`.
2447 #[inline]
2448 #[stable(feature = "rust1", since = "1.0.0")]
2449 pub unsafe fn from_raw_parts_mut<'a, T>(p: *mut T, len: usize) -> &'a mut [T] {
2450     mem::transmute(Repr { data: p, len: len })
2451 }
2452
2453 // This function is public only because there is no other way to unit test heapsort.
2454 #[unstable(feature = "sort_internals", reason = "internal to sort module", issue = "0")]
2455 #[doc(hidden)]
2456 pub fn heapsort<T, F>(v: &mut [T], mut is_less: F)
2457     where F: FnMut(&T, &T) -> bool
2458 {
2459     sort::heapsort(v, &mut is_less);
2460 }
2461
2462 //
2463 // Comparison traits
2464 //
2465
2466 extern {
2467     /// Calls implementation provided memcmp.
2468     ///
2469     /// Interprets the data as u8.
2470     ///
2471     /// Returns 0 for equal, < 0 for less than and > 0 for greater
2472     /// than.
2473     // FIXME(#32610): Return type should be c_int
2474     fn memcmp(s1: *const u8, s2: *const u8, n: usize) -> i32;
2475 }
2476
2477 #[stable(feature = "rust1", since = "1.0.0")]
2478 impl<A, B> PartialEq<[B]> for [A] where A: PartialEq<B> {
2479     fn eq(&self, other: &[B]) -> bool {
2480         SlicePartialEq::equal(self, other)
2481     }
2482
2483     fn ne(&self, other: &[B]) -> bool {
2484         SlicePartialEq::not_equal(self, other)
2485     }
2486 }
2487
2488 #[stable(feature = "rust1", since = "1.0.0")]
2489 impl<T: Eq> Eq for [T] {}
2490
2491 /// Implements comparison of vectors lexicographically.
2492 #[stable(feature = "rust1", since = "1.0.0")]
2493 impl<T: Ord> Ord for [T] {
2494     fn cmp(&self, other: &[T]) -> Ordering {
2495         SliceOrd::compare(self, other)
2496     }
2497 }
2498
2499 /// Implements comparison of vectors lexicographically.
2500 #[stable(feature = "rust1", since = "1.0.0")]
2501 impl<T: PartialOrd> PartialOrd for [T] {
2502     fn partial_cmp(&self, other: &[T]) -> Option<Ordering> {
2503         SlicePartialOrd::partial_compare(self, other)
2504     }
2505 }
2506
2507 #[doc(hidden)]
2508 // intermediate trait for specialization of slice's PartialEq
2509 trait SlicePartialEq<B> {
2510     fn equal(&self, other: &[B]) -> bool;
2511
2512     fn not_equal(&self, other: &[B]) -> bool { !self.equal(other) }
2513 }
2514
2515 // Generic slice equality
2516 impl<A, B> SlicePartialEq<B> for [A]
2517     where A: PartialEq<B>
2518 {
2519     default fn equal(&self, other: &[B]) -> bool {
2520         if self.len() != other.len() {
2521             return false;
2522         }
2523
2524         for i in 0..self.len() {
2525             if !self[i].eq(&other[i]) {
2526                 return false;
2527             }
2528         }
2529
2530         true
2531     }
2532 }
2533
2534 // Use memcmp for bytewise equality when the types allow
2535 impl<A> SlicePartialEq<A> for [A]
2536     where A: PartialEq<A> + BytewiseEquality
2537 {
2538     fn equal(&self, other: &[A]) -> bool {
2539         if self.len() != other.len() {
2540             return false;
2541         }
2542         if self.as_ptr() == other.as_ptr() {
2543             return true;
2544         }
2545         unsafe {
2546             let size = mem::size_of_val(self);
2547             memcmp(self.as_ptr() as *const u8,
2548                    other.as_ptr() as *const u8, size) == 0
2549         }
2550     }
2551 }
2552
2553 #[doc(hidden)]
2554 // intermediate trait for specialization of slice's PartialOrd
2555 trait SlicePartialOrd<B> {
2556     fn partial_compare(&self, other: &[B]) -> Option<Ordering>;
2557 }
2558
2559 impl<A> SlicePartialOrd<A> for [A]
2560     where A: PartialOrd
2561 {
2562     default fn partial_compare(&self, other: &[A]) -> Option<Ordering> {
2563         let l = cmp::min(self.len(), other.len());
2564
2565         // Slice to the loop iteration range to enable bound check
2566         // elimination in the compiler
2567         let lhs = &self[..l];
2568         let rhs = &other[..l];
2569
2570         for i in 0..l {
2571             match lhs[i].partial_cmp(&rhs[i]) {
2572                 Some(Ordering::Equal) => (),
2573                 non_eq => return non_eq,
2574             }
2575         }
2576
2577         self.len().partial_cmp(&other.len())
2578     }
2579 }
2580
2581 impl<A> SlicePartialOrd<A> for [A]
2582     where A: Ord
2583 {
2584     default fn partial_compare(&self, other: &[A]) -> Option<Ordering> {
2585         Some(SliceOrd::compare(self, other))
2586     }
2587 }
2588
2589 #[doc(hidden)]
2590 // intermediate trait for specialization of slice's Ord
2591 trait SliceOrd<B> {
2592     fn compare(&self, other: &[B]) -> Ordering;
2593 }
2594
2595 impl<A> SliceOrd<A> for [A]
2596     where A: Ord
2597 {
2598     default fn compare(&self, other: &[A]) -> Ordering {
2599         let l = cmp::min(self.len(), other.len());
2600
2601         // Slice to the loop iteration range to enable bound check
2602         // elimination in the compiler
2603         let lhs = &self[..l];
2604         let rhs = &other[..l];
2605
2606         for i in 0..l {
2607             match lhs[i].cmp(&rhs[i]) {
2608                 Ordering::Equal => (),
2609                 non_eq => return non_eq,
2610             }
2611         }
2612
2613         self.len().cmp(&other.len())
2614     }
2615 }
2616
2617 // memcmp compares a sequence of unsigned bytes lexicographically.
2618 // this matches the order we want for [u8], but no others (not even [i8]).
2619 impl SliceOrd<u8> for [u8] {
2620     #[inline]
2621     fn compare(&self, other: &[u8]) -> Ordering {
2622         let order = unsafe {
2623             memcmp(self.as_ptr(), other.as_ptr(),
2624                    cmp::min(self.len(), other.len()))
2625         };
2626         if order == 0 {
2627             self.len().cmp(&other.len())
2628         } else if order < 0 {
2629             Less
2630         } else {
2631             Greater
2632         }
2633     }
2634 }
2635
2636 #[doc(hidden)]
2637 /// Trait implemented for types that can be compared for equality using
2638 /// their bytewise representation
2639 trait BytewiseEquality { }
2640
2641 macro_rules! impl_marker_for {
2642     ($traitname:ident, $($ty:ty)*) => {
2643         $(
2644             impl $traitname for $ty { }
2645         )*
2646     }
2647 }
2648
2649 impl_marker_for!(BytewiseEquality,
2650                  u8 i8 u16 i16 u32 i32 u64 i64 usize isize char bool);
2651
2652 #[doc(hidden)]
2653 unsafe impl<'a, T> TrustedRandomAccess for Iter<'a, T> {
2654     unsafe fn get_unchecked(&mut self, i: usize) -> &'a T {
2655         &*self.ptr.offset(i as isize)
2656     }
2657     fn may_have_side_effect() -> bool { false }
2658 }
2659
2660 #[doc(hidden)]
2661 unsafe impl<'a, T> TrustedRandomAccess for IterMut<'a, T> {
2662     unsafe fn get_unchecked(&mut self, i: usize) -> &'a mut T {
2663         &mut *self.ptr.offset(i as isize)
2664     }
2665     fn may_have_side_effect() -> bool { false }
2666 }