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