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