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