]> git.lizzy.rs Git - rust.git/blob - src/libcore/slice.rs
6c8bacaef48e2f4e73b0d390cecced7d76fb9f63
[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 #![doc(primitive = "slice")]
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 mem::transmute;
37 use clone::Clone;
38 use collections::Collection;
39 use cmp::{PartialEq, PartialOrd, Eq, Ord, Ordering, Less, Equal, Greater, Equiv};
40 use cmp;
41 use default::Default;
42 use iter::*;
43 use num::{CheckedAdd, Saturating, div_rem};
44 use option::{None, Option, Some};
45 use ptr;
46 use ptr::RawPtr;
47 use mem;
48 use mem::size_of;
49 use kinds::marker;
50 use raw::{Repr, Slice};
51
52 //
53 // Extension traits
54 //
55
56 /// Extension methods for vectors
57 pub trait ImmutableSlice<'a, T> {
58     /**
59      * Returns a slice of self spanning the interval [`start`, `end`).
60      *
61      * Fails when the slice (or part of it) is outside the bounds of self,
62      * or when `start` > `end`.
63      */
64     fn slice(&self, start: uint, end: uint) -> &'a [T];
65
66     /**
67      * Returns a slice of self from `start` to the end of the vec.
68      *
69      * Fails when `start` points outside the bounds of self.
70      */
71     fn slice_from(&self, start: uint) -> &'a [T];
72
73     /**
74      * Returns a slice of self from the start of the vec to `end`.
75      *
76      * Fails when `end` points outside the bounds of self.
77      */
78     fn slice_to(&self, end: uint) -> &'a [T];
79
80     /// Divides one slice into two at an index.
81     ///
82     /// The first will contain all indices from `[0, mid)` (excluding
83     /// the index `mid` itself) and the second will contain all
84     /// indices from `[mid, len)` (excluding the index `len` itself).
85     ///
86     /// Fails if `mid > len`.
87     fn split_at(&self, mid: uint) -> (&'a [T], &'a [T]);
88
89     /// Returns an iterator over the vector
90     fn iter(self) -> Items<'a, T>;
91     /// Returns an iterator over the subslices of the vector which are
92     /// separated by elements that match `pred`.  The matched element
93     /// is not contained in the subslices.
94     fn split(self, pred: |&T|: 'a -> bool) -> Splits<'a, T>;
95     /// Returns an iterator over the subslices of the vector which are
96     /// separated by elements that match `pred`, limited to splitting
97     /// at most `n` times.  The matched element is not contained in
98     /// the subslices.
99     fn splitn(self, n: uint, pred: |&T|: 'a -> bool) -> SplitsN<'a, T>;
100     /// Returns an iterator over the subslices of the vector which are
101     /// separated by elements that match `pred` limited to splitting
102     /// at most `n` times. This starts at the end of the vector and
103     /// works backwards.  The matched element is not contained in the
104     /// subslices.
105     fn rsplitn(self,  n: uint, pred: |&T|: 'a -> bool) -> SplitsN<'a, T>;
106
107     /**
108      * Returns an iterator over all contiguous windows of length
109      * `size`. The windows overlap. If the vector is shorter than
110      * `size`, the iterator returns no values.
111      *
112      * # Failure
113      *
114      * Fails if `size` is 0.
115      *
116      * # Example
117      *
118      * Print the adjacent pairs of a vector (i.e. `[1,2]`, `[2,3]`,
119      * `[3,4]`):
120      *
121      * ```rust
122      * let v = &[1i, 2, 3, 4];
123      * for win in v.windows(2) {
124      *     println!("{}", win);
125      * }
126      * ```
127      *
128      */
129     fn windows(self, size: uint) -> Windows<'a, T>;
130     /**
131      *
132      * Returns an iterator over `size` elements of the vector at a
133      * time. The chunks do not overlap. If `size` does not divide the
134      * length of the vector, then the last chunk will not have length
135      * `size`.
136      *
137      * # Failure
138      *
139      * Fails if `size` is 0.
140      *
141      * # Example
142      *
143      * Print the vector two elements at a time (i.e. `[1,2]`,
144      * `[3,4]`, `[5]`):
145      *
146      * ```rust
147      * let v = &[1i, 2, 3, 4, 5];
148      * for win in v.chunks(2) {
149      *     println!("{}", win);
150      * }
151      * ```
152      *
153      */
154     fn chunks(self, size: uint) -> Chunks<'a, T>;
155
156     /// Returns the element of a vector at the given index, or `None` if the
157     /// index is out of bounds
158     fn get(&self, index: uint) -> Option<&'a T>;
159     /// Returns the first element of a vector, or `None` if it is empty
160     fn head(&self) -> Option<&'a T>;
161     /// Returns all but the first element of a vector
162     fn tail(&self) -> &'a [T];
163     /// Returns all but the first `n' elements of a vector
164     fn tailn(&self, n: uint) -> &'a [T];
165     /// Returns all but the last element of a vector
166     fn init(&self) -> &'a [T];
167     /// Returns all but the last `n' elements of a vector
168     fn initn(&self, n: uint) -> &'a [T];
169     /// Returns the last element of a vector, or `None` if it is empty.
170     fn last(&self) -> Option<&'a T>;
171
172     /// Returns a pointer to the element at the given index, without doing
173     /// bounds checking.
174     unsafe fn unsafe_ref(self, index: uint) -> &'a T;
175
176     /**
177      * Returns an unsafe pointer to the vector's buffer
178      *
179      * The caller must ensure that the vector outlives the pointer this
180      * function returns, or else it will end up pointing to garbage.
181      *
182      * Modifying the vector may cause its buffer to be reallocated, which
183      * would also make any pointers to it invalid.
184      */
185     fn as_ptr(&self) -> *const T;
186
187     /**
188      * Binary search a sorted vector with a comparator function.
189      *
190      * The comparator function should implement an order consistent
191      * with the sort order of the underlying vector, returning an
192      * order code that indicates whether its argument is `Less`,
193      * `Equal` or `Greater` the desired target.
194      *
195      * Returns the index where the comparator returned `Equal`, or `None` if
196      * not found.
197      */
198     fn bsearch(&self, f: |&T| -> Ordering) -> Option<uint>;
199
200     /**
201      * Returns an immutable reference to the first element in this slice
202      * and adjusts the slice in place so that it no longer contains
203      * that element. O(1).
204      *
205      * Equivalent to:
206      *
207      * ```ignore
208      *     if self.len() == 0 { return None }
209      *     let head = &self[0];
210      *     *self = self.slice_from(1);
211      *     Some(head)
212      * ```
213      *
214      * Returns `None` if vector is empty
215      */
216     fn shift_ref(&mut self) -> Option<&'a T>;
217
218     /**
219      * Returns an immutable reference to the last element in this slice
220      * and adjusts the slice in place so that it no longer contains
221      * that element. O(1).
222      *
223      * Equivalent to:
224      *
225      * ```ignore
226      *     if self.len() == 0 { return None; }
227      *     let tail = &self[self.len() - 1];
228      *     *self = self.slice_to(self.len() - 1);
229      *     Some(tail)
230      * ```
231      *
232      * Returns `None` if slice is empty.
233      */
234     fn pop_ref(&mut self) -> Option<&'a T>;
235 }
236
237 impl<'a,T> ImmutableSlice<'a, T> for &'a [T] {
238     #[inline]
239     fn slice(&self, start: uint, end: uint) -> &'a [T] {
240         assert!(start <= end);
241         assert!(end <= self.len());
242         unsafe {
243             transmute(Slice {
244                     data: self.as_ptr().offset(start as int),
245                     len: (end - start)
246                 })
247         }
248     }
249
250     #[inline]
251     fn slice_from(&self, start: uint) -> &'a [T] {
252         self.slice(start, self.len())
253     }
254
255     #[inline]
256     fn slice_to(&self, end: uint) -> &'a [T] {
257         self.slice(0, end)
258     }
259
260     #[inline]
261     fn split_at(&self, mid: uint) -> (&'a [T], &'a [T]) {
262         (self.slice(0, mid), self.slice(mid, self.len()))
263     }
264
265     #[inline]
266     fn iter(self) -> Items<'a, T> {
267         unsafe {
268             let p = self.as_ptr();
269             if mem::size_of::<T>() == 0 {
270                 Items{ptr: p,
271                       end: (p as uint + self.len()) as *const T,
272                       marker: marker::ContravariantLifetime::<'a>}
273             } else {
274                 Items{ptr: p,
275                       end: p.offset(self.len() as int),
276                       marker: marker::ContravariantLifetime::<'a>}
277             }
278         }
279     }
280
281     #[inline]
282     fn split(self, pred: |&T|: 'a -> bool) -> Splits<'a, T> {
283         Splits {
284             v: self,
285             pred: pred,
286             finished: false
287         }
288     }
289
290     #[inline]
291     fn splitn(self, n: uint, pred: |&T|: 'a -> bool) -> SplitsN<'a, T> {
292         SplitsN {
293             iter: self.split(pred),
294             count: n,
295             invert: false
296         }
297     }
298
299     #[inline]
300     fn rsplitn(self, n: uint, pred: |&T|: 'a -> bool) -> SplitsN<'a, T> {
301         SplitsN {
302             iter: self.split(pred),
303             count: n,
304             invert: true
305         }
306     }
307
308     #[inline]
309     fn windows(self, size: uint) -> Windows<'a, T> {
310         assert!(size != 0);
311         Windows { v: self, size: size }
312     }
313
314     #[inline]
315     fn chunks(self, size: uint) -> Chunks<'a, T> {
316         assert!(size != 0);
317         Chunks { v: self, size: size }
318     }
319
320     #[inline]
321     fn get(&self, index: uint) -> Option<&'a T> {
322         if index < self.len() { Some(&self[index]) } else { None }
323     }
324
325     #[inline]
326     fn head(&self) -> Option<&'a T> {
327         if self.len() == 0 { None } else { Some(&self[0]) }
328     }
329
330     #[inline]
331     fn tail(&self) -> &'a [T] { self.slice(1, self.len()) }
332
333     #[inline]
334     fn tailn(&self, n: uint) -> &'a [T] { self.slice(n, self.len()) }
335
336     #[inline]
337     fn init(&self) -> &'a [T] {
338         self.slice(0, self.len() - 1)
339     }
340
341     #[inline]
342     fn initn(&self, n: uint) -> &'a [T] {
343         self.slice(0, self.len() - n)
344     }
345
346     #[inline]
347     fn last(&self) -> Option<&'a T> {
348             if self.len() == 0 { None } else { Some(&self[self.len() - 1]) }
349     }
350
351     #[inline]
352     unsafe fn unsafe_ref(self, index: uint) -> &'a T {
353         transmute(self.repr().data.offset(index as int))
354     }
355
356     #[inline]
357     fn as_ptr(&self) -> *const T {
358         self.repr().data
359     }
360
361
362     fn bsearch(&self, f: |&T| -> Ordering) -> Option<uint> {
363         let mut base : uint = 0;
364         let mut lim : uint = self.len();
365
366         while lim != 0 {
367             let ix = base + (lim >> 1);
368             match f(&self[ix]) {
369                 Equal => return Some(ix),
370                 Less => {
371                     base = ix + 1;
372                     lim -= 1;
373                 }
374                 Greater => ()
375             }
376             lim >>= 1;
377         }
378         return None;
379     }
380
381     fn shift_ref(&mut self) -> Option<&'a T> {
382         unsafe {
383             let s: &mut Slice<T> = transmute(self);
384             match raw::shift_ptr(s) {
385                 Some(p) => Some(&*p),
386                 None => None
387             }
388         }
389     }
390
391     fn pop_ref(&mut self) -> Option<&'a T> {
392         unsafe {
393             let s: &mut Slice<T> = transmute(self);
394             match raw::pop_ptr(s) {
395                 Some(p) => Some(&*p),
396                 None => None
397             }
398         }
399     }
400 }
401
402 /// Extension methods for vectors such that their elements are
403 /// mutable.
404 pub trait MutableSlice<'a, T> {
405     /// Returns a mutable reference to the element at the given index,
406     /// or `None` if the index is out of bounds
407     fn get_mut(self, index: uint) -> Option<&'a mut T>;
408     /// Work with `self` as a mut slice.
409     /// Primarily intended for getting a &mut [T] from a [T, ..N].
410     fn as_mut_slice(self) -> &'a mut [T];
411
412     /// Return a slice that points into another slice.
413     fn mut_slice(self, start: uint, end: uint) -> &'a mut [T];
414
415     /**
416      * Returns a slice of self from `start` to the end of the vec.
417      *
418      * Fails when `start` points outside the bounds of self.
419      */
420     fn mut_slice_from(self, start: uint) -> &'a mut [T];
421
422     /**
423      * Returns a slice of self from the start of the vec to `end`.
424      *
425      * Fails when `end` points outside the bounds of self.
426      */
427     fn mut_slice_to(self, end: uint) -> &'a mut [T];
428
429     /// Returns an iterator that allows modifying each value
430     fn mut_iter(self) -> MutItems<'a, T>;
431
432     /// Returns a mutable pointer to the last item in the vector.
433     fn mut_last(self) -> Option<&'a mut T>;
434
435     /// Returns an iterator over the mutable subslices of the vector
436     /// which are separated by elements that match `pred`.  The
437     /// matched element is not contained in the subslices.
438     fn mut_split(self, pred: |&T|: 'a -> bool) -> MutSplits<'a, T>;
439
440     /**
441      * Returns an iterator over `size` elements of the vector at a time.
442      * The chunks are mutable and do not overlap. If `size` does not divide the
443      * length of the vector, then the last chunk will not have length
444      * `size`.
445      *
446      * # Failure
447      *
448      * Fails if `size` is 0.
449      */
450     fn mut_chunks(self, chunk_size: uint) -> MutChunks<'a, T>;
451
452     /**
453      * Returns a mutable reference to the first element in this slice
454      * and adjusts the slice in place so that it no longer contains
455      * that element. O(1).
456      *
457      * Equivalent to:
458      *
459      * ```ignore
460      *     if self.len() == 0 { return None; }
461      *     let head = &mut self[0];
462      *     *self = self.mut_slice_from(1);
463      *     Some(head)
464      * ```
465      *
466      * Returns `None` if slice is empty
467      */
468     fn mut_shift_ref(&mut self) -> Option<&'a mut T>;
469
470     /**
471      * Returns a mutable reference to the last element in this slice
472      * and adjusts the slice in place so that it no longer contains
473      * that element. O(1).
474      *
475      * Equivalent to:
476      *
477      * ```ignore
478      *     if self.len() == 0 { return None; }
479      *     let tail = &mut self[self.len() - 1];
480      *     *self = self.mut_slice_to(self.len() - 1);
481      *     Some(tail)
482      * ```
483      *
484      * Returns `None` if slice is empty.
485      */
486     fn mut_pop_ref(&mut self) -> Option<&'a mut T>;
487
488     /// Swaps two elements in a vector.
489     ///
490     /// Fails if `a` or `b` are out of bounds.
491     ///
492     /// # Arguments
493     ///
494     /// * a - The index of the first element
495     /// * b - The index of the second element
496     ///
497     /// # Example
498     ///
499     /// ```rust
500     /// let mut v = ["a", "b", "c", "d"];
501     /// v.swap(1, 3);
502     /// assert!(v == ["a", "d", "c", "b"]);
503     /// ```
504     fn swap(self, a: uint, b: uint);
505
506
507     /// Divides one `&mut` into two at an index.
508     ///
509     /// The first will contain all indices from `[0, mid)` (excluding
510     /// the index `mid` itself) and the second will contain all
511     /// indices from `[mid, len)` (excluding the index `len` itself).
512     ///
513     /// Fails if `mid > len`.
514     ///
515     /// # Example
516     ///
517     /// ```rust
518     /// let mut v = [1i, 2, 3, 4, 5, 6];
519     ///
520     /// // scoped to restrict the lifetime of the borrows
521     /// {
522     ///    let (left, right) = v.mut_split_at(0);
523     ///    assert!(left == &mut []);
524     ///    assert!(right == &mut [1i, 2, 3, 4, 5, 6]);
525     /// }
526     ///
527     /// {
528     ///     let (left, right) = v.mut_split_at(2);
529     ///     assert!(left == &mut [1i, 2]);
530     ///     assert!(right == &mut [3i, 4, 5, 6]);
531     /// }
532     ///
533     /// {
534     ///     let (left, right) = v.mut_split_at(6);
535     ///     assert!(left == &mut [1i, 2, 3, 4, 5, 6]);
536     ///     assert!(right == &mut []);
537     /// }
538     /// ```
539     fn mut_split_at(self, mid: uint) -> (&'a mut [T], &'a mut [T]);
540
541     /// Reverse the order of elements in a vector, in place.
542     ///
543     /// # Example
544     ///
545     /// ```rust
546     /// let mut v = [1i, 2, 3];
547     /// v.reverse();
548     /// assert!(v == [3i, 2, 1]);
549     /// ```
550     fn reverse(self);
551
552     /// Returns an unsafe mutable pointer to the element in index
553     unsafe fn unsafe_mut_ref(self, index: uint) -> &'a mut T;
554
555     /// Return an unsafe mutable pointer to the vector's buffer.
556     ///
557     /// The caller must ensure that the vector outlives the pointer this
558     /// function returns, or else it will end up pointing to garbage.
559     ///
560     /// Modifying the vector may cause its buffer to be reallocated, which
561     /// would also make any pointers to it invalid.
562     #[inline]
563     fn as_mut_ptr(self) -> *mut T;
564
565     /// Unsafely sets the element in index to the value.
566     ///
567     /// This performs no bounds checks, and it is undefined behaviour
568     /// if `index` is larger than the length of `self`. However, it
569     /// does run the destructor at `index`. It is equivalent to
570     /// `self[index] = val`.
571     ///
572     /// # Example
573     ///
574     /// ```rust
575     /// let mut v = ["foo".to_string(), "bar".to_string(), "baz".to_string()];
576     ///
577     /// unsafe {
578     ///     // `"baz".to_string()` is deallocated.
579     ///     v.unsafe_set(2, "qux".to_string());
580     ///
581     ///     // Out of bounds: could cause a crash, or overwriting
582     ///     // other data, or something else.
583     ///     // v.unsafe_set(10, "oops".to_string());
584     /// }
585     /// ```
586     unsafe fn unsafe_set(self, index: uint, val: T);
587
588     /// Unchecked vector index assignment.  Does not drop the
589     /// old value and hence is only suitable when the vector
590     /// is newly allocated.
591     ///
592     /// # Example
593     ///
594     /// ```rust
595     /// let mut v = ["foo".to_string(), "bar".to_string()];
596     ///
597     /// // memory leak! `"bar".to_string()` is not deallocated.
598     /// unsafe { v.init_elem(1, "baz".to_string()); }
599     /// ```
600     unsafe fn init_elem(self, i: uint, val: T);
601
602     /// Copies raw bytes from `src` to `self`.
603     ///
604     /// This does not run destructors on the overwritten elements, and
605     /// ignores move semantics. `self` and `src` must not
606     /// overlap. Fails if `self` is shorter than `src`.
607     unsafe fn copy_memory(self, src: &[T]);
608 }
609
610 impl<'a,T> MutableSlice<'a, T> for &'a mut [T] {
611     #[inline]
612     fn get_mut(self, index: uint) -> Option<&'a mut T> {
613         if index < self.len() { Some(&mut self[index]) } else { None }
614     }
615
616     #[inline]
617     fn as_mut_slice(self) -> &'a mut [T] { self }
618
619     fn mut_slice(self, start: uint, end: uint) -> &'a mut [T] {
620         assert!(start <= end);
621         assert!(end <= self.len());
622         unsafe {
623             transmute(Slice {
624                     data: self.as_mut_ptr().offset(start as int) as *const T,
625                     len: (end - start)
626                 })
627         }
628     }
629
630     #[inline]
631     fn mut_slice_from(self, start: uint) -> &'a mut [T] {
632         let len = self.len();
633         self.mut_slice(start, len)
634     }
635
636     #[inline]
637     fn mut_slice_to(self, end: uint) -> &'a mut [T] {
638         self.mut_slice(0, end)
639     }
640
641     #[inline]
642     fn mut_split_at(self, mid: uint) -> (&'a mut [T], &'a mut [T]) {
643         unsafe {
644             let len = self.len();
645             let self2: &'a mut [T] = mem::transmute_copy(&self);
646             (self.mut_slice(0, mid), self2.mut_slice(mid, len))
647         }
648     }
649
650     #[inline]
651     fn mut_iter(self) -> MutItems<'a, T> {
652         unsafe {
653             let p = self.as_mut_ptr();
654             if mem::size_of::<T>() == 0 {
655                 MutItems{ptr: p,
656                          end: (p as uint + self.len()) as *mut T,
657                          marker: marker::ContravariantLifetime::<'a>,
658                          marker2: marker::NoCopy}
659             } else {
660                 MutItems{ptr: p,
661                          end: p.offset(self.len() as int),
662                          marker: marker::ContravariantLifetime::<'a>,
663                          marker2: marker::NoCopy}
664             }
665         }
666     }
667
668     #[inline]
669     fn mut_last(self) -> Option<&'a mut T> {
670         let len = self.len();
671         if len == 0 { return None; }
672         Some(&mut self[len - 1])
673     }
674
675     #[inline]
676     fn mut_split(self, pred: |&T|: 'a -> bool) -> MutSplits<'a, T> {
677         MutSplits { v: self, pred: pred, finished: false }
678     }
679
680     #[inline]
681     fn mut_chunks(self, chunk_size: uint) -> MutChunks<'a, T> {
682         assert!(chunk_size > 0);
683         MutChunks { v: self, chunk_size: chunk_size }
684     }
685
686     fn mut_shift_ref(&mut self) -> Option<&'a mut T> {
687         unsafe {
688             let s: &mut Slice<T> = transmute(self);
689             match raw::shift_ptr(s) {
690                 // FIXME #13933: this `&` -> `&mut` cast is a little
691                 // dubious
692                 Some(p) => Some(&mut *(p as *mut _)),
693                 None => None,
694             }
695         }
696     }
697
698     fn mut_pop_ref(&mut self) -> Option<&'a mut T> {
699         unsafe {
700             let s: &mut Slice<T> = transmute(self);
701             match raw::pop_ptr(s) {
702                 // FIXME #13933: this `&` -> `&mut` cast is a little
703                 // dubious
704                 Some(p) => Some(&mut *(p as *mut _)),
705                 None => None,
706             }
707         }
708     }
709
710     fn swap(self, a: uint, b: uint) {
711         unsafe {
712             // Can't take two mutable loans from one vector, so instead just cast
713             // them to their raw pointers to do the swap
714             let pa: *mut T = &mut self[a];
715             let pb: *mut T = &mut self[b];
716             ptr::swap(pa, pb);
717         }
718     }
719
720     fn reverse(self) {
721         let mut i: uint = 0;
722         let ln = self.len();
723         while i < ln / 2 {
724             self.swap(i, ln - i - 1);
725             i += 1;
726         }
727     }
728
729     #[inline]
730     unsafe fn unsafe_mut_ref(self, index: uint) -> &'a mut T {
731         transmute((self.repr().data as *mut T).offset(index as int))
732     }
733
734     #[inline]
735     fn as_mut_ptr(self) -> *mut T {
736         self.repr().data as *mut T
737     }
738
739     #[inline]
740     unsafe fn unsafe_set(self, index: uint, val: T) {
741         *self.unsafe_mut_ref(index) = val;
742     }
743
744     #[inline]
745     unsafe fn init_elem(self, i: uint, val: T) {
746         ptr::write(&mut (*self.as_mut_ptr().offset(i as int)), val);
747     }
748
749     #[inline]
750     unsafe fn copy_memory(self, src: &[T]) {
751         let len_src = src.len();
752         assert!(self.len() >= len_src);
753         ptr::copy_nonoverlapping_memory(self.as_mut_ptr(), src.as_ptr(), len_src)
754     }
755 }
756
757 /// Extension methods for vectors contain `PartialEq` elements.
758 pub trait ImmutableEqSlice<T:PartialEq> {
759     /// Find the first index containing a matching value
760     fn position_elem(&self, t: &T) -> Option<uint>;
761
762     /// Find the last index containing a matching value
763     fn rposition_elem(&self, t: &T) -> Option<uint>;
764
765     /// Return true if a vector contains an element with the given value
766     fn contains(&self, x: &T) -> bool;
767
768     /// Returns true if `needle` is a prefix of the vector.
769     fn starts_with(&self, needle: &[T]) -> bool;
770
771     /// Returns true if `needle` is a suffix of the vector.
772     fn ends_with(&self, needle: &[T]) -> bool;
773 }
774
775 impl<'a,T:PartialEq> ImmutableEqSlice<T> for &'a [T] {
776     #[inline]
777     fn position_elem(&self, x: &T) -> Option<uint> {
778         self.iter().position(|y| *x == *y)
779     }
780
781     #[inline]
782     fn rposition_elem(&self, t: &T) -> Option<uint> {
783         self.iter().rposition(|x| *x == *t)
784     }
785
786     #[inline]
787     fn contains(&self, x: &T) -> bool {
788         self.iter().any(|elt| *x == *elt)
789     }
790
791     #[inline]
792     fn starts_with(&self, needle: &[T]) -> bool {
793         let n = needle.len();
794         self.len() >= n && needle == self.slice_to(n)
795     }
796
797     #[inline]
798     fn ends_with(&self, needle: &[T]) -> bool {
799         let (m, n) = (self.len(), needle.len());
800         m >= n && needle == self.slice_from(m - n)
801     }
802 }
803
804 /// Extension methods for vectors containing `Ord` elements.
805 pub trait ImmutableOrdSlice<T: Ord> {
806     /**
807      * Binary search a sorted vector for a given element.
808      *
809      * Returns the index of the element or None if not found.
810      */
811     fn bsearch_elem(&self, x: &T) -> Option<uint>;
812 }
813
814 impl<'a, T: Ord> ImmutableOrdSlice<T> for &'a [T] {
815     fn bsearch_elem(&self, x: &T) -> Option<uint> {
816         self.bsearch(|p| p.cmp(x))
817     }
818 }
819
820 /// Trait for &[T] where T is Cloneable
821 pub trait MutableCloneableSlice<T> {
822     /// Copies as many elements from `src` as it can into `self` (the
823     /// shorter of `self.len()` and `src.len()`). Returns the number
824     /// of elements copied.
825     ///
826     /// # Example
827     ///
828     /// ```rust
829     /// use std::slice::MutableCloneableSlice;
830     ///
831     /// let mut dst = [0i, 0, 0];
832     /// let src = [1i, 2];
833     ///
834     /// assert!(dst.copy_from(src) == 2);
835     /// assert!(dst == [1, 2, 0]);
836     ///
837     /// let src2 = [3i, 4, 5, 6];
838     /// assert!(dst.copy_from(src2) == 3);
839     /// assert!(dst == [3i, 4, 5]);
840     /// ```
841     fn copy_from(self, &[T]) -> uint;
842 }
843
844 impl<'a, T:Clone> MutableCloneableSlice<T> for &'a mut [T] {
845     #[inline]
846     fn copy_from(self, src: &[T]) -> uint {
847         for (a, b) in self.mut_iter().zip(src.iter()) {
848             a.clone_from(b);
849         }
850         cmp::min(self.len(), src.len())
851     }
852 }
853
854
855
856
857 //
858 // Common traits
859 //
860
861 /// Any vector that can be represented as a slice.
862 pub trait Vector<T> {
863     /// Work with `self` as a slice.
864     fn as_slice<'a>(&'a self) -> &'a [T];
865 }
866
867 impl<'a,T> Vector<T> for &'a [T] {
868     #[inline(always)]
869     fn as_slice<'a>(&'a self) -> &'a [T] { *self }
870 }
871
872 impl<'a, T> Collection for &'a [T] {
873     /// Returns the length of a vector
874     #[inline]
875     fn len(&self) -> uint {
876         self.repr().len
877     }
878 }
879
880 impl<'a, T> Default for &'a [T] {
881     fn default() -> &'a [T] { &[] }
882 }
883
884
885
886
887 //
888 // Iterators
889 //
890
891 // The shared definition of the `Item` and `MutItems` iterators
892 macro_rules! iterator {
893     (struct $name:ident -> $ptr:ty, $elem:ty) => {
894         impl<'a, T> Iterator<$elem> for $name<'a, T> {
895             #[inline]
896             fn next(&mut self) -> Option<$elem> {
897                 // could be implemented with slices, but this avoids bounds checks
898                 unsafe {
899                     if self.ptr == self.end {
900                         None
901                     } else {
902                         if mem::size_of::<T>() == 0 {
903                             // purposefully don't use 'ptr.offset' because for
904                             // vectors with 0-size elements this would return the
905                             // same pointer.
906                             self.ptr = transmute(self.ptr as uint + 1);
907
908                             // Use a non-null pointer value
909                             Some(transmute(1u))
910                         } else {
911                             let old = self.ptr;
912                             self.ptr = self.ptr.offset(1);
913
914                             Some(transmute(old))
915                         }
916                     }
917                 }
918             }
919
920             #[inline]
921             fn size_hint(&self) -> (uint, Option<uint>) {
922                 let diff = (self.end as uint) - (self.ptr as uint);
923                 let size = mem::size_of::<T>();
924                 let exact = diff / (if size == 0 {1} else {size});
925                 (exact, Some(exact))
926             }
927         }
928
929         impl<'a, T> DoubleEndedIterator<$elem> for $name<'a, T> {
930             #[inline]
931             fn next_back(&mut self) -> Option<$elem> {
932                 // could be implemented with slices, but this avoids bounds checks
933                 unsafe {
934                     if self.end == self.ptr {
935                         None
936                     } else {
937                         if mem::size_of::<T>() == 0 {
938                             // See above for why 'ptr.offset' isn't used
939                             self.end = transmute(self.end as uint - 1);
940
941                             // Use a non-null pointer value
942                             Some(transmute(1u))
943                         } else {
944                             self.end = self.end.offset(-1);
945
946                             Some(transmute(self.end))
947                         }
948                     }
949                 }
950             }
951         }
952     }
953 }
954
955 /// Immutable slice iterator
956 pub struct Items<'a, T> {
957     ptr: *const T,
958     end: *const T,
959     marker: marker::ContravariantLifetime<'a>
960 }
961
962 iterator!{struct Items -> *const T, &'a T}
963
964 impl<'a, T> ExactSize<&'a T> for Items<'a, T> {}
965
966 impl<'a, T> Clone for Items<'a, T> {
967     fn clone(&self) -> Items<'a, T> { *self }
968 }
969
970 impl<'a, T> RandomAccessIterator<&'a T> for Items<'a, T> {
971     #[inline]
972     fn indexable(&self) -> uint {
973         let (exact, _) = self.size_hint();
974         exact
975     }
976
977     #[inline]
978     fn idx(&mut self, index: uint) -> Option<&'a T> {
979         unsafe {
980             if index < self.indexable() {
981                 if mem::size_of::<T>() == 0 {
982                     // Use a non-null pointer value
983                     Some(transmute(1u))
984                 } else {
985                     Some(transmute(self.ptr.offset(index as int)))
986                 }
987             } else {
988                 None
989             }
990         }
991     }
992 }
993
994 /// Mutable slice iterator
995 pub struct MutItems<'a, T> {
996     ptr: *mut T,
997     end: *mut T,
998     marker: marker::ContravariantLifetime<'a>,
999     marker2: marker::NoCopy
1000 }
1001
1002 iterator!{struct MutItems -> *mut T, &'a mut T}
1003
1004 impl<'a, T> ExactSize<&'a mut T> for MutItems<'a, T> {}
1005
1006 /// An iterator over the slices of a vector separated by elements that
1007 /// match a predicate function.
1008 pub struct Splits<'a, T> {
1009     v: &'a [T],
1010     pred: |t: &T|: 'a -> bool,
1011     finished: bool
1012 }
1013
1014 impl<'a, T> Iterator<&'a [T]> for Splits<'a, T> {
1015     #[inline]
1016     fn next(&mut self) -> Option<&'a [T]> {
1017         if self.finished { return None; }
1018
1019         match self.v.iter().position(|x| (self.pred)(x)) {
1020             None => {
1021                 self.finished = true;
1022                 Some(self.v)
1023             }
1024             Some(idx) => {
1025                 let ret = Some(self.v.slice(0, idx));
1026                 self.v = self.v.slice(idx + 1, self.v.len());
1027                 ret
1028             }
1029         }
1030     }
1031
1032     #[inline]
1033     fn size_hint(&self) -> (uint, Option<uint>) {
1034         if self.finished {
1035             (0, Some(0))
1036         } else {
1037             (1, Some(self.v.len() + 1))
1038         }
1039     }
1040 }
1041
1042 impl<'a, T> DoubleEndedIterator<&'a [T]> for Splits<'a, T> {
1043     #[inline]
1044     fn next_back(&mut self) -> Option<&'a [T]> {
1045         if self.finished { return None; }
1046
1047         match self.v.iter().rposition(|x| (self.pred)(x)) {
1048             None => {
1049                 self.finished = true;
1050                 Some(self.v)
1051             }
1052             Some(idx) => {
1053                 let ret = Some(self.v.slice(idx + 1, self.v.len()));
1054                 self.v = self.v.slice(0, idx);
1055                 ret
1056             }
1057         }
1058     }
1059 }
1060
1061 /// An iterator over the subslices of the vector which are separated
1062 /// by elements that match `pred`.
1063 pub struct MutSplits<'a, T> {
1064     v: &'a mut [T],
1065     pred: |t: &T|: 'a -> bool,
1066     finished: bool
1067 }
1068
1069 impl<'a, T> Iterator<&'a mut [T]> for MutSplits<'a, T> {
1070     #[inline]
1071     fn next(&mut self) -> Option<&'a mut [T]> {
1072         if self.finished { return None; }
1073
1074         let pred = &mut self.pred;
1075         match self.v.iter().position(|x| (*pred)(x)) {
1076             None => {
1077                 self.finished = true;
1078                 let tmp = mem::replace(&mut self.v, &mut []);
1079                 let len = tmp.len();
1080                 let (head, tail) = tmp.mut_split_at(len);
1081                 self.v = tail;
1082                 Some(head)
1083             }
1084             Some(idx) => {
1085                 let tmp = mem::replace(&mut self.v, &mut []);
1086                 let (head, tail) = tmp.mut_split_at(idx);
1087                 self.v = tail.mut_slice_from(1);
1088                 Some(head)
1089             }
1090         }
1091     }
1092
1093     #[inline]
1094     fn size_hint(&self) -> (uint, Option<uint>) {
1095         if self.finished {
1096             (0, Some(0))
1097         } else {
1098             // if the predicate doesn't match anything, we yield one slice
1099             // if it matches every element, we yield len+1 empty slices.
1100             (1, Some(self.v.len() + 1))
1101         }
1102     }
1103 }
1104
1105 impl<'a, T> DoubleEndedIterator<&'a mut [T]> for MutSplits<'a, T> {
1106     #[inline]
1107     fn next_back(&mut self) -> Option<&'a mut [T]> {
1108         if self.finished { return None; }
1109
1110         let pred = &mut self.pred;
1111         match self.v.iter().rposition(|x| (*pred)(x)) {
1112             None => {
1113                 self.finished = true;
1114                 let tmp = mem::replace(&mut self.v, &mut []);
1115                 Some(tmp)
1116             }
1117             Some(idx) => {
1118                 let tmp = mem::replace(&mut self.v, &mut []);
1119                 let (head, tail) = tmp.mut_split_at(idx);
1120                 self.v = head;
1121                 Some(tail.mut_slice_from(1))
1122             }
1123         }
1124     }
1125 }
1126
1127 /// An iterator over the slices of a vector separated by elements that
1128 /// match a predicate function, splitting at most a fixed number of times.
1129 pub struct SplitsN<'a, T> {
1130     iter: Splits<'a, T>,
1131     count: uint,
1132     invert: bool
1133 }
1134
1135 impl<'a, T> Iterator<&'a [T]> for SplitsN<'a, T> {
1136     #[inline]
1137     fn next(&mut self) -> Option<&'a [T]> {
1138         if self.count == 0 {
1139             if self.iter.finished {
1140                 None
1141             } else {
1142                 self.iter.finished = true;
1143                 Some(self.iter.v)
1144             }
1145         } else {
1146             self.count -= 1;
1147             if self.invert { self.iter.next_back() } else { self.iter.next() }
1148         }
1149     }
1150
1151     #[inline]
1152     fn size_hint(&self) -> (uint, Option<uint>) {
1153         if self.iter.finished {
1154             (0, Some(0))
1155         } else {
1156             (1, Some(cmp::min(self.count, self.iter.v.len()) + 1))
1157         }
1158     }
1159 }
1160
1161 /// An iterator over the (overlapping) slices of length `size` within
1162 /// a vector.
1163 #[deriving(Clone)]
1164 pub struct Windows<'a, T> {
1165     v: &'a [T],
1166     size: uint
1167 }
1168
1169 impl<'a, T> Iterator<&'a [T]> for Windows<'a, T> {
1170     #[inline]
1171     fn next(&mut self) -> Option<&'a [T]> {
1172         if self.size > self.v.len() {
1173             None
1174         } else {
1175             let ret = Some(self.v.slice(0, self.size));
1176             self.v = self.v.slice(1, self.v.len());
1177             ret
1178         }
1179     }
1180
1181     #[inline]
1182     fn size_hint(&self) -> (uint, Option<uint>) {
1183         if self.size > self.v.len() {
1184             (0, Some(0))
1185         } else {
1186             let x = self.v.len() - self.size;
1187             (x.saturating_add(1), x.checked_add(&1u))
1188         }
1189     }
1190 }
1191
1192 /// An iterator over a vector in (non-overlapping) chunks (`size`
1193 /// elements at a time).
1194 ///
1195 /// When the vector len is not evenly divided by the chunk size,
1196 /// the last slice of the iteration will be the remainder.
1197 #[deriving(Clone)]
1198 pub struct Chunks<'a, T> {
1199     v: &'a [T],
1200     size: uint
1201 }
1202
1203 impl<'a, T> Iterator<&'a [T]> for Chunks<'a, T> {
1204     #[inline]
1205     fn next(&mut self) -> Option<&'a [T]> {
1206         if self.v.len() == 0 {
1207             None
1208         } else {
1209             let chunksz = cmp::min(self.v.len(), self.size);
1210             let (fst, snd) = self.v.split_at(chunksz);
1211             self.v = snd;
1212             Some(fst)
1213         }
1214     }
1215
1216     #[inline]
1217     fn size_hint(&self) -> (uint, Option<uint>) {
1218         if self.v.len() == 0 {
1219             (0, Some(0))
1220         } else {
1221             let (n, rem) = div_rem(self.v.len(), self.size);
1222             let n = if rem > 0 { n+1 } else { n };
1223             (n, Some(n))
1224         }
1225     }
1226 }
1227
1228 impl<'a, T> DoubleEndedIterator<&'a [T]> for Chunks<'a, T> {
1229     #[inline]
1230     fn next_back(&mut self) -> Option<&'a [T]> {
1231         if self.v.len() == 0 {
1232             None
1233         } else {
1234             let remainder = self.v.len() % self.size;
1235             let chunksz = if remainder != 0 { remainder } else { self.size };
1236             let (fst, snd) = self.v.split_at(self.v.len() - chunksz);
1237             self.v = fst;
1238             Some(snd)
1239         }
1240     }
1241 }
1242
1243 impl<'a, T> RandomAccessIterator<&'a [T]> for Chunks<'a, T> {
1244     #[inline]
1245     fn indexable(&self) -> uint {
1246         self.v.len()/self.size + if self.v.len() % self.size != 0 { 1 } else { 0 }
1247     }
1248
1249     #[inline]
1250     fn idx(&mut self, index: uint) -> Option<&'a [T]> {
1251         if index < self.indexable() {
1252             let lo = index * self.size;
1253             let mut hi = lo + self.size;
1254             if hi < lo || hi > self.v.len() { hi = self.v.len(); }
1255
1256             Some(self.v.slice(lo, hi))
1257         } else {
1258             None
1259         }
1260     }
1261 }
1262
1263 /// An iterator over a vector in (non-overlapping) mutable chunks (`size`  elements at a time). When
1264 /// the vector len is not evenly divided by the chunk size, the last slice of the iteration will be
1265 /// the remainder.
1266 pub struct MutChunks<'a, T> {
1267     v: &'a mut [T],
1268     chunk_size: uint
1269 }
1270
1271 impl<'a, T> Iterator<&'a mut [T]> for MutChunks<'a, T> {
1272     #[inline]
1273     fn next(&mut self) -> Option<&'a mut [T]> {
1274         if self.v.len() == 0 {
1275             None
1276         } else {
1277             let sz = cmp::min(self.v.len(), self.chunk_size);
1278             let tmp = mem::replace(&mut self.v, &mut []);
1279             let (head, tail) = tmp.mut_split_at(sz);
1280             self.v = tail;
1281             Some(head)
1282         }
1283     }
1284
1285     #[inline]
1286     fn size_hint(&self) -> (uint, Option<uint>) {
1287         if self.v.len() == 0 {
1288             (0, Some(0))
1289         } else {
1290             let (n, rem) = div_rem(self.v.len(), self.chunk_size);
1291             let n = if rem > 0 { n + 1 } else { n };
1292             (n, Some(n))
1293         }
1294     }
1295 }
1296
1297 impl<'a, T> DoubleEndedIterator<&'a mut [T]> for MutChunks<'a, T> {
1298     #[inline]
1299     fn next_back(&mut self) -> Option<&'a mut [T]> {
1300         if self.v.len() == 0 {
1301             None
1302         } else {
1303             let remainder = self.v.len() % self.chunk_size;
1304             let sz = if remainder != 0 { remainder } else { self.chunk_size };
1305             let tmp = mem::replace(&mut self.v, &mut []);
1306             let tmp_len = tmp.len();
1307             let (head, tail) = tmp.mut_split_at(tmp_len - sz);
1308             self.v = head;
1309             Some(tail)
1310         }
1311     }
1312 }
1313
1314
1315
1316
1317 //
1318 // Free functions
1319 //
1320
1321 /**
1322  * Converts a pointer to A into a slice of length 1 (without copying).
1323  */
1324 pub fn ref_slice<'a, A>(s: &'a A) -> &'a [A] {
1325     unsafe {
1326         transmute(Slice { data: s, len: 1 })
1327     }
1328 }
1329
1330 /**
1331  * Converts a pointer to A into a slice of length 1 (without copying).
1332  */
1333 pub fn mut_ref_slice<'a, A>(s: &'a mut A) -> &'a mut [A] {
1334     unsafe {
1335         let ptr: *const A = transmute(s);
1336         transmute(Slice { data: ptr, len: 1 })
1337     }
1338 }
1339
1340
1341
1342
1343 //
1344 // Submodules
1345 //
1346
1347 /// Unsafe operations
1348 pub mod raw {
1349     use mem::transmute;
1350     use ptr::RawPtr;
1351     use raw::Slice;
1352     use option::{None, Option, Some};
1353
1354     /**
1355      * Form a slice from a pointer and length (as a number of units,
1356      * not bytes).
1357      */
1358     #[inline]
1359     pub unsafe fn buf_as_slice<T,U>(p: *const T, len: uint, f: |v: &[T]| -> U)
1360                                -> U {
1361         f(transmute(Slice {
1362             data: p,
1363             len: len
1364         }))
1365     }
1366
1367     /**
1368      * Form a slice from a pointer and length (as a number of units,
1369      * not bytes).
1370      */
1371     #[inline]
1372     pub unsafe fn mut_buf_as_slice<T,
1373                                    U>(
1374                                    p: *mut T,
1375                                    len: uint,
1376                                    f: |v: &mut [T]| -> U)
1377                                    -> U {
1378         f(transmute(Slice {
1379             data: p as *const T,
1380             len: len
1381         }))
1382     }
1383
1384     /**
1385      * Returns a pointer to first element in slice and adjusts
1386      * slice so it no longer contains that element. Returns None
1387      * if the slice is empty. O(1).
1388      */
1389      #[inline]
1390     pub unsafe fn shift_ptr<T>(slice: &mut Slice<T>) -> Option<*const T> {
1391         if slice.len == 0 { return None; }
1392         let head: *const T = slice.data;
1393         slice.data = slice.data.offset(1);
1394         slice.len -= 1;
1395         Some(head)
1396     }
1397
1398     /**
1399      * Returns a pointer to last element in slice and adjusts
1400      * slice so it no longer contains that element. Returns None
1401      * if the slice is empty. O(1).
1402      */
1403      #[inline]
1404     pub unsafe fn pop_ptr<T>(slice: &mut Slice<T>) -> Option<*const T> {
1405         if slice.len == 0 { return None; }
1406         let tail: *const T = slice.data.offset((slice.len - 1) as int);
1407         slice.len -= 1;
1408         Some(tail)
1409     }
1410 }
1411
1412 /// Operations on `[u8]`.
1413 pub mod bytes {
1414     use collections::Collection;
1415     use ptr;
1416     use slice::MutableSlice;
1417
1418     /// A trait for operations on mutable `[u8]`s.
1419     pub trait MutableByteVector {
1420         /// Sets all bytes of the receiver to the given value.
1421         fn set_memory(self, value: u8);
1422     }
1423
1424     impl<'a> MutableByteVector for &'a mut [u8] {
1425         #[inline]
1426         #[allow(experimental)]
1427         fn set_memory(self, value: u8) {
1428             unsafe { ptr::set_memory(self.as_mut_ptr(), value, self.len()) };
1429         }
1430     }
1431
1432     /// Copies data from `src` to `dst`
1433     ///
1434     /// `src` and `dst` must not overlap. Fails if the length of `dst`
1435     /// is less than the length of `src`.
1436     #[inline]
1437     pub fn copy_memory(dst: &mut [u8], src: &[u8]) {
1438         // Bound checks are done at .copy_memory.
1439         unsafe { dst.copy_memory(src) }
1440     }
1441 }
1442
1443
1444
1445
1446 //
1447 // Boilerplate traits
1448 //
1449
1450 impl<'a,T:PartialEq> PartialEq for &'a [T] {
1451     fn eq(&self, other: & &'a [T]) -> bool {
1452         self.len() == other.len() &&
1453             order::eq(self.iter(), other.iter())
1454     }
1455     fn ne(&self, other: & &'a [T]) -> bool {
1456         self.len() != other.len() ||
1457             order::ne(self.iter(), other.iter())
1458     }
1459 }
1460
1461 impl<'a,T:Eq> Eq for &'a [T] {}
1462
1463 impl<'a,T:PartialEq, V: Vector<T>> Equiv<V> for &'a [T] {
1464     #[inline]
1465     fn equiv(&self, other: &V) -> bool { self.as_slice() == other.as_slice() }
1466 }
1467
1468 impl<'a,T:Ord> Ord for &'a [T] {
1469     fn cmp(&self, other: & &'a [T]) -> Ordering {
1470         order::cmp(self.iter(), other.iter())
1471     }
1472 }
1473
1474 impl<'a, T: PartialOrd> PartialOrd for &'a [T] {
1475     #[inline]
1476     fn partial_cmp(&self, other: &&'a [T]) -> Option<Ordering> {
1477         order::partial_cmp(self.iter(), other.iter())
1478     }
1479     #[inline]
1480     fn lt(&self, other: & &'a [T]) -> bool {
1481         order::lt(self.iter(), other.iter())
1482     }
1483     #[inline]
1484     fn le(&self, other: & &'a [T]) -> bool {
1485         order::le(self.iter(), other.iter())
1486     }
1487     #[inline]
1488     fn ge(&self, other: & &'a [T]) -> bool {
1489         order::ge(self.iter(), other.iter())
1490     }
1491     #[inline]
1492     fn gt(&self, other: & &'a [T]) -> bool {
1493         order::gt(self.iter(), other.iter())
1494     }
1495 }