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