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