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