]> git.lizzy.rs Git - rust.git/blob - src/libcore/slice.rs
77fc0e7159f1606793d060a36d679963711bde6d
[rust.git] / src / libcore / slice.rs
1 // Copyright 2012-2014 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 `std::slice`.
14
15 #![stable(feature = "rust1", since = "1.0.0")]
16
17 // How this module is organized.
18 //
19 // The library infrastructure for slices is fairly messy. There's
20 // a lot of stuff defined here. Let's keep it clean.
21 //
22 // Since slices don't support inherent methods; all operations
23 // on them are defined on traits, which are then reexported from
24 // the prelude for convenience. So there are a lot of traits here.
25 //
26 // The layout of this file is thus:
27 //
28 // * Slice-specific 'extension' traits and their implementations. This
29 //   is where most of the slice API resides.
30 // * Implementations of a few common traits with important slice ops.
31 // * Definitions of a bunch of iterators.
32 // * Free functions.
33 // * The `raw` and `bytes` submodules.
34 // * Boilerplate trait implementations.
35
36 use clone::Clone;
37 use cmp::{Ordering, PartialEq, PartialOrd, Eq, Ord};
38 use cmp::Ordering::{Less, Equal, Greater};
39 use cmp;
40 use default::Default;
41 use intrinsics::assume;
42 use iter::*;
43 use ops::{FnMut, self, Index};
44 use ops::RangeFull;
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, self};
52 use raw::Repr;
53 // Avoid conflicts with *both* the Slice trait (buggy) and the `slice::raw` module.
54 use raw::Slice as RawSlice;
55
56
57 //
58 // Extension traits
59 //
60
61 /// Extension methods for slices.
62 #[unstable(feature = "core_slice_ext",
63            reason = "stable interface provided by `impl [T]` in later crates",
64            issue = "32110")]
65 #[allow(missing_docs)] // documented elsewhere
66 pub trait SliceExt {
67     type Item;
68
69     #[stable(feature = "core", since = "1.6.0")]
70     fn split_at(&self, mid: usize) -> (&[Self::Item], &[Self::Item]);
71     #[stable(feature = "core", since = "1.6.0")]
72     fn iter(&self) -> Iter<Self::Item>;
73     #[stable(feature = "core", since = "1.6.0")]
74     fn split<P>(&self, pred: P) -> Split<Self::Item, P>
75                     where P: FnMut(&Self::Item) -> bool;
76     #[stable(feature = "core", since = "1.6.0")]
77     fn splitn<P>(&self, n: usize, pred: P) -> SplitN<Self::Item, P>
78                      where P: FnMut(&Self::Item) -> bool;
79     #[stable(feature = "core", since = "1.6.0")]
80     fn rsplitn<P>(&self,  n: usize, pred: P) -> RSplitN<Self::Item, P>
81                       where P: FnMut(&Self::Item) -> bool;
82     #[stable(feature = "core", since = "1.6.0")]
83     fn windows(&self, size: usize) -> Windows<Self::Item>;
84     #[stable(feature = "core", since = "1.6.0")]
85     fn chunks(&self, size: usize) -> Chunks<Self::Item>;
86     #[stable(feature = "core", since = "1.6.0")]
87     fn get(&self, index: usize) -> Option<&Self::Item>;
88     #[stable(feature = "core", since = "1.6.0")]
89     fn first(&self) -> Option<&Self::Item>;
90     #[stable(feature = "core", since = "1.6.0")]
91     fn split_first(&self) -> Option<(&Self::Item, &[Self::Item])>;
92     #[stable(feature = "core", since = "1.6.0")]
93     fn split_last(&self) -> Option<(&Self::Item, &[Self::Item])>;
94     #[stable(feature = "core", since = "1.6.0")]
95     fn last(&self) -> Option<&Self::Item>;
96     #[stable(feature = "core", since = "1.6.0")]
97     unsafe fn get_unchecked(&self, index: usize) -> &Self::Item;
98     #[stable(feature = "core", since = "1.6.0")]
99     fn as_ptr(&self) -> *const Self::Item;
100     #[stable(feature = "core", since = "1.6.0")]
101     fn binary_search(&self, x: &Self::Item) -> Result<usize, usize>
102         where Self::Item: Ord;
103     #[stable(feature = "core", since = "1.6.0")]
104     fn binary_search_by<F>(&self, f: F) -> Result<usize, usize>
105         where F: FnMut(&Self::Item) -> Ordering;
106     #[stable(feature = "core", since = "1.6.0")]
107     fn len(&self) -> usize;
108     #[stable(feature = "core", since = "1.6.0")]
109     fn is_empty(&self) -> bool { self.len() == 0 }
110     #[stable(feature = "core", since = "1.6.0")]
111     fn get_mut(&mut self, index: usize) -> Option<&mut Self::Item>;
112     #[stable(feature = "core", since = "1.6.0")]
113     fn iter_mut(&mut self) -> IterMut<Self::Item>;
114     #[stable(feature = "core", since = "1.6.0")]
115     fn first_mut(&mut self) -> Option<&mut Self::Item>;
116     #[stable(feature = "core", since = "1.6.0")]
117     fn split_first_mut(&mut self) -> Option<(&mut Self::Item, &mut [Self::Item])>;
118     #[stable(feature = "core", since = "1.6.0")]
119     fn split_last_mut(&mut self) -> Option<(&mut Self::Item, &mut [Self::Item])>;
120     #[stable(feature = "core", since = "1.6.0")]
121     fn last_mut(&mut self) -> Option<&mut Self::Item>;
122     #[stable(feature = "core", since = "1.6.0")]
123     fn split_mut<P>(&mut self, pred: P) -> SplitMut<Self::Item, P>
124                         where P: FnMut(&Self::Item) -> bool;
125     #[stable(feature = "core", since = "1.6.0")]
126     fn splitn_mut<P>(&mut self, n: usize, pred: P) -> SplitNMut<Self::Item, P>
127                      where P: FnMut(&Self::Item) -> bool;
128     #[stable(feature = "core", since = "1.6.0")]
129     fn rsplitn_mut<P>(&mut self,  n: usize, pred: P) -> RSplitNMut<Self::Item, P>
130                       where P: FnMut(&Self::Item) -> bool;
131     #[stable(feature = "core", since = "1.6.0")]
132     fn chunks_mut(&mut self, chunk_size: usize) -> ChunksMut<Self::Item>;
133     #[stable(feature = "core", since = "1.6.0")]
134     fn swap(&mut self, a: usize, b: usize);
135     #[stable(feature = "core", since = "1.6.0")]
136     fn split_at_mut(&mut self, mid: usize) -> (&mut [Self::Item], &mut [Self::Item]);
137     #[stable(feature = "core", since = "1.6.0")]
138     fn reverse(&mut self);
139     #[stable(feature = "core", since = "1.6.0")]
140     unsafe fn get_unchecked_mut(&mut self, index: usize) -> &mut Self::Item;
141     #[stable(feature = "core", since = "1.6.0")]
142     fn as_mut_ptr(&mut self) -> *mut Self::Item;
143
144     #[stable(feature = "core", since = "1.6.0")]
145     fn contains(&self, x: &Self::Item) -> bool where Self::Item: PartialEq;
146
147     #[stable(feature = "core", since = "1.6.0")]
148     fn starts_with(&self, needle: &[Self::Item]) -> bool where Self::Item: PartialEq;
149
150     #[stable(feature = "core", since = "1.6.0")]
151     fn ends_with(&self, needle: &[Self::Item]) -> bool where Self::Item: PartialEq;
152
153     #[stable(feature = "clone_from_slice", since = "1.7.0")]
154     fn clone_from_slice(&mut self, &[Self::Item]) where Self::Item: Clone;
155     #[unstable(feature = "copy_from_slice", issue = "31755")]
156     fn copy_from_slice(&mut self, src: &[Self::Item]) where Self::Item: Copy;
157 }
158
159 // Use macros to be generic over const/mut
160 macro_rules! slice_offset {
161     ($ptr:expr, $by:expr) => {{
162         let ptr = $ptr;
163         if size_from_ptr(ptr) == 0 {
164             ::intrinsics::arith_offset(ptr as *mut i8, $by) as *mut _
165         } else {
166             ptr.offset($by)
167         }
168     }};
169 }
170
171 macro_rules! slice_ref {
172     ($ptr:expr) => {{
173         let ptr = $ptr;
174         if size_from_ptr(ptr) == 0 {
175             // Use a non-null pointer value
176             &mut *(1 as *mut _)
177         } else {
178             mem::transmute(ptr)
179         }
180     }};
181 }
182
183 #[unstable(feature = "core_slice_ext",
184            reason = "stable interface provided by `impl [T]` in later crates",
185            issue = "32110")]
186 impl<T> SliceExt for [T] {
187     type Item = T;
188
189     #[inline]
190     fn split_at(&self, mid: usize) -> (&[T], &[T]) {
191         (&self[..mid], &self[mid..])
192     }
193
194     #[inline]
195     fn iter(&self) -> Iter<T> {
196         unsafe {
197             let p = if mem::size_of::<T>() == 0 {
198                 1 as *const _
199             } else {
200                 let p = self.as_ptr();
201                 assume(!p.is_null());
202                 p
203             };
204
205             Iter {
206                 ptr: p,
207                 end: slice_offset!(p, self.len() as isize),
208                 _marker: marker::PhantomData
209             }
210         }
211     }
212
213     #[inline]
214     fn split<P>(&self, pred: P) -> Split<T, P> where P: FnMut(&T) -> bool {
215         Split {
216             v: self,
217             pred: pred,
218             finished: false
219         }
220     }
221
222     #[inline]
223     fn splitn<P>(&self, n: usize, pred: P) -> SplitN<T, P> where
224         P: FnMut(&T) -> bool,
225     {
226         SplitN {
227             inner: GenericSplitN {
228                 iter: self.split(pred),
229                 count: n,
230                 invert: false
231             }
232         }
233     }
234
235     #[inline]
236     fn rsplitn<P>(&self, n: usize, pred: P) -> RSplitN<T, P> where
237         P: FnMut(&T) -> bool,
238     {
239         RSplitN {
240             inner: GenericSplitN {
241                 iter: self.split(pred),
242                 count: n,
243                 invert: true
244             }
245         }
246     }
247
248     #[inline]
249     fn windows(&self, size: usize) -> Windows<T> {
250         assert!(size != 0);
251         Windows { v: self, size: size }
252     }
253
254     #[inline]
255     fn chunks(&self, size: usize) -> Chunks<T> {
256         assert!(size != 0);
257         Chunks { v: self, size: size }
258     }
259
260     #[inline]
261     fn get(&self, index: usize) -> Option<&T> {
262         if index < self.len() { Some(&self[index]) } else { None }
263     }
264
265     #[inline]
266     fn first(&self) -> Option<&T> {
267         if self.is_empty() { None } else { Some(&self[0]) }
268     }
269
270     #[inline]
271     fn split_first(&self) -> Option<(&T, &[T])> {
272         if self.is_empty() { None } else { Some((&self[0], &self[1..])) }
273     }
274
275     #[inline]
276     fn split_last(&self) -> Option<(&T, &[T])> {
277         let len = self.len();
278         if len == 0 { None } else { Some((&self[len - 1], &self[..(len - 1)])) }
279     }
280
281     #[inline]
282     fn last(&self) -> Option<&T> {
283         if self.is_empty() { None } else { Some(&self[self.len() - 1]) }
284     }
285
286     #[inline]
287     unsafe fn get_unchecked(&self, index: usize) -> &T {
288         &*(self.as_ptr().offset(index as isize))
289     }
290
291     #[inline]
292     fn as_ptr(&self) -> *const T {
293         self as *const [T] as *const T
294     }
295
296     fn binary_search_by<F>(&self, mut f: F) -> Result<usize, usize> where
297         F: FnMut(&T) -> Ordering
298     {
299         let mut base = 0usize;
300         let mut s = self;
301
302         loop {
303             let (head, tail) = s.split_at(s.len() >> 1);
304             if tail.is_empty() {
305                 return Err(base)
306             }
307             match f(&tail[0]) {
308                 Less => {
309                     base += head.len() + 1;
310                     s = &tail[1..];
311                 }
312                 Greater => s = head,
313                 Equal => return Ok(base + head.len()),
314             }
315         }
316     }
317
318     #[inline]
319     fn len(&self) -> usize { self.repr().len }
320
321     #[inline]
322     fn get_mut(&mut self, index: usize) -> Option<&mut T> {
323         if index < self.len() { Some(&mut self[index]) } else { None }
324     }
325
326     #[inline]
327     fn split_at_mut(&mut self, mid: usize) -> (&mut [T], &mut [T]) {
328         let len = self.len();
329         let ptr = self.as_mut_ptr();
330
331         unsafe {
332             assert!(mid <= len);
333
334             (from_raw_parts_mut(ptr, mid),
335              from_raw_parts_mut(ptr.offset(mid as isize), len - mid))
336         }
337     }
338
339     #[inline]
340     fn iter_mut(&mut self) -> IterMut<T> {
341         unsafe {
342             let p = if mem::size_of::<T>() == 0 {
343                 1 as *mut _
344             } else {
345                 let p = self.as_mut_ptr();
346                 assume(!p.is_null());
347                 p
348             };
349
350             IterMut {
351                 ptr: p,
352                 end: slice_offset!(p, self.len() as isize),
353                 _marker: marker::PhantomData
354             }
355         }
356     }
357
358     #[inline]
359     fn last_mut(&mut self) -> Option<&mut T> {
360         let len = self.len();
361         if len == 0 { return None; }
362         Some(&mut self[len - 1])
363     }
364
365     #[inline]
366     fn first_mut(&mut self) -> Option<&mut T> {
367         if self.is_empty() { None } else { Some(&mut self[0]) }
368     }
369
370     #[inline]
371     fn split_first_mut(&mut self) -> Option<(&mut T, &mut [T])> {
372         if self.is_empty() { None } else {
373             let split = self.split_at_mut(1);
374             Some((&mut split.0[0], split.1))
375         }
376     }
377
378     #[inline]
379     fn split_last_mut(&mut self) -> Option<(&mut T, &mut [T])> {
380         let len = self.len();
381         if len == 0 { None } else {
382             let split = self.split_at_mut(len - 1);
383             Some((&mut split.1[0], split.0))
384         }
385     }
386
387     #[inline]
388     fn split_mut<P>(&mut self, pred: P) -> SplitMut<T, P> where P: FnMut(&T) -> bool {
389         SplitMut { v: self, pred: pred, finished: false }
390     }
391
392     #[inline]
393     fn splitn_mut<P>(&mut self, n: usize, pred: P) -> SplitNMut<T, P> where
394         P: FnMut(&T) -> bool
395     {
396         SplitNMut {
397             inner: GenericSplitN {
398                 iter: self.split_mut(pred),
399                 count: n,
400                 invert: false
401             }
402         }
403     }
404
405     #[inline]
406     fn rsplitn_mut<P>(&mut self, n: usize, pred: P) -> RSplitNMut<T, P> where
407         P: FnMut(&T) -> bool,
408     {
409         RSplitNMut {
410             inner: GenericSplitN {
411                 iter: self.split_mut(pred),
412                 count: n,
413                 invert: true
414             }
415         }
416    }
417
418     #[inline]
419     fn chunks_mut(&mut self, chunk_size: usize) -> ChunksMut<T> {
420         assert!(chunk_size > 0);
421         ChunksMut { v: self, chunk_size: chunk_size }
422     }
423
424     #[inline]
425     fn swap(&mut self, a: usize, b: usize) {
426         unsafe {
427             // Can't take two mutable loans from one vector, so instead just cast
428             // them to their raw pointers to do the swap
429             let pa: *mut T = &mut self[a];
430             let pb: *mut T = &mut self[b];
431             ptr::swap(pa, pb);
432         }
433     }
434
435     fn reverse(&mut self) {
436         let mut i: usize = 0;
437         let ln = self.len();
438         while i < ln / 2 {
439             // Unsafe swap to avoid the bounds check in safe swap.
440             unsafe {
441                 let pa: *mut T = self.get_unchecked_mut(i);
442                 let pb: *mut T = self.get_unchecked_mut(ln - i - 1);
443                 ptr::swap(pa, pb);
444             }
445             i += 1;
446         }
447     }
448
449     #[inline]
450     unsafe fn get_unchecked_mut(&mut self, index: usize) -> &mut T {
451         &mut *self.as_mut_ptr().offset(index as isize)
452     }
453
454     #[inline]
455     fn as_mut_ptr(&mut self) -> *mut T {
456         self as *mut [T] as *mut T
457     }
458
459     #[inline]
460     fn contains(&self, x: &T) -> bool where T: PartialEq {
461         self.iter().any(|elt| *x == *elt)
462     }
463
464     #[inline]
465     fn starts_with(&self, needle: &[T]) -> bool where T: PartialEq {
466         let n = needle.len();
467         self.len() >= n && needle == &self[..n]
468     }
469
470     #[inline]
471     fn ends_with(&self, needle: &[T]) -> bool where T: PartialEq {
472         let (m, n) = (self.len(), needle.len());
473         m >= n && needle == &self[m-n..]
474     }
475
476     fn binary_search(&self, x: &T) -> Result<usize, usize> where T: Ord {
477         self.binary_search_by(|p| p.cmp(x))
478     }
479
480     #[inline]
481     fn clone_from_slice(&mut self, src: &[T]) where T: Clone {
482         assert!(self.len() == src.len(),
483                 "destination and source slices have different lengths");
484         // NOTE: We need to explicitly slice them to the same length
485         // for bounds checking to be elided, and the optimizer will
486         // generate memcpy for simple cases (for example T = u8).
487         let len = self.len();
488         let src = &src[..len];
489         for i in 0..len {
490             self[i].clone_from(&src[i]);
491         }
492     }
493
494     #[inline]
495     fn copy_from_slice(&mut self, src: &[T]) where T: Copy {
496         assert!(self.len() == src.len(),
497                 "destination and source slices have different lengths");
498         unsafe {
499             ptr::copy_nonoverlapping(
500                 src.as_ptr(), self.as_mut_ptr(), self.len());
501         }
502     }
503 }
504
505 #[stable(feature = "rust1", since = "1.0.0")]
506 impl<T> ops::Index<usize> for [T] {
507     type Output = T;
508
509     fn index(&self, index: usize) -> &T {
510         assert!(index < self.len());
511         unsafe { self.get_unchecked(index) }
512     }
513 }
514
515 #[stable(feature = "rust1", since = "1.0.0")]
516 impl<T> ops::IndexMut<usize> for [T] {
517     #[inline]
518     fn index_mut(&mut self, index: usize) -> &mut T {
519         assert!(index < self.len());
520         unsafe { self.get_unchecked_mut(index) }
521     }
522 }
523
524 #[inline(never)]
525 #[cold]
526 fn slice_index_len_fail(index: usize, len: usize) -> ! {
527     panic!("index {} out of range for slice of length {}", index, len);
528 }
529
530 #[inline(never)]
531 #[cold]
532 fn slice_index_order_fail(index: usize, end: usize) -> ! {
533     panic!("slice index starts at {} but ends at {}", index, end);
534 }
535
536 // FIXME implement indexing with inclusive ranges
537
538 /// Implements slicing with syntax `&self[begin .. end]`.
539 ///
540 /// Returns a slice of self for the index range [`begin`..`end`).
541 ///
542 /// This operation is `O(1)`.
543 ///
544 /// # Panics
545 ///
546 /// Requires that `begin <= end` and `end <= self.len()`,
547 /// otherwise slicing will panic.
548 #[stable(feature = "rust1", since = "1.0.0")]
549 impl<T> ops::Index<ops::Range<usize>> for [T] {
550     type Output = [T];
551
552     #[inline]
553     fn index(&self, index: ops::Range<usize>) -> &[T] {
554         if index.start > index.end {
555             slice_index_order_fail(index.start, index.end);
556         } else if index.end > self.len() {
557             slice_index_len_fail(index.end, self.len());
558         }
559         unsafe {
560             from_raw_parts (
561                 self.as_ptr().offset(index.start as isize),
562                 index.end - index.start
563             )
564         }
565     }
566 }
567
568 /// Implements slicing with syntax `&self[.. end]`.
569 ///
570 /// Returns a slice of self from the beginning until but not including
571 /// the index `end`.
572 ///
573 /// Equivalent to `&self[0 .. end]`
574 #[stable(feature = "rust1", since = "1.0.0")]
575 impl<T> ops::Index<ops::RangeTo<usize>> for [T] {
576     type Output = [T];
577
578     #[inline]
579     fn index(&self, index: ops::RangeTo<usize>) -> &[T] {
580         self.index(0 .. index.end)
581     }
582 }
583
584 /// Implements slicing with syntax `&self[begin ..]`.
585 ///
586 /// Returns a slice of self from and including the index `begin` until the end.
587 ///
588 /// Equivalent to `&self[begin .. self.len()]`
589 #[stable(feature = "rust1", since = "1.0.0")]
590 impl<T> ops::Index<ops::RangeFrom<usize>> for [T] {
591     type Output = [T];
592
593     #[inline]
594     fn index(&self, index: ops::RangeFrom<usize>) -> &[T] {
595         self.index(index.start .. self.len())
596     }
597 }
598
599 /// Implements slicing with syntax `&self[..]`.
600 ///
601 /// Returns a slice of the whole slice. This operation can not panic.
602 ///
603 /// Equivalent to `&self[0 .. self.len()]`
604 #[stable(feature = "rust1", since = "1.0.0")]
605 impl<T> ops::Index<RangeFull> for [T] {
606     type Output = [T];
607
608     #[inline]
609     fn index(&self, _index: RangeFull) -> &[T] {
610         self
611     }
612 }
613
614 #[unstable(feature = "inclusive_range", reason = "recently added, follows RFC", issue = "28237")]
615 impl<T> ops::Index<ops::RangeInclusive<usize>> for [T] {
616     type Output = [T];
617
618     #[inline]
619     fn index(&self, index: ops::RangeInclusive<usize>) -> &[T] {
620         match index {
621             ops::RangeInclusive::Empty { .. } => &[],
622             ops::RangeInclusive::NonEmpty { end, .. } if end == usize::max_value() =>
623                 panic!("attempted to index slice up to maximum usize"),
624             ops::RangeInclusive::NonEmpty { start, end } =>
625                 self.index(start .. end+1)
626         }
627     }
628 }
629 #[unstable(feature = "inclusive_range", reason = "recently added, follows RFC", issue = "28237")]
630 impl<T> ops::Index<ops::RangeToInclusive<usize>> for [T] {
631     type Output = [T];
632
633     #[inline]
634     fn index(&self, index: ops::RangeToInclusive<usize>) -> &[T] {
635         // SNAP 4d3eebf change this to `0...index.end`
636         self.index(ops::RangeInclusive::NonEmpty { start: 0, end: index.end })
637     }
638 }
639
640 /// Implements mutable slicing with syntax `&mut self[begin .. end]`.
641 ///
642 /// Returns a slice of self for the index range [`begin`..`end`).
643 ///
644 /// This operation is `O(1)`.
645 ///
646 /// # Panics
647 ///
648 /// Requires that `begin <= end` and `end <= self.len()`,
649 /// otherwise slicing will panic.
650 #[stable(feature = "rust1", since = "1.0.0")]
651 impl<T> ops::IndexMut<ops::Range<usize>> for [T] {
652     #[inline]
653     fn index_mut(&mut self, index: ops::Range<usize>) -> &mut [T] {
654         if index.start > index.end {
655             slice_index_order_fail(index.start, index.end);
656         } else if index.end > self.len() {
657             slice_index_len_fail(index.end, self.len());
658         }
659         unsafe {
660             from_raw_parts_mut(
661                 self.as_mut_ptr().offset(index.start as isize),
662                 index.end - index.start
663             )
664         }
665     }
666 }
667
668 /// Implements mutable slicing with syntax `&mut self[.. end]`.
669 ///
670 /// Returns a slice of self from the beginning until but not including
671 /// the index `end`.
672 ///
673 /// Equivalent to `&mut self[0 .. end]`
674 #[stable(feature = "rust1", since = "1.0.0")]
675 impl<T> ops::IndexMut<ops::RangeTo<usize>> for [T] {
676     #[inline]
677     fn index_mut(&mut self, index: ops::RangeTo<usize>) -> &mut [T] {
678         self.index_mut(0 .. index.end)
679     }
680 }
681
682 /// Implements mutable slicing with syntax `&mut self[begin ..]`.
683 ///
684 /// Returns a slice of self from and including the index `begin` until the end.
685 ///
686 /// Equivalent to `&mut self[begin .. self.len()]`
687 #[stable(feature = "rust1", since = "1.0.0")]
688 impl<T> ops::IndexMut<ops::RangeFrom<usize>> for [T] {
689     #[inline]
690     fn index_mut(&mut self, index: ops::RangeFrom<usize>) -> &mut [T] {
691         let len = self.len();
692         self.index_mut(index.start .. len)
693     }
694 }
695
696 /// Implements mutable slicing with syntax `&mut self[..]`.
697 ///
698 /// Returns a slice of the whole slice. This operation can not panic.
699 ///
700 /// Equivalent to `&mut self[0 .. self.len()]`
701 #[stable(feature = "rust1", since = "1.0.0")]
702 impl<T> ops::IndexMut<RangeFull> for [T] {
703     #[inline]
704     fn index_mut(&mut self, _index: RangeFull) -> &mut [T] {
705         self
706     }
707 }
708
709 #[unstable(feature = "inclusive_range", reason = "recently added, follows RFC", issue = "28237")]
710 impl<T> ops::IndexMut<ops::RangeInclusive<usize>> for [T] {
711     #[inline]
712     fn index_mut(&mut self, index: ops::RangeInclusive<usize>) -> &mut [T] {
713         match index {
714             ops::RangeInclusive::Empty { .. } => &mut [],
715             ops::RangeInclusive::NonEmpty { end, .. } if end == usize::max_value() =>
716                 panic!("attempted to index slice up to maximum usize"),
717             ops::RangeInclusive::NonEmpty { start, end } =>
718                 self.index_mut(start .. end+1)
719         }
720     }
721 }
722 #[unstable(feature = "inclusive_range", reason = "recently added, follows RFC", issue = "28237")]
723 impl<T> ops::IndexMut<ops::RangeToInclusive<usize>> for [T] {
724     #[inline]
725     fn index_mut(&mut self, index: ops::RangeToInclusive<usize>) -> &mut [T] {
726         // SNAP 4d3eebf change this to `0...index.end`
727         self.index_mut(ops::RangeInclusive::NonEmpty { start: 0, end: index.end })
728     }
729 }
730
731 ////////////////////////////////////////////////////////////////////////////////
732 // Common traits
733 ////////////////////////////////////////////////////////////////////////////////
734
735 #[stable(feature = "rust1", since = "1.0.0")]
736 impl<'a, T> Default for &'a [T] {
737     fn default() -> &'a [T] { &[] }
738 }
739
740 #[stable(feature = "mut_slice_default", since = "1.5.0")]
741 impl<'a, T> Default for &'a mut [T] {
742     fn default() -> &'a mut [T] { &mut [] }
743 }
744
745 //
746 // Iterators
747 //
748
749 #[stable(feature = "rust1", since = "1.0.0")]
750 impl<'a, T> IntoIterator for &'a [T] {
751     type Item = &'a T;
752     type IntoIter = Iter<'a, T>;
753
754     fn into_iter(self) -> Iter<'a, T> {
755         self.iter()
756     }
757 }
758
759 #[stable(feature = "rust1", since = "1.0.0")]
760 impl<'a, T> IntoIterator for &'a mut [T] {
761     type Item = &'a mut T;
762     type IntoIter = IterMut<'a, T>;
763
764     fn into_iter(self) -> IterMut<'a, T> {
765         self.iter_mut()
766     }
767 }
768
769 #[inline(always)]
770 fn size_from_ptr<T>(_: *const T) -> usize {
771     mem::size_of::<T>()
772 }
773
774 // The shared definition of the `Iter` and `IterMut` iterators
775 macro_rules! iterator {
776     (struct $name:ident -> $ptr:ty, $elem:ty) => {
777         #[stable(feature = "rust1", since = "1.0.0")]
778         impl<'a, T> Iterator for $name<'a, T> {
779             type Item = $elem;
780
781             #[inline]
782             fn next(&mut self) -> Option<$elem> {
783                 // could be implemented with slices, but this avoids bounds checks
784                 unsafe {
785                     if mem::size_of::<T>() != 0 {
786                         assume(!self.ptr.is_null());
787                         assume(!self.end.is_null());
788                     }
789                     if self.ptr == self.end {
790                         None
791                     } else {
792                         let old = self.ptr;
793                         self.ptr = slice_offset!(self.ptr, 1);
794                         Some(slice_ref!(old))
795                     }
796                 }
797             }
798
799             #[inline]
800             fn size_hint(&self) -> (usize, Option<usize>) {
801                 let diff = (self.end as usize).wrapping_sub(self.ptr as usize);
802                 let size = mem::size_of::<T>();
803                 let exact = diff / (if size == 0 {1} else {size});
804                 (exact, Some(exact))
805             }
806
807             #[inline]
808             fn count(self) -> usize {
809                 self.size_hint().0
810             }
811
812             #[inline]
813             fn nth(&mut self, n: usize) -> Option<$elem> {
814                 // Call helper method. Can't put the definition here because mut versus const.
815                 self.iter_nth(n)
816             }
817
818             #[inline]
819             fn last(mut self) -> Option<$elem> {
820                 self.next_back()
821             }
822         }
823
824         #[stable(feature = "rust1", since = "1.0.0")]
825         impl<'a, T> DoubleEndedIterator for $name<'a, T> {
826             #[inline]
827             fn next_back(&mut self) -> Option<$elem> {
828                 // could be implemented with slices, but this avoids bounds checks
829                 unsafe {
830                     if mem::size_of::<T>() != 0 {
831                         assume(!self.ptr.is_null());
832                         assume(!self.end.is_null());
833                     }
834                     if self.end == self.ptr {
835                         None
836                     } else {
837                         self.end = slice_offset!(self.end, -1);
838                         Some(slice_ref!(self.end))
839                     }
840                 }
841             }
842         }
843     }
844 }
845
846 macro_rules! make_slice {
847     ($start: expr, $end: expr) => {{
848         let start = $start;
849         let diff = ($end as usize).wrapping_sub(start as usize);
850         if size_from_ptr(start) == 0 {
851             // use a non-null pointer value
852             unsafe { from_raw_parts(1 as *const _, diff) }
853         } else {
854             let len = diff / size_from_ptr(start);
855             unsafe { from_raw_parts(start, len) }
856         }
857     }}
858 }
859
860 macro_rules! make_mut_slice {
861     ($start: expr, $end: expr) => {{
862         let start = $start;
863         let diff = ($end as usize).wrapping_sub(start as usize);
864         if size_from_ptr(start) == 0 {
865             // use a non-null pointer value
866             unsafe { from_raw_parts_mut(1 as *mut _, diff) }
867         } else {
868             let len = diff / size_from_ptr(start);
869             unsafe { from_raw_parts_mut(start, len) }
870         }
871     }}
872 }
873
874 /// Immutable slice iterator
875 #[stable(feature = "rust1", since = "1.0.0")]
876 pub struct Iter<'a, T: 'a> {
877     ptr: *const T,
878     end: *const T,
879     _marker: marker::PhantomData<&'a T>,
880 }
881
882 #[stable(feature = "rust1", since = "1.0.0")]
883 unsafe impl<'a, T: Sync> Sync for Iter<'a, T> {}
884 #[stable(feature = "rust1", since = "1.0.0")]
885 unsafe impl<'a, T: Sync> Send for Iter<'a, T> {}
886
887 impl<'a, T> Iter<'a, T> {
888     /// View the underlying data as a subslice of the original data.
889     ///
890     /// This has the same lifetime as the original slice, and so the
891     /// iterator can continue to be used while this exists.
892     #[stable(feature = "iter_to_slice", since = "1.4.0")]
893     pub fn as_slice(&self) -> &'a [T] {
894         make_slice!(self.ptr, self.end)
895     }
896
897     // Helper function for Iter::nth
898     fn iter_nth(&mut self, n: usize) -> Option<&'a T> {
899         match self.as_slice().get(n) {
900             Some(elem_ref) => unsafe {
901                 self.ptr = slice_offset!(self.ptr, (n as isize).wrapping_add(1));
902                 Some(elem_ref)
903             },
904             None => {
905                 self.ptr = self.end;
906                 None
907             }
908         }
909     }
910 }
911
912 iterator!{struct Iter -> *const T, &'a T}
913
914 #[stable(feature = "rust1", since = "1.0.0")]
915 impl<'a, T> ExactSizeIterator for Iter<'a, T> {}
916
917 #[stable(feature = "rust1", since = "1.0.0")]
918 impl<'a, T> Clone for Iter<'a, T> {
919     fn clone(&self) -> Iter<'a, T> { Iter { ptr: self.ptr, end: self.end, _marker: self._marker } }
920 }
921
922 /// Mutable slice iterator.
923 #[stable(feature = "rust1", since = "1.0.0")]
924 pub struct IterMut<'a, T: 'a> {
925     ptr: *mut T,
926     end: *mut T,
927     _marker: marker::PhantomData<&'a mut T>,
928 }
929
930 #[stable(feature = "rust1", since = "1.0.0")]
931 unsafe impl<'a, T: Sync> Sync for IterMut<'a, T> {}
932 #[stable(feature = "rust1", since = "1.0.0")]
933 unsafe impl<'a, T: Send> Send for IterMut<'a, T> {}
934
935 impl<'a, T> IterMut<'a, T> {
936     /// View the underlying data as a subslice of the original data.
937     ///
938     /// To avoid creating `&mut` references that alias, this is forced
939     /// to consume the iterator. Consider using the `Slice` and
940     /// `SliceMut` implementations for obtaining slices with more
941     /// restricted lifetimes that do not consume the iterator.
942     #[stable(feature = "iter_to_slice", since = "1.4.0")]
943     pub fn into_slice(self) -> &'a mut [T] {
944         make_mut_slice!(self.ptr, self.end)
945     }
946
947     // Helper function for IterMut::nth
948     fn iter_nth(&mut self, n: usize) -> Option<&'a mut T> {
949         match make_mut_slice!(self.ptr, self.end).get_mut(n) {
950             Some(elem_ref) => unsafe {
951                 self.ptr = slice_offset!(self.ptr, (n as isize).wrapping_add(1));
952                 Some(elem_ref)
953             },
954             None => {
955                 self.ptr = self.end;
956                 None
957             }
958         }
959     }
960 }
961
962 iterator!{struct IterMut -> *mut T, &'a mut T}
963
964 #[stable(feature = "rust1", since = "1.0.0")]
965 impl<'a, T> ExactSizeIterator for IterMut<'a, T> {}
966
967 /// An internal abstraction over the splitting iterators, so that
968 /// splitn, splitn_mut etc can be implemented once.
969 #[doc(hidden)]
970 trait SplitIter: DoubleEndedIterator {
971     /// Mark the underlying iterator as complete, extracting the remaining
972     /// portion of the slice.
973     fn finish(&mut self) -> Option<Self::Item>;
974 }
975
976 /// An iterator over subslices separated by elements that match a predicate
977 /// function.
978 #[stable(feature = "rust1", since = "1.0.0")]
979 pub struct Split<'a, T:'a, P> where P: FnMut(&T) -> bool {
980     v: &'a [T],
981     pred: P,
982     finished: bool
983 }
984
985 // FIXME(#19839) Remove in favor of `#[derive(Clone)]`
986 #[stable(feature = "rust1", since = "1.0.0")]
987 impl<'a, T, P> Clone for Split<'a, T, P> where P: Clone + FnMut(&T) -> bool {
988     fn clone(&self) -> Split<'a, T, P> {
989         Split {
990             v: self.v,
991             pred: self.pred.clone(),
992             finished: self.finished,
993         }
994     }
995 }
996
997 #[stable(feature = "rust1", since = "1.0.0")]
998 impl<'a, T, P> Iterator for Split<'a, T, P> where P: FnMut(&T) -> bool {
999     type Item = &'a [T];
1000
1001     #[inline]
1002     fn next(&mut self) -> Option<&'a [T]> {
1003         if self.finished { return None; }
1004
1005         match self.v.iter().position(|x| (self.pred)(x)) {
1006             None => self.finish(),
1007             Some(idx) => {
1008                 let ret = Some(&self.v[..idx]);
1009                 self.v = &self.v[idx + 1..];
1010                 ret
1011             }
1012         }
1013     }
1014
1015     #[inline]
1016     fn size_hint(&self) -> (usize, Option<usize>) {
1017         if self.finished {
1018             (0, Some(0))
1019         } else {
1020             (1, Some(self.v.len() + 1))
1021         }
1022     }
1023 }
1024
1025 #[stable(feature = "rust1", since = "1.0.0")]
1026 impl<'a, T, P> DoubleEndedIterator for Split<'a, T, P> where P: FnMut(&T) -> bool {
1027     #[inline]
1028     fn next_back(&mut self) -> Option<&'a [T]> {
1029         if self.finished { return None; }
1030
1031         match self.v.iter().rposition(|x| (self.pred)(x)) {
1032             None => self.finish(),
1033             Some(idx) => {
1034                 let ret = Some(&self.v[idx + 1..]);
1035                 self.v = &self.v[..idx];
1036                 ret
1037             }
1038         }
1039     }
1040 }
1041
1042 impl<'a, T, P> SplitIter for Split<'a, T, P> where P: FnMut(&T) -> bool {
1043     #[inline]
1044     fn finish(&mut self) -> Option<&'a [T]> {
1045         if self.finished { None } else { self.finished = true; Some(self.v) }
1046     }
1047 }
1048
1049 /// An iterator over the subslices of the vector which are separated
1050 /// by elements that match `pred`.
1051 #[stable(feature = "rust1", since = "1.0.0")]
1052 pub struct SplitMut<'a, T:'a, P> where P: FnMut(&T) -> bool {
1053     v: &'a mut [T],
1054     pred: P,
1055     finished: bool
1056 }
1057
1058 impl<'a, T, P> SplitIter for SplitMut<'a, T, P> where P: FnMut(&T) -> bool {
1059     #[inline]
1060     fn finish(&mut self) -> Option<&'a mut [T]> {
1061         if self.finished {
1062             None
1063         } else {
1064             self.finished = true;
1065             Some(mem::replace(&mut self.v, &mut []))
1066         }
1067     }
1068 }
1069
1070 #[stable(feature = "rust1", since = "1.0.0")]
1071 impl<'a, T, P> Iterator for SplitMut<'a, T, P> where P: FnMut(&T) -> bool {
1072     type Item = &'a mut [T];
1073
1074     #[inline]
1075     fn next(&mut self) -> Option<&'a mut [T]> {
1076         if self.finished { return None; }
1077
1078         let idx_opt = { // work around borrowck limitations
1079             let pred = &mut self.pred;
1080             self.v.iter().position(|x| (*pred)(x))
1081         };
1082         match idx_opt {
1083             None => self.finish(),
1084             Some(idx) => {
1085                 let tmp = mem::replace(&mut self.v, &mut []);
1086                 let (head, tail) = tmp.split_at_mut(idx);
1087                 self.v = &mut tail[1..];
1088                 Some(head)
1089             }
1090         }
1091     }
1092
1093     #[inline]
1094     fn size_hint(&self) -> (usize, Option<usize>) {
1095         if self.finished {
1096             (0, Some(0))
1097         } else {
1098             // if the predicate doesn't match anything, we yield one slice
1099             // if it matches every element, we yield len+1 empty slices.
1100             (1, Some(self.v.len() + 1))
1101         }
1102     }
1103 }
1104
1105 #[stable(feature = "rust1", since = "1.0.0")]
1106 impl<'a, T, P> DoubleEndedIterator for SplitMut<'a, T, P> where
1107     P: FnMut(&T) -> bool,
1108 {
1109     #[inline]
1110     fn next_back(&mut self) -> Option<&'a mut [T]> {
1111         if self.finished { return None; }
1112
1113         let idx_opt = { // work around borrowck limitations
1114             let pred = &mut self.pred;
1115             self.v.iter().rposition(|x| (*pred)(x))
1116         };
1117         match idx_opt {
1118             None => self.finish(),
1119             Some(idx) => {
1120                 let tmp = mem::replace(&mut self.v, &mut []);
1121                 let (head, tail) = tmp.split_at_mut(idx);
1122                 self.v = head;
1123                 Some(&mut tail[1..])
1124             }
1125         }
1126     }
1127 }
1128
1129 /// An private iterator over subslices separated by elements that
1130 /// match a predicate function, splitting at most a fixed number of
1131 /// times.
1132 struct GenericSplitN<I> {
1133     iter: I,
1134     count: usize,
1135     invert: bool
1136 }
1137
1138 impl<T, I: SplitIter<Item=T>> Iterator for GenericSplitN<I> {
1139     type Item = T;
1140
1141     #[inline]
1142     fn next(&mut self) -> Option<T> {
1143         match self.count {
1144             0 => None,
1145             1 => { self.count -= 1; self.iter.finish() }
1146             _ => {
1147                 self.count -= 1;
1148                 if self.invert {self.iter.next_back()} else {self.iter.next()}
1149             }
1150         }
1151     }
1152
1153     #[inline]
1154     fn size_hint(&self) -> (usize, Option<usize>) {
1155         let (lower, upper_opt) = self.iter.size_hint();
1156         (lower, upper_opt.map(|upper| cmp::min(self.count, upper)))
1157     }
1158 }
1159
1160 /// An iterator over subslices separated by elements that match a predicate
1161 /// function, limited to a given number of splits.
1162 #[stable(feature = "rust1", since = "1.0.0")]
1163 pub struct SplitN<'a, T: 'a, P> where P: FnMut(&T) -> bool {
1164     inner: GenericSplitN<Split<'a, T, P>>
1165 }
1166
1167 /// An iterator over subslices separated by elements that match a
1168 /// predicate function, limited to a given number of splits, starting
1169 /// from the end of the slice.
1170 #[stable(feature = "rust1", since = "1.0.0")]
1171 pub struct RSplitN<'a, T: 'a, P> where P: FnMut(&T) -> bool {
1172     inner: GenericSplitN<Split<'a, T, P>>
1173 }
1174
1175 /// An iterator over subslices separated by elements that match a predicate
1176 /// function, limited to a given number of splits.
1177 #[stable(feature = "rust1", since = "1.0.0")]
1178 pub struct SplitNMut<'a, T: 'a, P> where P: FnMut(&T) -> bool {
1179     inner: GenericSplitN<SplitMut<'a, T, P>>
1180 }
1181
1182 /// An iterator over subslices separated by elements that match a
1183 /// predicate function, limited to a given number of splits, starting
1184 /// from the end of the slice.
1185 #[stable(feature = "rust1", since = "1.0.0")]
1186 pub struct RSplitNMut<'a, T: 'a, P> where P: FnMut(&T) -> bool {
1187     inner: GenericSplitN<SplitMut<'a, T, P>>
1188 }
1189
1190 macro_rules! forward_iterator {
1191     ($name:ident: $elem:ident, $iter_of:ty) => {
1192         #[stable(feature = "rust1", since = "1.0.0")]
1193         impl<'a, $elem, P> Iterator for $name<'a, $elem, P> where
1194             P: FnMut(&T) -> bool
1195         {
1196             type Item = $iter_of;
1197
1198             #[inline]
1199             fn next(&mut self) -> Option<$iter_of> {
1200                 self.inner.next()
1201             }
1202
1203             #[inline]
1204             fn size_hint(&self) -> (usize, Option<usize>) {
1205                 self.inner.size_hint()
1206             }
1207         }
1208     }
1209 }
1210
1211 forward_iterator! { SplitN: T, &'a [T] }
1212 forward_iterator! { RSplitN: T, &'a [T] }
1213 forward_iterator! { SplitNMut: T, &'a mut [T] }
1214 forward_iterator! { RSplitNMut: T, &'a mut [T] }
1215
1216 /// An iterator over overlapping subslices of length `size`.
1217 #[stable(feature = "rust1", since = "1.0.0")]
1218 pub struct Windows<'a, T:'a> {
1219     v: &'a [T],
1220     size: usize
1221 }
1222
1223 // FIXME(#19839) Remove in favor of `#[derive(Clone)]`
1224 #[stable(feature = "rust1", since = "1.0.0")]
1225 impl<'a, T> Clone for Windows<'a, T> {
1226     fn clone(&self) -> Windows<'a, T> {
1227         Windows {
1228             v: self.v,
1229             size: self.size,
1230         }
1231     }
1232 }
1233
1234 #[stable(feature = "rust1", since = "1.0.0")]
1235 impl<'a, T> Iterator for Windows<'a, T> {
1236     type Item = &'a [T];
1237
1238     #[inline]
1239     fn next(&mut self) -> Option<&'a [T]> {
1240         if self.size > self.v.len() {
1241             None
1242         } else {
1243             let ret = Some(&self.v[..self.size]);
1244             self.v = &self.v[1..];
1245             ret
1246         }
1247     }
1248
1249     #[inline]
1250     fn size_hint(&self) -> (usize, Option<usize>) {
1251         if self.size > self.v.len() {
1252             (0, Some(0))
1253         } else {
1254             let size = self.v.len() - self.size + 1;
1255             (size, Some(size))
1256         }
1257     }
1258
1259     #[inline]
1260     fn count(self) -> usize {
1261         self.size_hint().0
1262     }
1263
1264     #[inline]
1265     fn nth(&mut self, n: usize) -> Option<Self::Item> {
1266         let (end, overflow) = self.size.overflowing_add(n);
1267         if end > self.v.len() || overflow {
1268             self.v = &[];
1269             None
1270         } else {
1271             let nth = &self.v[n..end];
1272             self.v = &self.v[n+1..];
1273             Some(nth)
1274         }
1275     }
1276
1277     #[inline]
1278     fn last(self) -> Option<Self::Item> {
1279         if self.size > self.v.len() {
1280             None
1281         } else {
1282             let start = self.v.len() - self.size;
1283             Some(&self.v[start..])
1284         }
1285     }
1286 }
1287
1288 #[stable(feature = "rust1", since = "1.0.0")]
1289 impl<'a, T> DoubleEndedIterator for Windows<'a, T> {
1290     #[inline]
1291     fn next_back(&mut self) -> Option<&'a [T]> {
1292         if self.size > self.v.len() {
1293             None
1294         } else {
1295             let ret = Some(&self.v[self.v.len()-self.size..]);
1296             self.v = &self.v[..self.v.len()-1];
1297             ret
1298         }
1299     }
1300 }
1301
1302 #[stable(feature = "rust1", since = "1.0.0")]
1303 impl<'a, T> ExactSizeIterator for Windows<'a, T> {}
1304
1305 /// An iterator over a slice in (non-overlapping) chunks (`size` elements at a
1306 /// time).
1307 ///
1308 /// When the slice len is not evenly divided by the chunk size, the last slice
1309 /// of the iteration will be the remainder.
1310 #[stable(feature = "rust1", since = "1.0.0")]
1311 pub struct Chunks<'a, T:'a> {
1312     v: &'a [T],
1313     size: usize
1314 }
1315
1316 // FIXME(#19839) Remove in favor of `#[derive(Clone)]`
1317 #[stable(feature = "rust1", since = "1.0.0")]
1318 impl<'a, T> Clone for Chunks<'a, T> {
1319     fn clone(&self) -> Chunks<'a, T> {
1320         Chunks {
1321             v: self.v,
1322             size: self.size,
1323         }
1324     }
1325 }
1326
1327 #[stable(feature = "rust1", since = "1.0.0")]
1328 impl<'a, T> Iterator for Chunks<'a, T> {
1329     type Item = &'a [T];
1330
1331     #[inline]
1332     fn next(&mut self) -> Option<&'a [T]> {
1333         if self.v.is_empty() {
1334             None
1335         } else {
1336             let chunksz = cmp::min(self.v.len(), self.size);
1337             let (fst, snd) = self.v.split_at(chunksz);
1338             self.v = snd;
1339             Some(fst)
1340         }
1341     }
1342
1343     #[inline]
1344     fn size_hint(&self) -> (usize, Option<usize>) {
1345         if self.v.is_empty() {
1346             (0, Some(0))
1347         } else {
1348             let n = self.v.len() / self.size;
1349             let rem = self.v.len() % self.size;
1350             let n = if rem > 0 { n+1 } else { n };
1351             (n, Some(n))
1352         }
1353     }
1354
1355     #[inline]
1356     fn count(self) -> usize {
1357         self.size_hint().0
1358     }
1359
1360     #[inline]
1361     fn nth(&mut self, n: usize) -> Option<Self::Item> {
1362         let (start, overflow) = n.overflowing_mul(self.size);
1363         if start >= self.v.len() || overflow {
1364             self.v = &[];
1365             None
1366         } else {
1367             let end = match start.checked_add(self.size) {
1368                 Some(sum) => cmp::min(self.v.len(), sum),
1369                 None => self.v.len(),
1370             };
1371             let nth = &self.v[start..end];
1372             self.v = &self.v[end..];
1373             Some(nth)
1374         }
1375     }
1376
1377     #[inline]
1378     fn last(self) -> Option<Self::Item> {
1379         if self.v.is_empty() {
1380             None
1381         } else {
1382             let start = (self.v.len() - 1) / self.size * self.size;
1383             Some(&self.v[start..])
1384         }
1385     }
1386 }
1387
1388 #[stable(feature = "rust1", since = "1.0.0")]
1389 impl<'a, T> DoubleEndedIterator for Chunks<'a, T> {
1390     #[inline]
1391     fn next_back(&mut self) -> Option<&'a [T]> {
1392         if self.v.is_empty() {
1393             None
1394         } else {
1395             let remainder = self.v.len() % self.size;
1396             let chunksz = if remainder != 0 { remainder } else { self.size };
1397             let (fst, snd) = self.v.split_at(self.v.len() - chunksz);
1398             self.v = fst;
1399             Some(snd)
1400         }
1401     }
1402 }
1403
1404 #[stable(feature = "rust1", since = "1.0.0")]
1405 impl<'a, T> ExactSizeIterator for Chunks<'a, T> {}
1406
1407 /// An iterator over a slice in (non-overlapping) mutable chunks (`size`
1408 /// elements at a time). When the slice len is not evenly divided by the chunk
1409 /// size, the last slice of the iteration will be the remainder.
1410 #[stable(feature = "rust1", since = "1.0.0")]
1411 pub struct ChunksMut<'a, T:'a> {
1412     v: &'a mut [T],
1413     chunk_size: usize
1414 }
1415
1416 #[stable(feature = "rust1", since = "1.0.0")]
1417 impl<'a, T> Iterator for ChunksMut<'a, T> {
1418     type Item = &'a mut [T];
1419
1420     #[inline]
1421     fn next(&mut self) -> Option<&'a mut [T]> {
1422         if self.v.is_empty() {
1423             None
1424         } else {
1425             let sz = cmp::min(self.v.len(), self.chunk_size);
1426             let tmp = mem::replace(&mut self.v, &mut []);
1427             let (head, tail) = tmp.split_at_mut(sz);
1428             self.v = tail;
1429             Some(head)
1430         }
1431     }
1432
1433     #[inline]
1434     fn size_hint(&self) -> (usize, Option<usize>) {
1435         if self.v.is_empty() {
1436             (0, Some(0))
1437         } else {
1438             let n = self.v.len() / self.chunk_size;
1439             let rem = self.v.len() % self.chunk_size;
1440             let n = if rem > 0 { n + 1 } else { n };
1441             (n, Some(n))
1442         }
1443     }
1444
1445     #[inline]
1446     fn count(self) -> usize {
1447         self.size_hint().0
1448     }
1449
1450     #[inline]
1451     fn nth(&mut self, n: usize) -> Option<&'a mut [T]> {
1452         let (start, overflow) = n.overflowing_mul(self.chunk_size);
1453         if start >= self.v.len() || overflow {
1454             self.v = &mut [];
1455             None
1456         } else {
1457             let end = match start.checked_add(self.chunk_size) {
1458                 Some(sum) => cmp::min(self.v.len(), sum),
1459                 None => self.v.len(),
1460             };
1461             let tmp = mem::replace(&mut self.v, &mut []);
1462             let (head, tail) = tmp.split_at_mut(end);
1463             let (_, nth) =  head.split_at_mut(start);
1464             self.v = tail;
1465             Some(nth)
1466         }
1467     }
1468
1469     #[inline]
1470     fn last(self) -> Option<Self::Item> {
1471         if self.v.is_empty() {
1472             None
1473         } else {
1474             let start = (self.v.len() - 1) / self.chunk_size * self.chunk_size;
1475             Some(&mut self.v[start..])
1476         }
1477     }
1478 }
1479
1480 #[stable(feature = "rust1", since = "1.0.0")]
1481 impl<'a, T> DoubleEndedIterator for ChunksMut<'a, T> {
1482     #[inline]
1483     fn next_back(&mut self) -> Option<&'a mut [T]> {
1484         if self.v.is_empty() {
1485             None
1486         } else {
1487             let remainder = self.v.len() % self.chunk_size;
1488             let sz = if remainder != 0 { remainder } else { self.chunk_size };
1489             let tmp = mem::replace(&mut self.v, &mut []);
1490             let tmp_len = tmp.len();
1491             let (head, tail) = tmp.split_at_mut(tmp_len - sz);
1492             self.v = head;
1493             Some(tail)
1494         }
1495     }
1496 }
1497
1498 #[stable(feature = "rust1", since = "1.0.0")]
1499 impl<'a, T> ExactSizeIterator for ChunksMut<'a, T> {}
1500
1501 //
1502 // Free functions
1503 //
1504
1505 /// Forms a slice from a pointer and a length.
1506 ///
1507 /// The `len` argument is the number of **elements**, not the number of bytes.
1508 ///
1509 /// # Safety
1510 ///
1511 /// This function is unsafe as there is no guarantee that the given pointer is
1512 /// valid for `len` elements, nor whether the lifetime inferred is a suitable
1513 /// lifetime for the returned slice.
1514 ///
1515 /// `p` must be non-null, even for zero-length slices.
1516 ///
1517 /// # Caveat
1518 ///
1519 /// The lifetime for the returned slice is inferred from its usage. To
1520 /// prevent accidental misuse, it's suggested to tie the lifetime to whichever
1521 /// source lifetime is safe in the context, such as by providing a helper
1522 /// function taking the lifetime of a host value for the slice, or by explicit
1523 /// annotation.
1524 ///
1525 /// # Examples
1526 ///
1527 /// ```
1528 /// use std::slice;
1529 ///
1530 /// // manifest a slice out of thin air!
1531 /// let ptr = 0x1234 as *const usize;
1532 /// let amt = 10;
1533 /// unsafe {
1534 ///     let slice = slice::from_raw_parts(ptr, amt);
1535 /// }
1536 /// ```
1537 #[inline]
1538 #[stable(feature = "rust1", since = "1.0.0")]
1539 pub unsafe fn from_raw_parts<'a, T>(p: *const T, len: usize) -> &'a [T] {
1540     mem::transmute(RawSlice { data: p, len: len })
1541 }
1542
1543 /// Performs the same functionality as `from_raw_parts`, except that a mutable
1544 /// slice is returned.
1545 ///
1546 /// This function is unsafe for the same reasons as `from_raw_parts`, as well
1547 /// as not being able to provide a non-aliasing guarantee of the returned
1548 /// mutable slice.
1549 #[inline]
1550 #[stable(feature = "rust1", since = "1.0.0")]
1551 pub unsafe fn from_raw_parts_mut<'a, T>(p: *mut T, len: usize) -> &'a mut [T] {
1552     mem::transmute(RawSlice { data: p, len: len })
1553 }
1554
1555 //
1556 // Submodules
1557 //
1558
1559 /// Operations on `[u8]`.
1560 #[unstable(feature = "slice_bytes", reason = "needs review",
1561            issue = "27740")]
1562 #[rustc_deprecated(reason = "unidiomatic functions not pulling their weight",
1563                    since = "1.6.0")]
1564 #[allow(deprecated)]
1565 pub mod bytes {
1566     use ptr;
1567     use slice::SliceExt;
1568
1569     /// A trait for operations on mutable `[u8]`s.
1570     pub trait MutableByteVector {
1571         /// Sets all bytes of the receiver to the given value.
1572         fn set_memory(&mut self, value: u8);
1573     }
1574
1575     impl MutableByteVector for [u8] {
1576         #[inline]
1577         fn set_memory(&mut self, value: u8) {
1578             unsafe { ptr::write_bytes(self.as_mut_ptr(), value, self.len()) };
1579         }
1580     }
1581
1582     /// Copies data from `src` to `dst`
1583     ///
1584     /// Panics if the length of `dst` is less than the length of `src`.
1585     #[inline]
1586     pub fn copy_memory(src: &[u8], dst: &mut [u8]) {
1587         let len_src = src.len();
1588         assert!(dst.len() >= len_src);
1589         // `dst` is unaliasable, so we know statically it doesn't overlap
1590         // with `src`.
1591         unsafe {
1592             ptr::copy_nonoverlapping(src.as_ptr(),
1593                                      dst.as_mut_ptr(),
1594                                      len_src);
1595         }
1596     }
1597 }
1598
1599
1600
1601 //
1602 // Boilerplate traits
1603 //
1604
1605 #[stable(feature = "rust1", since = "1.0.0")]
1606 impl<A, B> PartialEq<[B]> for [A] where A: PartialEq<B> {
1607     fn eq(&self, other: &[B]) -> bool {
1608         if self.len() != other.len() {
1609             return false;
1610         }
1611
1612         for i in 0..self.len() {
1613             if !self[i].eq(&other[i]) {
1614                 return false;
1615             }
1616         }
1617
1618         true
1619     }
1620     fn ne(&self, other: &[B]) -> bool {
1621         if self.len() != other.len() {
1622             return true;
1623         }
1624
1625         for i in 0..self.len() {
1626             if self[i].ne(&other[i]) {
1627                 return true;
1628             }
1629         }
1630
1631         false
1632     }
1633 }
1634
1635 #[stable(feature = "rust1", since = "1.0.0")]
1636 impl<T: Eq> Eq for [T] {}
1637
1638 #[stable(feature = "rust1", since = "1.0.0")]
1639 impl<T: Ord> Ord for [T] {
1640     fn cmp(&self, other: &[T]) -> Ordering {
1641         let l = cmp::min(self.len(), other.len());
1642
1643         // Slice to the loop iteration range to enable bound check
1644         // elimination in the compiler
1645         let lhs = &self[..l];
1646         let rhs = &other[..l];
1647
1648         for i in 0..l {
1649             match lhs[i].cmp(&rhs[i]) {
1650                 Ordering::Equal => (),
1651                 non_eq => return non_eq,
1652             }
1653         }
1654
1655         self.len().cmp(&other.len())
1656     }
1657 }
1658
1659 #[stable(feature = "rust1", since = "1.0.0")]
1660 impl<T: PartialOrd> PartialOrd for [T] {
1661     fn partial_cmp(&self, other: &[T]) -> Option<Ordering> {
1662         let l = cmp::min(self.len(), other.len());
1663
1664         // Slice to the loop iteration range to enable bound check
1665         // elimination in the compiler
1666         let lhs = &self[..l];
1667         let rhs = &other[..l];
1668
1669         for i in 0..l {
1670             match lhs[i].partial_cmp(&rhs[i]) {
1671                 Some(Ordering::Equal) => (),
1672                 non_eq => return non_eq,
1673             }
1674         }
1675
1676         self.len().partial_cmp(&other.len())
1677     }
1678 }