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