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