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