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