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