]> git.lizzy.rs Git - rust.git/commitdiff
auto merge of #14054 : luqmana/rust/at, r=alexcrichton
authorbors <bors@rust-lang.org>
Fri, 9 May 2014 19:56:35 +0000 (12:56 -0700)
committerbors <bors@rust-lang.org>
Fri, 9 May 2014 19:56:35 +0000 (12:56 -0700)
`/data/local/tmp` seems to be more common.

102 files changed:
src/compiletest/runtest.rs
src/doc/guide-container.md
src/doc/rust.md
src/doc/tutorial.md
src/libcore/cast.rs
src/libcore/cell.rs
src/libcore/iter.rs
src/libcore/lib.rs
src/libcore/option.rs
src/libcore/ptr.rs
src/libcore/result.rs
src/libcore/should_not_exist.rs
src/libcore/str.rs
src/libgetopts/lib.rs
src/libnative/io/addrinfo.rs
src/libnative/io/file_win32.rs
src/libnative/io/mod.rs
src/libnative/io/process.rs
src/libnum/bigint.rs
src/librustc/back/rpath.rs
src/librustc/front/test.rs
src/librustc/lib.rs
src/librustc/middle/lint.rs
src/librustc/middle/resolve.rs
src/librustc/middle/trans/base.rs
src/librustc/middle/trans/consts.rs
src/librustc/middle/trans/monomorphize.rs
src/librustdoc/html/format.rs
src/librustdoc/html/render.rs
src/librustdoc/lib.rs
src/librustuv/addrinfo.rs
src/librustuv/process.rs
src/librustuv/uvio.rs
src/libserialize/base64.rs
src/libserialize/hex.rs
src/libserialize/json.rs
src/libserialize/serialize.rs
src/libstd/ascii.rs
src/libstd/io/mod.rs
src/libstd/io/net/addrinfo.rs
src/libstd/io/net/tcp.rs
src/libstd/io/net/udp.rs
src/libstd/io/net/unix.rs
src/libstd/io/process.rs
src/libstd/lib.rs
src/libstd/num/i16.rs
src/libstd/num/i32.rs
src/libstd/num/i64.rs
src/libstd/num/i8.rs
src/libstd/num/int.rs
src/libstd/num/int_macros.rs
src/libstd/num/strconv.rs
src/libstd/num/u16.rs
src/libstd/num/u32.rs
src/libstd/num/u64.rs
src/libstd/num/u8.rs
src/libstd/num/uint.rs
src/libstd/num/uint_macros.rs
src/libstd/os.rs
src/libstd/rt/args.rs
src/libstd/rt/rtio.rs
src/libstd/slice.rs
src/libstd/str.rs
src/libstd/strbuf.rs
src/libstd/sync/arc.rs
src/libstd/sync/deque.rs
src/libstd/unstable/dynamic_lib.rs
src/libstd/vec.rs
src/test/auxiliary/issue-11680.rs [new file with mode: 0644]
src/test/bench/core-map.rs
src/test/bench/core-set.rs
src/test/bench/core-std.rs
src/test/bench/rt-messaging-ping-pong.rs
src/test/bench/rt-parfib.rs
src/test/bench/rt-spawn-rate.rs
src/test/bench/shootout-binarytrees.rs
src/test/bench/shootout-chameneos-redux.rs
src/test/bench/shootout-fannkuch-redux.rs
src/test/bench/shootout-fasta-redux.rs
src/test/bench/shootout-fasta.rs
src/test/bench/shootout-k-nucleotide-pipes.rs
src/test/bench/shootout-mandelbrot.rs
src/test/bench/shootout-meteor.rs
src/test/bench/shootout-pidigits.rs
src/test/bench/shootout-spectralnorm.rs
src/test/bench/shootout-threadring.rs
src/test/compile-fail/issue-11493.rs [new file with mode: 0644]
src/test/compile-fail/issue-11680.rs [new file with mode: 0644]
src/test/compile-fail/lint-unused-mut-variables.rs
src/test/run-make/unicode-input/multiple_files.rs
src/test/run-make/unicode-input/span_length.rs
src/test/run-pass/backtrace.rs
src/test/run-pass/cleanup-shortcircuit.rs
src/test/run-pass/issue-10626.rs
src/test/run-pass/issue-13304.rs
src/test/run-pass/issue-4541.rs
src/test/run-pass/logging-separate-lines.rs
src/test/run-pass/out-of-stack.rs
src/test/run-pass/send_str_treemap.rs
src/test/run-pass/signal-exit-status.rs
src/test/run-pass/sigpipe-should-be-ignored.rs
src/test/run-pass/trait-to-str.rs

index 858e7334cff06b744e11d3428e2f4d6ea6c460f2..cea440afd9028592d728d41d504e05726f41dc70 100644 (file)
@@ -997,7 +997,7 @@ fn make_lib_name(config: &config, auxfile: &Path, testfile: &Path) -> Path {
 fn make_exe_name(config: &config, testfile: &Path) -> Path {
     let mut f = output_base_name(config, testfile);
     if !os::consts::EXE_SUFFIX.is_empty() {
-        match f.filename().map(|s| s + os::consts::EXE_SUFFIX.as_bytes()) {
+        match f.filename().map(|s| Vec::from_slice(s).append(os::consts::EXE_SUFFIX.as_bytes())) {
             Some(v) => f.set_filename(v),
             None => ()
         }
@@ -1091,7 +1091,7 @@ fn make_out_name(config: &config, testfile: &Path, extension: &str) -> Path {
 
 fn aux_output_dir_name(config: &config, testfile: &Path) -> Path {
     let mut f = output_base_name(config, testfile);
-    match f.filename().map(|s| s + bytes!(".libaux")) {
+    match f.filename().map(|s| Vec::from_slice(s).append(bytes!(".libaux"))) {
         Some(v) => f.set_filename(v),
         None => ()
     }
@@ -1273,7 +1273,7 @@ fn append_suffix_to_stem(p: &Path, suffix: &str) -> Path {
         (*p).clone()
     } else {
         let stem = p.filestem().unwrap();
-        p.with_filename(stem + bytes!("-") + suffix.as_bytes())
+        p.with_filename(Vec::from_slice(stem).append(bytes!("-")).append(suffix.as_bytes()))
     }
 }
 
index 6a54dc7ea1809366d770d2ee03c7950b29889821..1ab92d453785e41f1fe4f2b80ea3edf801e22408 100644 (file)
@@ -266,8 +266,8 @@ Iterators offer generic conversion to containers with the `collect` adaptor:
 
 ~~~
 let xs = [0, 1, 1, 2, 3, 5, 8];
-let ys = xs.iter().rev().skip(1).map(|&x| x * 2).collect::<~[int]>();
-assert_eq!(ys, ~[10, 6, 4, 2, 2, 0]);
+let ys = xs.iter().rev().skip(1).map(|&x| x * 2).collect::<Vec<int>>();
+assert_eq!(ys, vec![10, 6, 4, 2, 2, 0]);
 ~~~
 
 The method requires a type hint for the container type, if the surrounding code
@@ -278,14 +278,14 @@ implementing the `FromIterator` trait. For example, the implementation for
 vectors is as follows:
 
 ~~~ {.ignore}
-impl<A> FromIterator<A> for ~[A] {
-    pub fn from_iter<T: Iterator<A>>(iterator: &mut T) -> ~[A] {
+impl<T> FromIterator<T> for Vec<T> {
+    fn from_iter<I:Iterator<A>>(mut iterator: I) -> Vec<T> {
         let (lower, _) = iterator.size_hint();
-        let mut xs = with_capacity(lower);
-        for x in iterator {
-            xs.push(x);
+        let mut vector = Vec::with_capacity(lower);
+        for element in iterator {
+            vector.push(element);
         }
-        xs
+        vector
     }
 }
 ~~~
index 9a9e37479631fabf2965892f6f315e0ed04bff00..0e5af8626f8e8a24066e7c29c2695814f2fba274 100644 (file)
@@ -1741,10 +1741,10 @@ import public items from their destination, not private items.
 ## Attributes
 
 ~~~~ {.notrust .ebnf .gram}
-attribute : '#' '!' ? '[' attr_list ']' ;
-attr_list : attr [ ',' attr_list ]* ;
-attr : ident [ '=' literal
-             | '(' attr_list ')' ] ? ;
+attribute : '#' '!' ? '[' meta_item ']' ;
+meta_item : ident [ '=' literal
+                  | '(' meta_seq ')' ] ? ;
+meta_seq : meta_item [ ',' meta_seq ]* ;
 ~~~~
 
 Static entities in Rust &mdash; crates, modules and items &mdash; may have _attributes_
@@ -3598,18 +3598,18 @@ and the cast expression in `main`.
 Within the body of an item that has type parameter declarations, the names of its type parameters are types:
 
 ~~~~
-fn map<A: Clone, B: Clone>(f: |A| -> B, xs: &[A]) -> ~[B] {
+fn map<A: Clone, B: Clone>(f: |A| -> B, xs: &[A]) -> Vec<B> {
     if xs.len() == 0 {
-       return ~[];
+       return vec![];
     }
     let first: B = f(xs[0].clone());
-    let rest: ~[B] = map(f, xs.slice(1, xs.len()));
-    return ~[first] + rest;
+    let rest: Vec<B> = map(f, xs.slice(1, xs.len()));
+    return vec![first].append(rest.as_slice());
 }
 ~~~~
 
 Here, `first` has type `B`, referring to `map`'s `B` type parameter;
-and `rest` has type `~[B]`, a vector type with element type `B`.
+and `rest` has type `Vec<B>`, a vector type with element type `B`.
 
 ### Self types
 
index 56f9e8e5cbd7d7f3337396aa6ddbc85cefc99277..9b9153fe579462b47a9080e71c2743b9d6ebaa4c 100644 (file)
@@ -1588,8 +1588,8 @@ let mut numbers = vec![1, 2, 3];
 numbers.push(4);
 numbers.push(5);
 
-// The type of a unique vector is written as `~[int]`
-let more_numbers: ~[int] = numbers.move_iter().collect();
+// The type of a unique vector is written as `Vec<int>`
+let more_numbers: Vec<int> = numbers.move_iter().map(|i| i+1).collect();
 
 // The original `numbers` value can no longer be used, due to move semantics.
 
@@ -1633,7 +1633,7 @@ view[0] = 5;
 let ys: &mut [int] = &mut [1, 2, 3];
 ~~~
 
-Square brackets denote indexing into a vector:
+Square brackets denote indexing into a slice or fixed-size vector:
 
 ~~~~
 # enum Crayon { Almond, AntiqueBrass, Apricot,
@@ -1647,7 +1647,7 @@ match crayons[0] {
 }
 ~~~~
 
-A vector can be destructured using pattern matching:
+A slice or fixed-size vector can be destructured using pattern matching:
 
 ~~~~
 let numbers: &[int] = &[1, 2, 3];
@@ -1660,9 +1660,10 @@ let score = match numbers {
 ~~~~
 
 Both vectors and strings support a number of useful [methods](#methods),
-defined in [`std::vec`] and [`std::str`].
+defined in [`std::vec`], [`std::slice`], and [`std::str`].
 
 [`std::vec`]: std/vec/index.html
+[`std::slice`]: std/slice/index.html
 [`std::str`]: std/str/index.html
 
 # Ownership escape hatches
index 8cea197fbfa4a2f187b1fd9f061df68354ceddd6..cf99fdbd5d4c229739d746f424e4e9bb51fbcef6 100644 (file)
 use intrinsics;
 use ptr::copy_nonoverlapping_memory;
 
-/// Casts the value at `src` to U. The two types must have the same length.
-#[inline]
-pub unsafe fn transmute_copy<T, U>(src: &T) -> U {
-    let mut dest: U = mem::uninit();
-    let dest_ptr: *mut u8 = transmute(&mut dest);
-    let src_ptr: *u8 = transmute(src);
-    copy_nonoverlapping_memory(dest_ptr, src_ptr, mem::size_of::<U>());
-    dest
-}
-
-/**
- * Move a thing into the void
- *
- * The forget function will take ownership of the provided value but neglect
- * to run any required cleanup or memory-management operations on it.
- */
-#[inline]
-pub unsafe fn forget<T>(thing: T) { intrinsics::forget(thing); }
-
-/**
- * Force-increment the reference count on a shared box. If used
- * carelessly, this can leak the box.
- */
-#[inline]
-pub unsafe fn bump_box_refcount<T>(t: @T) { forget(t); }
-
 /**
  * Transform a value of one type into a value of another type.
  * Both types must have the same size and alignment.
@@ -54,10 +28,29 @@ pub unsafe fn transmute_copy<T, U>(src: &T) -> U {
  * ```
  */
 #[inline]
-pub unsafe fn transmute<L, G>(thing: L) -> G {
+pub unsafe fn transmute<T, U>(thing: T) -> U {
     intrinsics::transmute(thing)
 }
 
+/**
+ * Move a thing into the void
+ *
+ * The forget function will take ownership of the provided value but neglect
+ * to run any required cleanup or memory-management operations on it.
+ */
+#[inline]
+pub unsafe fn forget<T>(thing: T) { intrinsics::forget(thing); }
+
+/// Casts the value at `src` to U. The two types must have the same length.
+#[inline]
+pub unsafe fn transmute_copy<T, U>(src: &T) -> U {
+    let mut dest: U = mem::uninit();
+    let dest_ptr: *mut u8 = transmute(&mut dest);
+    let src_ptr: *u8 = transmute(src);
+    copy_nonoverlapping_memory(dest_ptr, src_ptr, mem::size_of::<U>());
+    dest
+}
+
 /// Coerce an immutable reference to be mutable.
 #[inline]
 #[deprecated="casting &T to &mut T is undefined behaviour: use Cell<T>, RefCell<T> or Unsafe<T>"]
@@ -106,7 +99,7 @@ pub unsafe fn copy_lifetime_vec<'a,S,T>(_ptr: &'a [S], ptr: &T) -> &'a T {
 
 #[cfg(test)]
 mod tests {
-    use cast::{bump_box_refcount, transmute};
+    use cast::transmute;
     use raw;
     use realstd::str::StrAllocating;
 
@@ -115,21 +108,6 @@ fn test_transmute_copy() {
         assert_eq!(1u, unsafe { ::cast::transmute_copy(&1) });
     }
 
-    #[test]
-    fn test_bump_managed_refcount() {
-        unsafe {
-            let managed = @"box box box".to_owned();      // refcount 1
-            bump_box_refcount(managed);     // refcount 2
-            let ptr: *int = transmute(managed); // refcount 2
-            let _box1: @~str = ::cast::transmute_copy(&ptr);
-            let _box2: @~str = ::cast::transmute_copy(&ptr);
-            assert!(*_box1 == "box box box".to_owned());
-            assert!(*_box2 == "box box box".to_owned());
-            // Will destroy _box1 and _box2. Without the bump, this would
-            // use-after-free. With too many bumps, it would leak.
-        }
-    }
-
     #[test]
     fn test_transmute() {
         unsafe {
index 8951c7d806ab2ca1ec064c3de1a009f454145b76..0413b31e8b76efa1694e3204a4db420fe9983150 100644 (file)
@@ -8,7 +8,7 @@
 // option. This file may not be copied, modified, or distributed
 // except according to those terms.
 
-//! Types dealing with dynamic mutability
+//! Types that provide interior mutability.
 
 use clone::Clone;
 use cmp::Eq;
index 5ee642cd8100d1a3f080ab7f0744e4e48c50545b..10ae30cf39d0cc08628657bd80f9269459492071 100644 (file)
@@ -455,8 +455,8 @@ fn advance(&mut self, f: |A| -> bool) -> bool {
     ///
     /// ```rust
     /// let a = [1, 2, 3, 4, 5];
-    /// let b: ~[int] = a.iter().map(|&x| x).collect();
-    /// assert!(a == b);
+    /// let b: Vec<int> = a.iter().map(|&x| x).collect();
+    /// assert!(a.as_slice() == b.as_slice());
     /// ```
     #[inline]
     fn collect<B: FromIterator<A>>(&mut self) -> B {
@@ -2340,8 +2340,8 @@ mod tests {
     #[test]
     fn test_counter_from_iter() {
         let it = count(0, 5).take(10);
-        let xs: ~[int] = FromIterator::from_iter(it);
-        assert_eq!(xs, box [0, 5, 10, 15, 20, 25, 30, 35, 40, 45]);
+        let xs: Vec<int> = FromIterator::from_iter(it);
+        assert_eq!(xs, vec![0, 5, 10, 15, 20, 25, 30, 35, 40, 45]);
     }
 
     #[test]
@@ -2371,7 +2371,7 @@ fn test_iterator_chain() {
     fn test_filter_map() {
         let mut it = count(0u, 1u).take(10)
             .filter_map(|x| if x % 2 == 0 { Some(x*x) } else { None });
-        assert_eq!(it.collect::<~[uint]>(), box [0*0, 2*2, 4*4, 6*6, 8*8]);
+        assert_eq!(it.collect::<Vec<uint>>(), vec![0*0, 2*2, 4*4, 6*6, 8*8]);
     }
 
     #[test]
@@ -2493,7 +2493,7 @@ fn test_inspect() {
         let ys = xs.iter()
                    .map(|&x| x)
                    .inspect(|_| n += 1)
-                   .collect::<~[uint]>();
+                   .collect::<Vec<uint>>();
 
         assert_eq!(n, xs.len());
         assert_eq!(xs.as_slice(), ys.as_slice());
@@ -2628,8 +2628,8 @@ fn test_iterator_size_hint() {
 
     #[test]
     fn test_collect() {
-        let a = box [1, 2, 3, 4, 5];
-        let b: ~[int] = a.iter().map(|&x| x).collect();
+        let a = vec![1, 2, 3, 4, 5];
+        let b: Vec<int> = a.iter().map(|&x| x).collect();
         assert_eq!(a, b);
     }
 
@@ -2702,7 +2702,7 @@ fn test_rev() {
         let mut it = xs.iter();
         it.next();
         it.next();
-        assert_eq!(it.rev().map(|&x| x).collect::<~[int]>(), box [16, 14, 12, 10, 8, 6]);
+        assert_eq!(it.rev().map(|&x| x).collect::<Vec<int>>(), vec![16, 14, 12, 10, 8, 6]);
     }
 
     #[test]
@@ -2940,12 +2940,12 @@ fn test_random_access_cycle() {
 
     #[test]
     fn test_double_ended_range() {
-        assert_eq!(range(11i, 14).rev().collect::<~[int]>(), box [13i, 12, 11]);
+        assert_eq!(range(11i, 14).rev().collect::<Vec<int>>(), vec![13i, 12, 11]);
         for _ in range(10i, 0).rev() {
             fail!("unreachable");
         }
 
-        assert_eq!(range(11u, 14).rev().collect::<~[uint]>(), box [13u, 12, 11]);
+        assert_eq!(range(11u, 14).rev().collect::<Vec<uint>>(), vec![13u, 12, 11]);
         for _ in range(10u, 0).rev() {
             fail!("unreachable");
         }
@@ -2997,13 +2997,14 @@ fn one() -> Foo {
             }
         }
 
-        assert_eq!(range(0i, 5).collect::<~[int]>(), box [0i, 1, 2, 3, 4]);
-        assert_eq!(range(-10i, -1).collect::<~[int]>(), box [-10, -9, -8, -7, -6, -5, -4, -3, -2]);
-        assert_eq!(range(0i, 5).rev().collect::<~[int]>(), box [4, 3, 2, 1, 0]);
-        assert_eq!(range(200, -5).collect::<~[int]>(), box []);
-        assert_eq!(range(200, -5).rev().collect::<~[int]>(), box []);
-        assert_eq!(range(200, 200).collect::<~[int]>(), box []);
-        assert_eq!(range(200, 200).rev().collect::<~[int]>(), box []);
+        assert_eq!(range(0i, 5).collect::<Vec<int>>(), vec![0i, 1, 2, 3, 4]);
+        assert_eq!(range(-10i, -1).collect::<Vec<int>>(),
+                   vec![-10, -9, -8, -7, -6, -5, -4, -3, -2]);
+        assert_eq!(range(0i, 5).rev().collect::<Vec<int>>(), vec![4, 3, 2, 1, 0]);
+        assert_eq!(range(200, -5).collect::<Vec<int>>(), vec![]);
+        assert_eq!(range(200, -5).rev().collect::<Vec<int>>(), vec![]);
+        assert_eq!(range(200, 200).collect::<Vec<int>>(), vec![]);
+        assert_eq!(range(200, 200).rev().collect::<Vec<int>>(), vec![]);
 
         assert_eq!(range(0i, 100).size_hint(), (100, Some(100)));
         // this test is only meaningful when sizeof uint < sizeof u64
@@ -3014,32 +3015,32 @@ fn one() -> Foo {
 
     #[test]
     fn test_range_inclusive() {
-        assert_eq!(range_inclusive(0i, 5).collect::<~[int]>(), box [0i, 1, 2, 3, 4, 5]);
-        assert_eq!(range_inclusive(0i, 5).rev().collect::<~[int]>(), box [5i, 4, 3, 2, 1, 0]);
-        assert_eq!(range_inclusive(200, -5).collect::<~[int]>(), box []);
-        assert_eq!(range_inclusive(200, -5).rev().collect::<~[int]>(), box []);
-        assert_eq!(range_inclusive(200, 200).collect::<~[int]>(), box [200]);
-        assert_eq!(range_inclusive(200, 200).rev().collect::<~[int]>(), box [200]);
+        assert_eq!(range_inclusive(0i, 5).collect::<Vec<int>>(), vec![0i, 1, 2, 3, 4, 5]);
+        assert_eq!(range_inclusive(0i, 5).rev().collect::<Vec<int>>(), vec![5i, 4, 3, 2, 1, 0]);
+        assert_eq!(range_inclusive(200, -5).collect::<Vec<int>>(), vec![]);
+        assert_eq!(range_inclusive(200, -5).rev().collect::<Vec<int>>(), vec![]);
+        assert_eq!(range_inclusive(200, 200).collect::<Vec<int>>(), vec![200]);
+        assert_eq!(range_inclusive(200, 200).rev().collect::<Vec<int>>(), vec![200]);
     }
 
     #[test]
     fn test_range_step() {
-        assert_eq!(range_step(0i, 20, 5).collect::<~[int]>(), box [0, 5, 10, 15]);
-        assert_eq!(range_step(20i, 0, -5).collect::<~[int]>(), box [20, 15, 10, 5]);
-        assert_eq!(range_step(20i, 0, -6).collect::<~[int]>(), box [20, 14, 8, 2]);
-        assert_eq!(range_step(200u8, 255, 50).collect::<~[u8]>(), box [200u8, 250]);
-        assert_eq!(range_step(200, -5, 1).collect::<~[int]>(), box []);
-        assert_eq!(range_step(200, 200, 1).collect::<~[int]>(), box []);
+        assert_eq!(range_step(0i, 20, 5).collect::<Vec<int>>(), vec![0, 5, 10, 15]);
+        assert_eq!(range_step(20i, 0, -5).collect::<Vec<int>>(), vec![20, 15, 10, 5]);
+        assert_eq!(range_step(20i, 0, -6).collect::<Vec<int>>(), vec![20, 14, 8, 2]);
+        assert_eq!(range_step(200u8, 255, 50).collect::<Vec<u8>>(), vec![200u8, 250]);
+        assert_eq!(range_step(200, -5, 1).collect::<Vec<int>>(), vec![]);
+        assert_eq!(range_step(200, 200, 1).collect::<Vec<int>>(), vec![]);
     }
 
     #[test]
     fn test_range_step_inclusive() {
-        assert_eq!(range_step_inclusive(0i, 20, 5).collect::<~[int]>(), box [0, 5, 10, 15, 20]);
-        assert_eq!(range_step_inclusive(20i, 0, -5).collect::<~[int]>(), box [20, 15, 10, 5, 0]);
-        assert_eq!(range_step_inclusive(20i, 0, -6).collect::<~[int]>(), box [20, 14, 8, 2]);
-        assert_eq!(range_step_inclusive(200u8, 255, 50).collect::<~[u8]>(), box [200u8, 250]);
-        assert_eq!(range_step_inclusive(200, -5, 1).collect::<~[int]>(), box []);
-        assert_eq!(range_step_inclusive(200, 200, 1).collect::<~[int]>(), box [200]);
+        assert_eq!(range_step_inclusive(0i, 20, 5).collect::<Vec<int>>(), vec![0, 5, 10, 15, 20]);
+        assert_eq!(range_step_inclusive(20i, 0, -5).collect::<Vec<int>>(), vec![20, 15, 10, 5, 0]);
+        assert_eq!(range_step_inclusive(20i, 0, -6).collect::<Vec<int>>(), vec![20, 14, 8, 2]);
+        assert_eq!(range_step_inclusive(200u8, 255, 50).collect::<Vec<u8>>(), vec![200u8, 250]);
+        assert_eq!(range_step_inclusive(200, -5, 1).collect::<Vec<int>>(), vec![]);
+        assert_eq!(range_step_inclusive(200, 200, 1).collect::<Vec<int>>(), vec![200]);
     }
 
     #[test]
index 53de765b89c1d43569ef5d6f880f205325912f88..38bce7a4741bf9ae7c38c969e2288f85255b625c 100644 (file)
 mod std {
     pub use clone;
     pub use cmp;
+    pub use kinds;
 
     #[cfg(test)] pub use realstd::fmt;    // needed for fail!()
     #[cfg(test)] pub use realstd::rt;     // needed for fail!()
     #[cfg(test)] pub use realstd::option; // needed for assert!()
     #[cfg(test)] pub use realstd::os;     // needed for tests
+    #[cfg(test)] pub use realstd::slice;  // needed for tests
+    #[cfg(test)] pub use realstd::vec;    // needed for vec![]
 }
index c6884a8002f799a06f17efe7d9dbe52e8ce2280a..2f8457e93f671b31725370c3a520c308481ff724 100644 (file)
@@ -844,22 +844,22 @@ fn test_mutate() {
 
     #[test]
     fn test_collect() {
-        let v: Option<~[int]> = collect(range(0, 0)
-                                        .map(|_| Some(0)));
-        assert_eq!(v, Some(box []));
+        let v: Option<Vec<int>> = collect(range(0, 0)
+                                          .map(|_| Some(0)));
+        assert_eq!(v, Some(vec![]));
 
-        let v: Option<~[int]> = collect(range(0, 3)
-                                        .map(|x| Some(x)));
-        assert_eq!(v, Some(box [0, 1, 2]));
+        let v: Option<Vec<int>> = collect(range(0, 3)
+                                          .map(|x| Some(x)));
+        assert_eq!(v, Some(vec![0, 1, 2]));
 
-        let v: Option<~[int]> = collect(range(0, 3)
-                                        .map(|x| if x > 1 { None } else { Some(x) }));
+        let v: Option<Vec<int>> = collect(range(0, 3)
+                                          .map(|x| if x > 1 { None } else { Some(x) }));
         assert_eq!(v, None);
 
         // test that it does not take more elements than it needs
         let mut functions = [|| Some(()), || None, || fail!()];
 
-        let v: Option<~[()]> = collect(functions.mut_iter().map(|f| (*f)()));
+        let v: Option<Vec<()>> = collect(functions.mut_iter().map(|f| (*f)()));
 
         assert_eq!(v, None);
     }
index e3a3f78dcb9257518bce768d43e465adebc5f122..bb587c0e42d03cd186e70b82b7d4db1f5ae9e38d 100644 (file)
@@ -8,6 +8,8 @@
 // option. This file may not be copied, modified, or distributed
 // except according to those terms.
 
+// FIXME: talk about offset, copy_memory, copy_nonoverlapping_memory
+
 //! Conveniences for working with unsafe pointers, the `*T`, and `*mut T` types.
 //!
 //! Working with unsafe pointers in Rust is fairly uncommon,
index 337b2ac89dd7aacc61ac982df1358d959d8e6932..27ae2ad9946f5718ae2852e5ee3a69029b9152fe 100644 (file)
@@ -653,20 +653,20 @@ pub fn test_impl_map_err() {
 
     #[test]
     fn test_collect() {
-        let v: Result<~[int], ()> = collect(range(0, 0).map(|_| Ok::<int, ()>(0)));
-        assert_eq!(v, Ok(box []));
+        let v: Result<Vec<int>, ()> = collect(range(0, 0).map(|_| Ok::<int, ()>(0)));
+        assert_eq!(v, Ok(vec![]));
 
-        let v: Result<~[int], ()> = collect(range(0, 3).map(|x| Ok::<int, ()>(x)));
-        assert_eq!(v, Ok(box [0, 1, 2]));
+        let v: Result<Vec<int>, ()> = collect(range(0, 3).map(|x| Ok::<int, ()>(x)));
+        assert_eq!(v, Ok(vec![0, 1, 2]));
 
-        let v: Result<~[int], int> = collect(range(0, 3)
-                                             .map(|x| if x > 1 { Err(x) } else { Ok(x) }));
+        let v: Result<Vec<int>, int> = collect(range(0, 3)
+                                               .map(|x| if x > 1 { Err(x) } else { Ok(x) }));
         assert_eq!(v, Err(2));
 
         // test that it does not take more elements than it needs
         let mut functions = [|| Ok(()), || Err(1), || fail!()];
 
-        let v: Result<~[()], int> = collect(functions.mut_iter().map(|f| (*f)()));
+        let v: Result<Vec<()>, int> = collect(functions.mut_iter().map(|f| (*f)()));
         assert_eq!(v, Err(1));
     }
 
index 50447f0c5b375cb1e7a5591780106186cbce1e82..0e6baaa518a73e8aa20b1ed51c915949a20ecf70 100644 (file)
@@ -13,8 +13,9 @@
 use clone::Clone;
 use container::Container;
 use default::Default;
+use finally::try_finally;
 use intrinsics;
-use iter::{Iterator, FromIterator};
+use iter::{range, Iterator, FromIterator};
 use mem;
 use num::{CheckedMul, CheckedAdd};
 use option::{Some, None};
@@ -25,7 +26,6 @@
 use str::StrSlice;
 
 #[cfg(not(test))] use ops::Add;
-#[cfg(not(test))] use slice::Vector;
 
 #[allow(ctypes)]
 extern {
@@ -147,56 +147,34 @@ fn add(&self, rhs: & &'a str) -> ~str {
 impl<A: Clone> Clone for ~[A] {
     #[inline]
     fn clone(&self) -> ~[A] {
-        self.iter().map(|a| a.clone()).collect()
-    }
-}
-
-impl<A> FromIterator<A> for ~[A] {
-    fn from_iter<T: Iterator<A>>(mut iterator: T) -> ~[A] {
-        let (lower, _) = iterator.size_hint();
-        let cap = if lower == 0 {16} else {lower};
-        let mut cap = cap.checked_mul(&mem::size_of::<A>()).unwrap();
-        let mut len = 0;
+        let len = self.len();
+        let data_size = len.checked_mul(&mem::size_of::<A>()).unwrap();
+        let size = mem::size_of::<Vec<()>>().checked_add(&data_size).unwrap();
 
         unsafe {
-            let mut ptr = alloc(cap) as *mut Vec<A>;
-            let mut ret = cast::transmute(ptr);
-            for elt in iterator {
-                if len * mem::size_of::<A>() >= cap {
-                    cap = cap.checked_mul(&2).unwrap();
-                    let ptr2 = alloc(cap) as *mut Vec<A>;
-                    ptr::copy_nonoverlapping_memory(&mut (*ptr2).data,
-                                                    &(*ptr).data,
-                                                    len);
-                    free(ptr as *u8);
-                    cast::forget(ret);
-                    ret = cast::transmute(ptr2);
-                    ptr = ptr2;
-                }
-
-                let base = &mut (*ptr).data as *mut A;
-                intrinsics::move_val_init(&mut *base.offset(len as int), elt);
-                len += 1;
-                (*ptr).fill = len * mem::nonzero_size_of::<A>();
-            }
-            ret
+            let ret = alloc(size) as *mut Vec<A>;
+
+            (*ret).fill = len * mem::nonzero_size_of::<A>();
+            (*ret).alloc = len * mem::nonzero_size_of::<A>();
+
+            let mut i = 0;
+            let p = &mut (*ret).data as *mut _ as *mut A;
+            try_finally(
+                &mut i, (),
+                |i, ()| while *i < len {
+                    mem::move_val_init(
+                        &mut(*p.offset(*i as int)),
+                        self.unsafe_ref(*i).clone());
+                    *i += 1;
+                },
+                |i| if *i < len {
+                    // we must be failing, clean up after ourselves
+                    for j in range(0, *i as int) {
+                        ptr::read(&*p.offset(j));
+                    }
+                    free(ret as *u8);
+                });
+            cast::transmute(ret)
         }
     }
 }
-
-#[cfg(not(test))]
-impl<'a,T:Clone, V: Vector<T>> Add<V, ~[T]> for &'a [T] {
-    #[inline]
-    fn add(&self, rhs: &V) -> ~[T] {
-        let first = self.iter().map(|t| t.clone());
-        first.chain(rhs.as_slice().iter().map(|t| t.clone())).collect()
-    }
-}
-
-#[cfg(not(test))]
-impl<T:Clone, V: Vector<T>> Add<V, ~[T]> for ~[T] {
-    #[inline]
-    fn add(&self, rhs: &V) -> ~[T] {
-        self.as_slice() + rhs.as_slice()
-    }
-}
index 9d9e12d0ad594c52629bc5e34bf3c9680ab201e9..689f59b471c90402c7ec9298d15d8bc697f8e58d 100644 (file)
@@ -621,12 +621,12 @@ fn size_hint(&self) -> (uint, Option<uint>) {
 ///          0x0073, 0xDD1E, 0x0069, 0x0063,
 ///          0xD834];
 ///
-/// assert_eq!(str::utf16_items(v).collect::<~[_]>(),
-///            ~[ScalarValue('𝄞'),
-///              ScalarValue('m'), ScalarValue('u'), ScalarValue('s'),
-///              LoneSurrogate(0xDD1E),
-///              ScalarValue('i'), ScalarValue('c'),
-///              LoneSurrogate(0xD834)]);
+/// assert_eq!(str::utf16_items(v).collect::<Vec<_>>(),
+///            vec![ScalarValue('𝄞'),
+///                 ScalarValue('m'), ScalarValue('u'), ScalarValue('s'),
+///                 LoneSurrogate(0xDD1E),
+///                 ScalarValue('i'), ScalarValue('c'),
+///                 LoneSurrogate(0xD834)]);
 /// ```
 pub fn utf16_items<'a>(v: &'a [u16]) -> UTF16Items<'a> {
     UTF16Items { iter : v.iter() }
@@ -896,8 +896,8 @@ pub trait StrSlice<'a> {
     /// # Example
     ///
     /// ```rust
-    /// let v: ~[char] = "abc åäö".chars().collect();
-    /// assert_eq!(v, ~['a', 'b', 'c', ' ', 'å', 'ä', 'ö']);
+    /// let v: Vec<char> = "abc åäö".chars().collect();
+    /// assert_eq!(v, vec!['a', 'b', 'c', ' ', 'å', 'ä', 'ö']);
     /// ```
     fn chars(&self) -> Chars<'a>;
 
@@ -925,14 +925,14 @@ pub trait StrSlice<'a> {
     /// # Example
     ///
     /// ```rust
-    /// let v: ~[&str] = "Mary had a little lamb".split(' ').collect();
-    /// assert_eq!(v, ~["Mary", "had", "a", "little", "lamb"]);
+    /// let v: Vec<&str> = "Mary had a little lamb".split(' ').collect();
+    /// assert_eq!(v, vec!["Mary", "had", "a", "little", "lamb"]);
     ///
-    /// let v: ~[&str] = "abc1def2ghi".split(|c: char| c.is_digit()).collect();
-    /// assert_eq!(v, ~["abc", "def", "ghi"]);
+    /// let v: Vec<&str> = "abc1def2ghi".split(|c: char| c.is_digit()).collect();
+    /// assert_eq!(v, vec!["abc", "def", "ghi"]);
     ///
-    /// let v: ~[&str] = "lionXXtigerXleopard".split('X').collect();
-    /// assert_eq!(v, ~["lion", "", "tiger", "leopard"]);
+    /// let v: Vec<&str> = "lionXXtigerXleopard".split('X').collect();
+    /// assert_eq!(v, vec!["lion", "", "tiger", "leopard"]);
     /// ```
     fn split<Sep: CharEq>(&self, sep: Sep) -> CharSplits<'a, Sep>;
 
@@ -943,14 +943,14 @@ pub trait StrSlice<'a> {
     /// # Example
     ///
     /// ```rust
-    /// let v: ~[&str] = "Mary had a little lambda".splitn(' ', 2).collect();
-    /// assert_eq!(v, ~["Mary", "had", "a little lambda"]);
+    /// let v: Vec<&str> = "Mary had a little lambda".splitn(' ', 2).collect();
+    /// assert_eq!(v, vec!["Mary", "had", "a little lambda"]);
     ///
-    /// let v: ~[&str] = "abc1def2ghi".splitn(|c: char| c.is_digit(), 1).collect();
-    /// assert_eq!(v, ~["abc", "def2ghi"]);
+    /// let v: Vec<&str> = "abc1def2ghi".splitn(|c: char| c.is_digit(), 1).collect();
+    /// assert_eq!(v, vec!["abc", "def2ghi"]);
     ///
-    /// let v: ~[&str] = "lionXXtigerXleopard".splitn('X', 2).collect();
-    /// assert_eq!(v, ~["lion", "", "tigerXleopard"]);
+    /// let v: Vec<&str> = "lionXXtigerXleopard".splitn('X', 2).collect();
+    /// assert_eq!(v, vec!["lion", "", "tigerXleopard"]);
     /// ```
     fn splitn<Sep: CharEq>(&self, sep: Sep, count: uint) -> CharSplitsN<'a, Sep>;
 
@@ -963,20 +963,20 @@ pub trait StrSlice<'a> {
     /// # Example
     ///
     /// ```rust
-    /// let v: ~[&str] = "A.B.".split_terminator('.').collect();
-    /// assert_eq!(v, ~["A", "B"]);
+    /// let v: Vec<&str> = "A.B.".split_terminator('.').collect();
+    /// assert_eq!(v, vec!["A", "B"]);
     ///
-    /// let v: ~[&str] = "A..B..".split_terminator('.').collect();
-    /// assert_eq!(v, ~["A", "", "B", ""]);
+    /// let v: Vec<&str> = "A..B..".split_terminator('.').collect();
+    /// assert_eq!(v, vec!["A", "", "B", ""]);
     ///
-    /// let v: ~[&str] = "Mary had a little lamb".split(' ').rev().collect();
-    /// assert_eq!(v, ~["lamb", "little", "a", "had", "Mary"]);
+    /// let v: Vec<&str> = "Mary had a little lamb".split(' ').rev().collect();
+    /// assert_eq!(v, vec!["lamb", "little", "a", "had", "Mary"]);
     ///
-    /// let v: ~[&str] = "abc1def2ghi".split(|c: char| c.is_digit()).rev().collect();
-    /// assert_eq!(v, ~["ghi", "def", "abc"]);
+    /// let v: Vec<&str> = "abc1def2ghi".split(|c: char| c.is_digit()).rev().collect();
+    /// assert_eq!(v, vec!["ghi", "def", "abc"]);
     ///
-    /// let v: ~[&str] = "lionXXtigerXleopard".split('X').rev().collect();
-    /// assert_eq!(v, ~["leopard", "tiger", "", "lion"]);
+    /// let v: Vec<&str> = "lionXXtigerXleopard".split('X').rev().collect();
+    /// assert_eq!(v, vec!["leopard", "tiger", "", "lion"]);
     /// ```
     fn split_terminator<Sep: CharEq>(&self, sep: Sep) -> CharSplits<'a, Sep>;
 
@@ -991,14 +991,14 @@ pub trait StrSlice<'a> {
     /// # Example
     ///
     /// ```rust
-    /// let v: ~[&str] = "Mary had a little lamb".rsplitn(' ', 2).collect();
-    /// assert_eq!(v, ~["lamb", "little", "Mary had a"]);
+    /// let v: Vec<&str> = "Mary had a little lamb".rsplitn(' ', 2).collect();
+    /// assert_eq!(v, vec!["lamb", "little", "Mary had a"]);
     ///
-    /// let v: ~[&str] = "abc1def2ghi".rsplitn(|c: char| c.is_digit(), 1).collect();
-    /// assert_eq!(v, ~["ghi", "abc1def"]);
+    /// let v: Vec<&str> = "abc1def2ghi".rsplitn(|c: char| c.is_digit(), 1).collect();
+    /// assert_eq!(v, vec!["ghi", "abc1def"]);
     ///
-    /// let v: ~[&str] = "lionXXtigerXleopard".rsplitn('X', 2).collect();
-    /// assert_eq!(v, ~["leopard", "tiger", "lionX"]);
+    /// let v: Vec<&str> = "lionXXtigerXleopard".rsplitn('X', 2).collect();
+    /// assert_eq!(v, vec!["leopard", "tiger", "lionX"]);
     /// ```
     fn rsplitn<Sep: CharEq>(&self, sep: Sep, count: uint) -> CharSplitsN<'a, Sep>;
 
@@ -1013,14 +1013,14 @@ pub trait StrSlice<'a> {
     /// # Example
     ///
     /// ```rust
-    /// let v: ~[(uint, uint)] = "abcXXXabcYYYabc".match_indices("abc").collect();
-    /// assert_eq!(v, ~[(0,3), (6,9), (12,15)]);
+    /// let v: Vec<(uint, uint)> = "abcXXXabcYYYabc".match_indices("abc").collect();
+    /// assert_eq!(v, vec![(0,3), (6,9), (12,15)]);
     ///
-    /// let v: ~[(uint, uint)] = "1abcabc2".match_indices("abc").collect();
-    /// assert_eq!(v, ~[(1,4), (4,7)]);
+    /// let v: Vec<(uint, uint)> = "1abcabc2".match_indices("abc").collect();
+    /// assert_eq!(v, vec![(1,4), (4,7)]);
     ///
-    /// let v: ~[(uint, uint)] = "ababa".match_indices("aba").collect();
-    /// assert_eq!(v, ~[(0, 3)]); // only the first `aba`
+    /// let v: Vec<(uint, uint)> = "ababa".match_indices("aba").collect();
+    /// assert_eq!(v, vec![(0, 3)]); // only the first `aba`
     /// ```
     fn match_indices(&self, sep: &'a str) -> MatchIndices<'a>;
 
@@ -1029,11 +1029,11 @@ pub trait StrSlice<'a> {
     /// # Example
     ///
     /// ```rust
-    /// let v: ~[&str] = "abcXXXabcYYYabc".split_str("abc").collect();
-    /// assert_eq!(v, ~["", "XXX", "YYY", ""]);
+    /// let v: Vec<&str> = "abcXXXabcYYYabc".split_str("abc").collect();
+    /// assert_eq!(v, vec!["", "XXX", "YYY", ""]);
     ///
-    /// let v: ~[&str] = "1abcabc2".split_str("abc").collect();
-    /// assert_eq!(v, ~["1", "", "2"]);
+    /// let v: Vec<&str> = "1abcabc2".split_str("abc").collect();
+    /// assert_eq!(v, vec!["1", "", "2"]);
     /// ```
     fn split_str(&self, &'a str) -> StrSplits<'a>;
 
@@ -1045,8 +1045,8 @@ pub trait StrSlice<'a> {
     ///
     /// ```rust
     /// let four_lines = "foo\nbar\n\nbaz\n";
-    /// let v: ~[&str] = four_lines.lines().collect();
-    /// assert_eq!(v, ~["foo", "bar", "", "baz"]);
+    /// let v: Vec<&str> = four_lines.lines().collect();
+    /// assert_eq!(v, vec!["foo", "bar", "", "baz"]);
     /// ```
     fn lines(&self) -> CharSplits<'a, char>;
 
@@ -1058,8 +1058,8 @@ pub trait StrSlice<'a> {
     ///
     /// ```rust
     /// let four_lines = "foo\r\nbar\n\r\nbaz\n";
-    /// let v: ~[&str] = four_lines.lines_any().collect();
-    /// assert_eq!(v, ~["foo", "bar", "", "baz"]);
+    /// let v: Vec<&str> = four_lines.lines_any().collect();
+    /// assert_eq!(v, vec!["foo", "bar", "", "baz"]);
     /// ```
     fn lines_any(&self) -> AnyLines<'a>;
 
@@ -1071,8 +1071,8 @@ pub trait StrSlice<'a> {
     ///
     /// ```rust
     /// let some_words = " Mary   had\ta little  \n\t lamb";
-    /// let v: ~[&str] = some_words.words().collect();
-    /// assert_eq!(v, ~["Mary", "had", "a", "little", "lamb"]);
+    /// let v: Vec<&str> = some_words.words().collect();
+    /// assert_eq!(v, vec!["Mary", "had", "a", "little", "lamb"]);
     /// ```
     fn words(&self) -> Words<'a>;
 
@@ -1469,7 +1469,8 @@ pub trait StrSlice<'a> {
     ///
     /// ```rust
     /// let string = "a\nb\nc";
-    /// let lines: ~[&str] = string.lines().collect();
+    /// let lines: Vec<&str> = string.lines().collect();
+    /// let lines = lines.as_slice();
     ///
     /// assert!(string.subslice_offset(lines[0]) == 0); // &"a"
     /// assert!(string.subslice_offset(lines[1]) == 2); // &"b"
index 78c2b6c99e955000a83673924d01aeab9ce7ae7c..3de1dde240c9722ae81f48d72997bda6f29cffe6 100644 (file)
@@ -51,7 +51,7 @@
 //! fn main() {
 //!     let args = os::args();
 //!
-//!     let program = args[0].clone();
+//!     let program = args.get(0).clone();
 //!
 //!     let opts = [
 //!         optopt("o", "", "set output file name", "NAME"),
index 71944202205ffcd47118e3f6e524f3c8ad739fcd..57b87f21521e8221844e230b806f2888fcf12f45 100644 (file)
@@ -22,7 +22,7 @@
 
 impl GetAddrInfoRequest {
     pub fn run(host: Option<&str>, servname: Option<&str>,
-               hint: Option<ai::Hint>) -> Result<~[ai::Info], IoError> {
+               hint: Option<ai::Hint>) -> Result<Vec<ai::Info>, IoError> {
         assert!(host.is_some() || servname.is_some());
 
         let c_host = host.map_or(unsafe { CString::new(null(), true) }, |x| x.to_c_str());
@@ -80,7 +80,7 @@ pub fn run(host: Option<&str>, servname: Option<&str>,
 
         unsafe { freeaddrinfo(res); }
 
-        Ok(addrs.move_iter().collect())
+        Ok(addrs)
     }
 }
 
index 282f9c2e343475e2079ec6dce95b068931435090..42e5ad062ee84b078fc6372c351da52c71f84c85 100644 (file)
@@ -22,7 +22,7 @@
 use std::rt::rtio;
 use std::str;
 use std::sync::arc::UnsafeArc;
-use std::slice;
+use std::vec;
 
 use io::IoResult;
 
@@ -368,8 +368,8 @@ fn prune(root: &CString, dirs: Vec<Path>) -> Vec<Path> {
                 if fp_buf as uint == 0 {
                     fail!("os::list_dir() failure: got null ptr from wfd");
                 } else {
-                    let fp_vec = slice::from_buf(fp_buf, libc::wcslen(fp_buf) as uint);
-                    let fp_trimmed = str::truncate_utf16_at_nul(fp_vec);
+                    let fp_vec = vec::raw::from_buf(fp_buf, libc::wcslen(fp_buf) as uint);
+                    let fp_trimmed = str::truncate_utf16_at_nul(fp_vec.as_slice());
                     let fp_str = str::from_utf16(fp_trimmed)
                             .expect("rust_list_dir_wfd_fp_buf returned invalid UTF-16");
                     paths.push(Path::new(fp_str));
index 58fcd60f13815495f7ba58b4ff9e34269f31b467..f2c2c66e1425fe521be0ff897e2a17c10b98b567 100644 (file)
@@ -194,7 +194,7 @@ fn unix_connect(&mut self, path: &CString,
         })
     }
     fn get_host_addresses(&mut self, host: Option<&str>, servname: Option<&str>,
-                          hint: Option<ai::Hint>) -> IoResult<~[ai::Info]> {
+                          hint: Option<ai::Hint>) -> IoResult<Vec<ai::Info>> {
         addrinfo::GetAddrInfoRequest::run(host, servname, hint)
     }
 
@@ -260,7 +260,7 @@ fn timer_init(&mut self) -> IoResult<Box<RtioTimer:Send>> {
     }
     fn spawn(&mut self, config: ProcessConfig)
             -> IoResult<(Box<RtioProcess:Send>,
-                         ~[Option<Box<RtioPipe:Send>>])> {
+                         Vec<Option<Box<RtioPipe:Send>>>)> {
         process::Process::spawn(config).map(|(p, io)| {
             (box p as Box<RtioProcess:Send>,
              io.move_iter().map(|p| p.map(|p| {
index efdab990d18223f1e73bd4daf5d7227cab089ff6..c83af20d1d84eac884ed7dd2b83372f2500f40a8 100644 (file)
@@ -67,7 +67,7 @@ impl Process {
     ///     os pipe instead. This process takes ownership of these file
     ///     descriptors, closing them upon destruction of the process.
     pub fn spawn(config: p::ProcessConfig)
-        -> Result<(Process, ~[Option<file::FileDesc>]), io::IoError>
+        -> Result<(Process, Vec<Option<file::FileDesc>>), io::IoError>
     {
         // right now we only handle stdin/stdout/stderr.
         if config.extra_io.len() > 0 {
@@ -117,7 +117,7 @@ fn get_io(io: p::StdioContainer, ret: &mut Vec<Option<file::FileDesc>>)
                         exit_code: None,
                         exit_signal: None,
                     },
-                    ret_io.move_iter().collect()))
+                    ret_io))
             }
             Err(e) => Err(e)
         }
index 5e1bd29e5a6e7d2cdcc3ec616493d16f944ceeb3..ef6f1aafe8864f9a74da4291f04f80265505298d 100644 (file)
@@ -74,7 +74,7 @@ pub fn to_doublebigdigit(hi: BigDigit, lo: BigDigit) -> DoubleBigDigit {
 /**
 A big unsigned integer type.
 
-A `BigUint`-typed value `BigUint { data: ~[a, b, c] }` represents a number
+A `BigUint`-typed value `BigUint { data: vec!(a, b, c) }` represents a number
 `(a + b * BigDigit::base + c * BigDigit::base^2)`.
 */
 #[deriving(Clone)]
index 8c0aa494d6f80b30b9ee7cb8c2a5b280d6b3c60b..c49adce904a5199b8c8aa6fffaa3bc35f5d4d904 100644 (file)
@@ -45,9 +45,9 @@ pub fn get_rpath_flags(sess: &Session, out_filename: &Path) -> Vec<~str> {
     let libs = sess.cstore.get_used_crates(cstore::RequireDynamic);
     let libs = libs.move_iter().filter_map(|(_, l)| {
         l.map(|p| p.clone())
-    }).collect::<~[_]>();
+    }).collect::<Vec<_>>();
 
-    let rpaths = get_rpaths(os, sysroot, output, libs,
+    let rpaths = get_rpaths(os, sysroot, output, libs.as_slice(),
                             sess.opts.target_triple);
     flags.push_all(rpaths_to_flags(rpaths.as_slice()).as_slice());
     flags
index 732443f1d4211b9da3db14bee5869cbd2c487df9..eaf6527ea829b9264852a17a56d20c98024e2dfd 100644 (file)
@@ -282,7 +282,7 @@ mod __test {
   #![!resolve_unexported]
   extern crate test (name = "test", vers = "...");
   fn main() {
-    test::test_main_static(::os::args(), tests)
+    test::test_main_static(::os::args().as_slice(), tests)
   }
 
   static tests : &'static [test::TestDescAndFn] = &[
@@ -326,8 +326,8 @@ fn mk_test_module(cx: &TestCtxt) -> @ast::Item {
     let mainfn = (quote_item!(&cx.ext_cx,
         pub fn main() {
             #![main]
-            #![allow(deprecated_owned_vector)]
-            test::test_main_static(::std::os::args(), TESTS);
+            use std::slice::Vector;
+            test::test_main_static(::std::os::args().as_slice(), TESTS);
         }
     )).unwrap();
 
index ab755b39f1a399ffcb5aaa03314df92c667ea9ab..0962acd0a2ebf23acf34db153c955d69e708e15e 100644 (file)
@@ -434,7 +434,7 @@ pub fn monitor(f: proc():Send) {
 }
 
 pub fn main() {
-    std::os::set_exit_status(main_args(std::os::args()));
+    std::os::set_exit_status(main_args(std::os::args().as_slice()));
 }
 
 pub fn main_args(args: &[~str]) -> int {
index 3c8ce77fa873ee4ddbe5196431ebd44f42c81191..a399fabd95fb6430e73200ac3fd0d888cba68c6e 100644 (file)
@@ -1367,28 +1367,38 @@ fn check_unsafe_block(cx: &Context, e: &ast::Expr) {
     }
 }
 
-fn check_unused_mut_pat(cx: &Context, p: &ast::Pat) {
-    match p.node {
-        ast::PatIdent(ast::BindByValue(ast::MutMutable),
-                      ref path, _) if pat_util::pat_is_binding(&cx.tcx.def_map, p) => {
-            // `let mut _a = 1;` doesn't need a warning.
-            let initial_underscore = if path.segments.len() == 1 {
-                token::get_ident(path.segments
-                                     .get(0)
-                                     .identifier).get().starts_with("_")
-            } else {
-                cx.tcx.sess.span_bug(p.span,
-                                     "mutable binding that doesn't consist \
-                                      of exactly one segment")
-            };
-
-            if !initial_underscore &&
-               !cx.tcx.used_mut_nodes.borrow().contains(&p.id) {
-                cx.span_lint(UnusedMut, p.span,
-                             "variable does not need to be mutable");
+fn check_unused_mut_pat(cx: &Context, pats: &[@ast::Pat]) {
+    // collect all mutable pattern and group their NodeIDs by their Identifier to
+    // avoid false warnings in match arms with multiple patterns
+    let mut mutables = HashMap::new();
+    for &p in pats.iter() {
+        pat_util::pat_bindings(&cx.tcx.def_map, p, |mode, id, _, path| {
+            match mode {
+                ast::BindByValue(ast::MutMutable) => {
+                    if path.segments.len() != 1 {
+                        cx.tcx.sess.span_bug(p.span,
+                                             "mutable binding that doesn't consist \
+                                              of exactly one segment");
+                    }
+                    let ident = path.segments.get(0).identifier;
+                    if !token::get_ident(ident).get().starts_with("_") {
+                        mutables.insert_or_update_with(ident.name as uint, vec!(id), |_, old| {
+                            old.push(id);
+                        });
+                    }
+                }
+                _ => {
+                }
             }
+        });
+    }
+
+    let used_mutables = cx.tcx.used_mut_nodes.borrow();
+    for (_, v) in mutables.iter() {
+        if !v.iter().any(|e| used_mutables.contains(e)) {
+            cx.span_lint(UnusedMut, cx.tcx.map.span(*v.get(0)),
+                         "variable does not need to be mutable");
         }
-        _ => ()
     }
 }
 
@@ -1684,7 +1694,6 @@ fn visit_view_item(&mut self, i: &ast::ViewItem, _: ()) {
     fn visit_pat(&mut self, p: &ast::Pat, _: ()) {
         check_pat_non_uppercase_statics(self, p);
         check_pat_uppercase_variable(self, p);
-        check_unused_mut_pat(self, p);
 
         visit::walk_pat(self, p, ());
     }
@@ -1700,6 +1709,11 @@ fn visit_expr(&mut self, e: &ast::Expr, _: ()) {
             ast::ExprParen(expr) => if self.negated_expr_id == e.id {
                 self.negated_expr_id = expr.id
             },
+            ast::ExprMatch(_, ref arms) => {
+                for a in arms.iter() {
+                    check_unused_mut_pat(self, a.pats.as_slice());
+                }
+            },
             _ => ()
         };
 
@@ -1723,6 +1737,18 @@ fn visit_stmt(&mut self, s: &ast::Stmt, _: ()) {
         check_unused_result(self, s);
         check_unnecessary_parens_stmt(self, s);
 
+        match s.node {
+            ast::StmtDecl(d, _) => {
+                match d.node {
+                    ast::DeclLocal(l) => {
+                        check_unused_mut_pat(self, &[l.pat]);
+                    },
+                    _ => {}
+                }
+            },
+            _ => {}
+        }
+
         visit::walk_stmt(self, s, ());
     }
 
@@ -1732,6 +1758,10 @@ fn visit_fn(&mut self, fk: &visit::FnKind, decl: &ast::FnDecl,
             visit::walk_fn(this, fk, decl, body, span, id, ());
         };
 
+        for a in decl.inputs.iter(){
+            check_unused_mut_pat(self, &[a.pat]);
+        }
+
         match *fk {
             visit::FkMethod(_, _, m) => {
                 self.with_lint_attrs(m.attrs.as_slice(), |cx| {
index 064593f2b41790b4ffd9efcb6361d1c82d0b544a..1abdca7cb9f7b560489c5e27ce93770864613e55 100644 (file)
@@ -1620,18 +1620,20 @@ fn handle_external_def(&mut self,
 
         match def {
           DefMod(_) | DefForeignMod(_) => {}
-          DefVariant(_, variant_id, is_struct) => {
+          DefVariant(enum_did, variant_id, is_struct) => {
             debug!("(building reduced graph for external crate) building \
                     variant {}",
                    final_ident);
-            // We assume the parent is visible, or else we wouldn't have seen
-            // it. Also variants are public-by-default if the parent was also
-            // public.
+            // If this variant is public, then it was publicly reexported,
+            // otherwise we need to inherit the visibility of the enum
+            // definition.
+            let is_exported = is_public ||
+                              self.external_exports.contains(&enum_did);
             if is_struct {
-                child_name_bindings.define_type(def, DUMMY_SP, true);
+                child_name_bindings.define_type(def, DUMMY_SP, is_exported);
                 self.structs.insert(variant_id);
             } else {
-                child_name_bindings.define_value(def, DUMMY_SP, true);
+                child_name_bindings.define_value(def, DUMMY_SP, is_exported);
             }
           }
           DefFn(..) | DefStaticMethod(..) | DefStatic(..) => {
index 3bef0eae0acbce0c98ece7977e85d00546e74ed2..400aa83a615143a04092b8c38428290c468c947c 100644 (file)
@@ -226,7 +226,8 @@ fn get_extern_rust_fn(ccx: &CrateContext, inputs: &[ty::t], output: ty::t,
 
     let f = decl_rust_fn(ccx, false, inputs, output, name);
     csearch::get_item_attrs(&ccx.sess().cstore, did, |meta_items| {
-        set_llvm_fn_attrs(meta_items.iter().map(|&x| attr::mk_attr(x)).collect::<~[_]>(), f)
+        set_llvm_fn_attrs(meta_items.iter().map(|&x| attr::mk_attr(x))
+                                    .collect::<Vec<_>>().as_slice(), f)
     });
 
     ccx.externs.borrow_mut().insert(name.to_owned(), f);
@@ -2109,12 +2110,12 @@ pub fn write_metadata(cx: &CrateContext, krate: &ast::Crate) -> Vec<u8> {
 
     let encode_parms = crate_ctxt_to_encode_parms(cx, encode_inlined_item);
     let metadata = encoder::encode_metadata(encode_parms, krate);
-    let compressed = encoder::metadata_encoding_version +
-                        match flate::deflate_bytes(metadata.as_slice()) {
-                            Some(compressed) => compressed,
-                            None => cx.sess().fatal(format!("failed to compress metadata", ))
-                        }.as_slice();
-    let llmeta = C_bytes(cx, compressed);
+    let compressed = Vec::from_slice(encoder::metadata_encoding_version)
+                     .append(match flate::deflate_bytes(metadata.as_slice()) {
+                         Some(compressed) => compressed,
+                         None => cx.sess().fatal(format!("failed to compress metadata"))
+                     }.as_slice());
+    let llmeta = C_bytes(cx, compressed.as_slice());
     let llconst = C_struct(cx, [llmeta], false);
     let name = format!("rust_metadata_{}_{}_{}", cx.link_meta.crateid.name,
                        cx.link_meta.crateid.version_or_default(), cx.link_meta.crate_hash);
index eae9da84a1fe6727885965175662132655890edb..548746362cf238bb1ff0f8c5d12b77697956650a 100644 (file)
@@ -33,7 +33,7 @@
 use util::ppaux::{Repr, ty_to_str};
 
 use std::c_str::ToCStr;
-use std::slice;
+use std::vec;
 use std::vec::Vec;
 use libc::c_uint;
 use syntax::{ast, ast_util};
@@ -94,12 +94,12 @@ fn const_vec(cx: &CrateContext, e: &ast::Expr,
     let vec_ty = ty::expr_ty(cx.tcx(), e);
     let unit_ty = ty::sequence_element_type(cx.tcx(), vec_ty);
     let llunitty = type_of::type_of(cx, unit_ty);
-    let (vs, inlineable) = slice::unzip(es.iter().map(|e| const_expr(cx, *e, is_local)));
+    let (vs, inlineable) = vec::unzip(es.iter().map(|e| const_expr(cx, *e, is_local)));
     // If the vector contains enums, an LLVM array won't work.
     let v = if vs.iter().any(|vi| val_ty(*vi) != llunitty) {
-        C_struct(cx, vs, false)
+        C_struct(cx, vs.as_slice(), false)
     } else {
-        C_array(llunitty, vs)
+        C_array(llunitty, vs.as_slice())
     };
     (v, llunitty, inlineable.iter().fold(true, |a, &b| a && b))
 }
@@ -539,7 +539,7 @@ fn const_expr_unadjusted(cx: &CrateContext, e: &ast::Expr,
               };
 
               expr::with_field_tys(tcx, ety, Some(e.id), |discr, field_tys| {
-                  let (cs, inlineable) = slice::unzip(field_tys.iter().enumerate()
+                  let (cs, inlineable) = vec::unzip(field_tys.iter().enumerate()
                       .map(|(ix, &field_ty)| {
                       match fs.iter().find(|f| field_ty.ident.name == f.ident.node.name) {
                           Some(f) => const_expr(cx, (*f).expr, is_local),
@@ -554,7 +554,7 @@ fn const_expr_unadjusted(cx: &CrateContext, e: &ast::Expr,
                           }
                       }
                   }));
-                  (adt::trans_const(cx, &*repr, discr, cs),
+                  (adt::trans_const(cx, &*repr, discr, cs.as_slice()),
                    inlineable.iter().fold(true, |a, &b| a && b))
               })
           }
index b8f50fcb1e58c245e61592e918567f8818e08fbd..4fd4f2f9d6ef0e635a147e737f71e85984127df1 100644 (file)
@@ -157,12 +157,13 @@ pub fn monomorphic_fn(ccx: &CrateContext,
             // This is a bit unfortunate.
 
             let idx = real_substs.tps.len() - num_method_ty_params;
-            let substs = real_substs.tps.slice(0, idx) +
-            &[real_substs.self_ty.unwrap()] + real_substs.tps.tailn(idx);
+            let substs = Vec::from_slice(real_substs.tps.slice(0, idx))
+                         .append([real_substs.self_ty.unwrap()])
+                         .append(real_substs.tps.tailn(idx));
             debug!("static default: changed substitution to {}",
                    substs.repr(ccx.tcx()));
 
-            ty::subst_tps(ccx.tcx(), substs, None, llitem_ty)
+            ty::subst_tps(ccx.tcx(), substs.as_slice(), None, llitem_ty)
         }
     };
 
index b544c939e936eef821f0bd0aa1d825bd0a76d642..06996df169254e2dd5d478b767b8963dcc439870 100644 (file)
@@ -380,7 +380,7 @@ fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
                            "".to_owned()
                        } else {
                            let mut m = decl.bounds.iter().map(|s| s.to_str());
-                           ": " + m.collect::<~[~str]>().connect(" + ")
+                           ": " + m.collect::<Vec<~str>>().connect(" + ")
                        },
                        arrow = match decl.decl.output { clean::Unit => "no", _ => "yes" },
                        ret = decl.decl.output)
index fe80d26d10933c284c2f9ced198a89d630e6f352..0bdf0818c8e82ab780d47bc522e69f9747c86936 100644 (file)
@@ -549,7 +549,8 @@ fn emit_source(&mut self, filename: &str) -> io::IoResult<()> {
             root_path.push_str("../");
         });
 
-        cur.push(p.filename().expect("source has no filename") + bytes!(".html"));
+        cur.push(Vec::from_slice(p.filename().expect("source has no filename"))
+                 .append(bytes!(".html")));
         let mut w = BufferedWriter::new(try!(File::create(&cur)));
 
         let title = format!("{} -- source", cur.filename_display());
index a79c8b30bbad2d86815d34d8f9cf4af527c2cbdb..72b474147335c7002c5fc1f67ca46ea2f01537be 100644 (file)
@@ -85,7 +85,7 @@ pub mod html {
 type Output = (clean::Crate, Vec<plugins::PluginJson> );
 
 pub fn main() {
-    std::os::set_exit_status(main_args(std::os::args()));
+    std::os::set_exit_status(main_args(std::os::args().as_slice()));
 }
 
 pub fn opts() -> Vec<getopts::OptGroup> {
index 94a084fe055aefee17ba157532e4188b4de35219..4766630b0f421ecd05024a2377a398fa786c9c6a 100644 (file)
@@ -33,7 +33,7 @@ struct Ctx {
 
 impl GetAddrInfoRequest {
     pub fn run(loop_: &Loop, node: Option<&str>, service: Option<&str>,
-               hints: Option<ai::Hint>) -> Result<~[ai::Info], UvError> {
+               hints: Option<ai::Hint>) -> Result<Vec<ai::Info>, UvError> {
         assert!(node.is_some() || service.is_some());
         let (_c_node, c_node_ptr) = match node {
             Some(n) => {
@@ -134,7 +134,7 @@ fn each_ai_flag(_f: |c_int, ai::Flag|) {
 }
 
 // Traverse the addrinfo linked list, producing a vector of Rust socket addresses
-pub fn accum_addrinfo(addr: &Addrinfo) -> ~[ai::Info] {
+pub fn accum_addrinfo(addr: &Addrinfo) -> Vec<ai::Info> {
     unsafe {
         let mut addr = addr.handle;
 
@@ -180,6 +180,6 @@ pub fn accum_addrinfo(addr: &Addrinfo) -> ~[ai::Info] {
             }
         }
 
-        return addrs.move_iter().collect();
+        addrs
     }
 }
index d744607050fc6583d750c8ea40517258f53bd10e..d671e20868c5c39d64b80193fbad4f416c1f1d57 100644 (file)
@@ -40,7 +40,8 @@ impl Process {
     /// Returns either the corresponding process object or an error which
     /// occurred.
     pub fn spawn(io_loop: &mut UvIoFactory, config: process::ProcessConfig)
-                -> Result<(Box<Process>, ~[Option<PipeWatcher>]), UvError> {
+                -> Result<(Box<Process>, Vec<Option<PipeWatcher>>), UvError>
+    {
         let cwd = config.cwd.map(|s| s.to_c_str());
         let mut io = vec![config.stdin, config.stdout, config.stderr];
         for slot in config.extra_io.iter() {
@@ -102,7 +103,7 @@ pub fn spawn(io_loop: &mut UvIoFactory, config: process::ProcessConfig)
         });
 
         match ret {
-            Ok(p) => Ok((p, ret_io.move_iter().collect())),
+            Ok(p) => Ok((p, ret_io)),
             Err(e) => Err(e),
         }
     }
index 17a64fdb51760740e729a079d2642251fdb37819..50258c2583c65c33d169e4e31c36e4df8ff62071 100644 (file)
@@ -178,7 +178,7 @@ fn timer_init(&mut self) -> Result<Box<rtio::RtioTimer:Send>, IoError> {
     }
 
     fn get_host_addresses(&mut self, host: Option<&str>, servname: Option<&str>,
-                          hint: Option<ai::Hint>) -> Result<~[ai::Info], IoError> {
+                          hint: Option<ai::Hint>) -> Result<Vec<ai::Info>, IoError> {
         let r = GetAddrInfoRequest::run(&self.loop_, host, servname, hint);
         r.map_err(uv_error_to_io_error)
     }
@@ -272,7 +272,7 @@ fn fs_utime(&mut self, path: &CString, atime: u64, mtime: u64)
 
     fn spawn(&mut self, config: ProcessConfig)
             -> Result<(Box<rtio::RtioProcess:Send>,
-                       ~[Option<Box<rtio::RtioPipe:Send>>]),
+                       Vec<Option<Box<rtio::RtioPipe:Send>>>),
                       IoError>
     {
         match Process::spawn(self, config) {
index 426894aeff7dd8eb914d28128edb291f2b5193d3..4709365ebff533fe7d0647fbfee3f2720c40cb85 100644 (file)
@@ -146,7 +146,7 @@ fn to_base64(&self, config: Config) -> ~str {
         }
 
         unsafe {
-            str::raw::from_utf8_owned(v.move_iter().collect())
+            str::raw::from_utf8(v.as_slice()).to_owned()
         }
     }
 }
@@ -155,7 +155,7 @@ fn to_base64(&self, config: Config) -> ~str {
 pub trait FromBase64 {
     /// Converts the value of `self`, interpreted as base64 encoded data, into
     /// an owned vector of bytes, returning the vector.
-    fn from_base64(&self) -> Result<~[u8], FromBase64Error>;
+    fn from_base64(&self) -> Result<Vec<u8>, FromBase64Error>;
 }
 
 /// Errors that can occur when decoding a base64 encoded string
@@ -192,14 +192,13 @@ impl<'a> FromBase64 for &'a str {
      * ```rust
      * extern crate serialize;
      * use serialize::base64::{ToBase64, FromBase64, STANDARD};
-     * use std::str;
      *
      * fn main () {
      *     let hello_str = bytes!("Hello, World").to_base64(STANDARD);
      *     println!("base64 output: {}", hello_str);
      *     let res = hello_str.from_base64();
      *     if res.is_ok() {
-     *       let opt_bytes = str::from_utf8_owned(res.unwrap());
+     *       let opt_bytes = StrBuf::from_utf8(res.unwrap());
      *       if opt_bytes.is_some() {
      *         println!("decoded from base64: {}", opt_bytes.unwrap());
      *       }
@@ -207,7 +206,7 @@ impl<'a> FromBase64 for &'a str {
      * }
      * ```
      */
-    fn from_base64(&self) -> Result<~[u8], FromBase64Error> {
+    fn from_base64(&self) -> Result<Vec<u8>, FromBase64Error> {
         let mut r = Vec::new();
         let mut buf: u32 = 0;
         let mut modulus = 0;
@@ -256,7 +255,7 @@ fn from_base64(&self) -> Result<~[u8], FromBase64Error> {
             _ => return Err(InvalidBase64Length),
         }
 
-        Ok(r.move_iter().collect())
+        Ok(r)
     }
 }
 
@@ -301,21 +300,21 @@ fn test_to_base64_url_safe() {
 
     #[test]
     fn test_from_base64_basic() {
-        assert_eq!("".from_base64().unwrap(), "".as_bytes().to_owned());
-        assert_eq!("Zg==".from_base64().unwrap(), "f".as_bytes().to_owned());
-        assert_eq!("Zm8=".from_base64().unwrap(), "fo".as_bytes().to_owned());
-        assert_eq!("Zm9v".from_base64().unwrap(), "foo".as_bytes().to_owned());
-        assert_eq!("Zm9vYg==".from_base64().unwrap(), "foob".as_bytes().to_owned());
-        assert_eq!("Zm9vYmE=".from_base64().unwrap(), "fooba".as_bytes().to_owned());
-        assert_eq!("Zm9vYmFy".from_base64().unwrap(), "foobar".as_bytes().to_owned());
+        assert_eq!("".from_base64().unwrap().as_slice(), "".as_bytes());
+        assert_eq!("Zg==".from_base64().unwrap().as_slice(), "f".as_bytes());
+        assert_eq!("Zm8=".from_base64().unwrap().as_slice(), "fo".as_bytes());
+        assert_eq!("Zm9v".from_base64().unwrap().as_slice(), "foo".as_bytes());
+        assert_eq!("Zm9vYg==".from_base64().unwrap().as_slice(), "foob".as_bytes());
+        assert_eq!("Zm9vYmE=".from_base64().unwrap().as_slice(), "fooba".as_bytes());
+        assert_eq!("Zm9vYmFy".from_base64().unwrap().as_slice(), "foobar".as_bytes());
     }
 
     #[test]
     fn test_from_base64_newlines() {
-        assert_eq!("Zm9v\r\nYmFy".from_base64().unwrap(),
-                   "foobar".as_bytes().to_owned());
-        assert_eq!("Zm9vYg==\r\n".from_base64().unwrap(),
-                   "foob".as_bytes().to_owned());
+        assert_eq!("Zm9v\r\nYmFy".from_base64().unwrap().as_slice(),
+                   "foobar".as_bytes());
+        assert_eq!("Zm9vYg==\r\n".from_base64().unwrap().as_slice(),
+                   "foob".as_bytes());
     }
 
     #[test]
@@ -341,8 +340,8 @@ fn test_base64_random() {
         for _ in range(0, 1000) {
             let times = task_rng().gen_range(1u, 100);
             let v = Vec::from_fn(times, |_| random::<u8>());
-            assert_eq!(v.as_slice().to_base64(STANDARD).from_base64().unwrap(),
-                       v.as_slice().to_owned());
+            assert_eq!(v.as_slice().to_base64(STANDARD).from_base64().unwrap().as_slice(),
+                       v.as_slice());
         }
     }
 
index cbed0656e4de285a8e141f11bdf43731060314e8..c463d97dba4d48fe960b36f79c1621615de10852 100644 (file)
@@ -45,7 +45,7 @@ fn to_hex(&self) -> ~str {
         }
 
         unsafe {
-            str::raw::from_utf8_owned(v.move_iter().collect())
+            str::raw::from_utf8(v.as_slice()).to_owned()
         }
     }
 }
@@ -54,7 +54,7 @@ fn to_hex(&self) -> ~str {
 pub trait FromHex {
     /// Converts the value of `self`, interpreted as hexadecimal encoded data,
     /// into an owned vector of bytes, returning the vector.
-    fn from_hex(&self) -> Result<~[u8], FromHexError>;
+    fn from_hex(&self) -> Result<Vec<u8>, FromHexError>;
 }
 
 /// Errors that can occur when decoding a hex encoded string
@@ -91,19 +91,18 @@ impl<'a> FromHex for &'a str {
      * ```rust
      * extern crate serialize;
      * use serialize::hex::{FromHex, ToHex};
-     * use std::str;
      *
      * fn main () {
      *     let hello_str = "Hello, World".as_bytes().to_hex();
      *     println!("{}", hello_str);
      *     let bytes = hello_str.from_hex().unwrap();
      *     println!("{:?}", bytes);
-     *     let result_str = str::from_utf8_owned(bytes).unwrap();
+     *     let result_str = StrBuf::from_utf8(bytes).unwrap();
      *     println!("{}", result_str);
      * }
      * ```
      */
-    fn from_hex(&self) -> Result<~[u8], FromHexError> {
+    fn from_hex(&self) -> Result<Vec<u8>, FromHexError> {
         // This may be an overestimate if there is any whitespace
         let mut b = Vec::with_capacity(self.len() / 2);
         let mut modulus = 0;
@@ -150,10 +149,10 @@ pub fn test_to_hex() {
 
     #[test]
     pub fn test_from_hex_okay() {
-        assert_eq!("666f6f626172".from_hex().unwrap(),
-                   "foobar".as_bytes().to_owned());
-        assert_eq!("666F6F626172".from_hex().unwrap(),
-                   "foobar".as_bytes().to_owned());
+        assert_eq!("666f6f626172".from_hex().unwrap().as_slice(),
+                   "foobar".as_bytes());
+        assert_eq!("666F6F626172".from_hex().unwrap().as_slice(),
+                   "foobar".as_bytes());
     }
 
     #[test]
@@ -169,8 +168,8 @@ pub fn test_from_hex_invalid_char() {
 
     #[test]
     pub fn test_from_hex_ignores_whitespace() {
-        assert_eq!("666f 6f6\r\n26172 ".from_hex().unwrap(),
-                   "foobar".as_bytes().to_owned());
+        assert_eq!("666f 6f6\r\n26172 ".from_hex().unwrap().as_slice(),
+                   "foobar".as_bytes());
     }
 
     #[test]
@@ -183,8 +182,8 @@ pub fn test_to_hex_all_bytes() {
     #[test]
     pub fn test_from_hex_all_bytes() {
         for i in range(0, 256) {
-            assert_eq!(format!("{:02x}", i as uint).from_hex().unwrap(), ~[i as u8]);
-            assert_eq!(format!("{:02X}", i as uint).from_hex().unwrap(), ~[i as u8]);
+            assert_eq!(format!("{:02x}", i as uint).from_hex().unwrap().as_slice(), &[i as u8]);
+            assert_eq!(format!("{:02X}", i as uint).from_hex().unwrap().as_slice(), &[i as u8]);
         }
     }
 
index 29315c458108fa20ff8d3c2b71788843d14f986e..2e4d7696c44d0b42a53fea7e5793af7b6adf690b 100644 (file)
@@ -166,14 +166,14 @@ fn main() {
  pub struct TestStruct1  {
     data_int: u8,
     data_str: ~str,
-    data_vector: ~[u8],
+    data_vector: Vec<u8>,
  }
 
 // To serialize use the `json::str_encode` to encode an object in a string.
 // It calls the generated `Encodable` impl.
 fn main() {
     let to_encode_object = TestStruct1
-         {data_int: 1, data_str:"toto".to_owned(), data_vector:~[2,3,4,5]};
+         {data_int: 1, data_str:"toto".to_owned(), data_vector:vec![2,3,4,5]};
     let encoded_str: ~str = json::Encoder::str_encode(&to_encode_object);
 
     // To deserialize use the `json::from_str` and `json::Decoder`
@@ -201,7 +201,7 @@ fn main() {
 pub struct TestStruct1  {
     data_int: u8,
     data_str: ~str,
-    data_vector: ~[u8],
+    data_vector: Vec<u8>,
 }
 
 impl ToJson for TestStruct1 {
@@ -218,7 +218,7 @@ fn main() {
     // Serialization using our impl of to_json
 
     let test2: TestStruct1 = TestStruct1 {data_int: 1, data_str:"toto".to_owned(),
-                                          data_vector:~[2,3,4,5]};
+                                          data_vector:vec![2,3,4,5]};
     let tjson: json::Json = test2.to_json();
     let json_str: ~str = tjson.to_str();
 
@@ -258,7 +258,7 @@ pub enum Json {
     Null,
 }
 
-pub type List = ~[Json];
+pub type List = Vec<Json>;
 pub type Object = TreeMap<~str, Json>;
 
 /// The errors that can arise while parsing a JSON stream.
@@ -2211,7 +2211,7 @@ impl<A:ToJson,B:ToJson> ToJson for (A, B) {
     fn to_json(&self) -> Json {
         match *self {
           (ref a, ref b) => {
-            List(box [a.to_json(), b.to_json()])
+            List(vec![a.to_json(), b.to_json()])
           }
         }
     }
@@ -2221,7 +2221,7 @@ impl<A:ToJson,B:ToJson,C:ToJson> ToJson for (A, B, C) {
     fn to_json(&self) -> Json {
         match *self {
           (ref a, ref b, ref c) => {
-            List(box [a.to_json(), b.to_json(), c.to_json()])
+            List(vec![a.to_json(), b.to_json(), c.to_json()])
           }
         }
     }
@@ -2298,12 +2298,12 @@ enum Animal {
     struct Inner {
         a: (),
         b: uint,
-        c: ~[~str],
+        c: Vec<~str>,
     }
 
     #[deriving(Eq, Encodable, Decodable, Show)]
     struct Outer {
-        inner: ~[Inner],
+        inner: Vec<Inner>,
     }
 
     fn mk_object(items: &[(~str, Json)]) -> Json {
@@ -2360,22 +2360,22 @@ fn test_write_bool() {
 
     #[test]
     fn test_write_list() {
-        assert_eq!(List(~[]).to_str(), "[]".to_owned());
-        assert_eq!(List(~[]).to_pretty_str(), "[]".to_owned());
+        assert_eq!(List(vec![]).to_str(), "[]".to_owned());
+        assert_eq!(List(vec![]).to_pretty_str(), "[]".to_owned());
 
-        assert_eq!(List(~[Boolean(true)]).to_str(), "[true]".to_owned());
+        assert_eq!(List(vec![Boolean(true)]).to_str(), "[true]".to_owned());
         assert_eq!(
-            List(~[Boolean(true)]).to_pretty_str(),
+            List(vec![Boolean(true)]).to_pretty_str(),
             "\
             [\n  \
                 true\n\
             ]".to_owned()
         );
 
-        let long_test_list = List(box [
+        let long_test_list = List(vec![
             Boolean(false),
             Null,
-            List(box [String("foo\nbar".to_owned()), Number(3.5)])]);
+            List(vec![String("foo\nbar".to_owned()), Number(3.5)])]);
 
         assert_eq!(long_test_list.to_str(),
             "[false,null,[\"foo\\nbar\",3.5]]".to_owned());
@@ -2411,7 +2411,7 @@ fn test_write_object() {
         );
 
         let complex_obj = mk_object([
-                ("b".to_owned(), List(box [
+                ("b".to_owned(), List(vec![
                     mk_object([("c".to_owned(), String("\x0c\r".to_owned()))]),
                     mk_object([("d".to_owned(), String("".to_owned()))])
                 ]))
@@ -2443,7 +2443,7 @@ fn test_write_object() {
 
         let a = mk_object([
             ("a".to_owned(), Boolean(true)),
-            ("b".to_owned(), List(box [
+            ("b".to_owned(), List(vec![
                 mk_object([("c".to_owned(), String("\x0c\r".to_owned()))]),
                 mk_object([("d".to_owned(), String("".to_owned()))])
             ]))
@@ -2678,44 +2678,44 @@ fn test_read_list() {
         assert_eq!(from_str("[1,]"),  Err(SyntaxError(InvalidSyntax,        1, 4)));
         assert_eq!(from_str("[6 7]"), Err(SyntaxError(InvalidSyntax,        1, 4)));
 
-        assert_eq!(from_str("[]"), Ok(List(~[])));
-        assert_eq!(from_str("[ ]"), Ok(List(~[])));
-        assert_eq!(from_str("[true]"), Ok(List(~[Boolean(true)])));
-        assert_eq!(from_str("[ false ]"), Ok(List(~[Boolean(false)])));
-        assert_eq!(from_str("[null]"), Ok(List(~[Null])));
+        assert_eq!(from_str("[]"), Ok(List(vec![])));
+        assert_eq!(from_str("[ ]"), Ok(List(vec![])));
+        assert_eq!(from_str("[true]"), Ok(List(vec![Boolean(true)])));
+        assert_eq!(from_str("[ false ]"), Ok(List(vec![Boolean(false)])));
+        assert_eq!(from_str("[null]"), Ok(List(vec![Null])));
         assert_eq!(from_str("[3, 1]"),
-                     Ok(List(~[Number(3.0), Number(1.0)])));
+                     Ok(List(vec![Number(3.0), Number(1.0)])));
         assert_eq!(from_str("\n[3, 2]\n"),
-                     Ok(List(~[Number(3.0), Number(2.0)])));
+                     Ok(List(vec![Number(3.0), Number(2.0)])));
         assert_eq!(from_str("[2, [4, 1]]"),
-               Ok(List(~[Number(2.0), List(~[Number(4.0), Number(1.0)])])));
+               Ok(List(vec![Number(2.0), List(vec![Number(4.0), Number(1.0)])])));
     }
 
     #[test]
     fn test_decode_list() {
         let mut decoder = Decoder::new(from_str("[]").unwrap());
-        let v: ~[()] = Decodable::decode(&mut decoder).unwrap();
-        assert_eq!(v, ~[]);
+        let v: Vec<()> = Decodable::decode(&mut decoder).unwrap();
+        assert_eq!(v, vec![]);
 
         let mut decoder = Decoder::new(from_str("[null]").unwrap());
-        let v: ~[()] = Decodable::decode(&mut decoder).unwrap();
-        assert_eq!(v, ~[()]);
+        let v: Vec<()> = Decodable::decode(&mut decoder).unwrap();
+        assert_eq!(v, vec![()]);
 
         let mut decoder = Decoder::new(from_str("[true]").unwrap());
-        let v: ~[bool] = Decodable::decode(&mut decoder).unwrap();
-        assert_eq!(v, ~[true]);
+        let v: Vec<bool> = Decodable::decode(&mut decoder).unwrap();
+        assert_eq!(v, vec![true]);
 
         let mut decoder = Decoder::new(from_str("[true]").unwrap());
-        let v: ~[bool] = Decodable::decode(&mut decoder).unwrap();
-        assert_eq!(v, ~[true]);
+        let v: Vec<bool> = Decodable::decode(&mut decoder).unwrap();
+        assert_eq!(v, vec![true]);
 
         let mut decoder = Decoder::new(from_str("[3, 1]").unwrap());
-        let v: ~[int] = Decodable::decode(&mut decoder).unwrap();
-        assert_eq!(v, ~[3, 1]);
+        let v: Vec<int> = Decodable::decode(&mut decoder).unwrap();
+        assert_eq!(v, vec![3, 1]);
 
         let mut decoder = Decoder::new(from_str("[[3], [1, 2]]").unwrap());
-        let v: ~[~[uint]] = Decodable::decode(&mut decoder).unwrap();
-        assert_eq!(v, ~[~[3], ~[1, 2]]);
+        let v: Vec<Vec<uint>> = Decodable::decode(&mut decoder).unwrap();
+        assert_eq!(v, vec![vec![3], vec![1, 2]]);
     }
 
     #[test]
@@ -2750,7 +2750,7 @@ fn test_read_object() {
                       "{\"a\" : 1.0 ,\"b\": [ true ]}").unwrap(),
                   mk_object([
                       ("a".to_owned(), Number(1.0)),
-                      ("b".to_owned(), List(~[Boolean(true)]))
+                      ("b".to_owned(), List(vec![Boolean(true)]))
                   ]));
         assert_eq!(from_str(
                       "{".to_owned() +
@@ -2763,7 +2763,7 @@ fn test_read_object() {
                       "}").unwrap(),
                   mk_object([
                       ("a".to_owned(), Number(1.0)),
-                      ("b".to_owned(), List(~[
+                      ("b".to_owned(), List(vec![
                           Boolean(true),
                           String("foo\nbar".to_owned()),
                           mk_object([
@@ -2785,8 +2785,8 @@ fn test_decode_struct() {
         assert_eq!(
             v,
             Outer {
-                inner: ~[
-                    Inner { a: (), b: 2, c: ~["abc".to_owned(), "xyz".to_owned()] }
+                inner: vec![
+                    Inner { a: (), b: 2, c: vec!["abc".to_owned(), "xyz".to_owned()] }
                 ]
             }
         );
@@ -2837,7 +2837,7 @@ struct DecodeStruct {
         x: f64,
         y: bool,
         z: ~str,
-        w: ~[DecodeStruct]
+        w: Vec<DecodeStruct>
     }
     #[deriving(Decodable)]
     enum DecodeEnum {
index 9d68705fca73f643ffe8c1fadcc94c053e67b1c6..7914dd8c7d2aaf1269fc8288ae86e2f0aa724ba8 100644 (file)
@@ -453,12 +453,14 @@ fn encode(&self, s: &mut S) -> Result<(), E> {
 
 impl<E, D:Decoder<E>,T:Decodable<D, E>> Decodable<D, E> for ~[T] {
     fn decode(d: &mut D) -> Result<~[T], E> {
+        use std::vec::FromVec;
+
         d.read_seq(|d, len| {
             let mut v: Vec<T> = Vec::with_capacity(len);
             for i in range(0, len) {
                 v.push(try!(d.read_seq_elt(i, |d| Decodable::decode(d))));
             }
-            let k = v.move_iter().collect::<~[T]>();
+            let k: ~[T] = FromVec::from_vec(v);
             Ok(k)
         })
     }
@@ -557,7 +559,7 @@ fn encode(&self, e: &mut S) -> Result<(), E> {
 
 impl<E, D: Decoder<E>> Decodable<D, E> for path::posix::Path {
     fn decode(d: &mut D) -> Result<path::posix::Path, E> {
-        let bytes: ~[u8] = try!(Decodable::decode(d));
+        let bytes: Vec<u8> = try!(Decodable::decode(d));
         Ok(path::posix::Path::new(bytes))
     }
 }
@@ -570,7 +572,7 @@ fn encode(&self, e: &mut S) -> Result<(), E> {
 
 impl<E, D: Decoder<E>> Decodable<D, E> for path::windows::Path {
     fn decode(d: &mut D) -> Result<path::windows::Path, E> {
-        let bytes: ~[u8] = try!(Decodable::decode(d));
+        let bytes: Vec<u8> = try!(Decodable::decode(d));
         Ok(path::windows::Path::new(bytes))
     }
 }
@@ -600,17 +602,17 @@ fn emit_from_vec<T>(&mut self, v: &[T], f: |&mut S, &T| -> Result<(), E>) -> Res
 }
 
 pub trait DecoderHelpers<E> {
-    fn read_to_vec<T>(&mut self, f: |&mut Self| -> Result<T, E>) -> Result<~[T], E>;
+    fn read_to_vec<T>(&mut self, f: |&mut Self| -> Result<T, E>) -> Result<Vec<T>, E>;
 }
 
 impl<E, D:Decoder<E>> DecoderHelpers<E> for D {
-    fn read_to_vec<T>(&mut self, f: |&mut D| -> Result<T, E>) -> Result<~[T], E> {
+    fn read_to_vec<T>(&mut self, f: |&mut D| -> Result<T, E>) -> Result<Vec<T>, E> {
         self.read_seq(|this, len| {
             let mut v = Vec::with_capacity(len);
             for i in range(0, len) {
                 v.push(try!(this.read_seq_elt(i, |this| f(this))));
             }
-            Ok(v.move_iter().collect())
+            Ok(v)
         })
     }
 }
index 5b4400593b483af65a7b4864f0a700d5dcecef90..f45ec8a6742a23585695e0f4c21b4d7fba6b0b63 100644 (file)
@@ -13,7 +13,7 @@
 use to_str::{IntoStr};
 use str;
 use str::Str;
-use str::StrSlice;
+use str::{StrAllocating, StrSlice};
 use str::OwnedStr;
 use container::Container;
 use cast;
@@ -217,14 +217,14 @@ pub trait OwnedAsciiCast {
 
     /// Take ownership and cast to an ascii vector. Fail on non-ASCII input.
     #[inline]
-    fn into_ascii(self) -> ~[Ascii] {
+    fn into_ascii(self) -> Vec<Ascii> {
         assert!(self.is_ascii());
         unsafe {self.into_ascii_nocheck()}
     }
 
     /// Take ownership and cast to an ascii vector. Return None on non-ASCII input.
     #[inline]
-    fn into_ascii_opt(self) -> Option<~[Ascii]> {
+    fn into_ascii_opt(self) -> Option<Vec<Ascii>> {
         if self.is_ascii() {
             Some(unsafe { self.into_ascii_nocheck() })
         } else {
@@ -234,7 +234,7 @@ fn into_ascii_opt(self) -> Option<~[Ascii]> {
 
     /// Take ownership and cast to an ascii vector.
     /// Does not perform validation checks.
-    unsafe fn into_ascii_nocheck(self) -> ~[Ascii];
+    unsafe fn into_ascii_nocheck(self) -> Vec<Ascii>;
 }
 
 impl OwnedAsciiCast for ~[u8] {
@@ -244,8 +244,8 @@ fn is_ascii(&self) -> bool {
     }
 
     #[inline]
-    unsafe fn into_ascii_nocheck(self) -> ~[Ascii] {
-        cast::transmute(self)
+    unsafe fn into_ascii_nocheck(self) -> Vec<Ascii> {
+        cast::transmute(Vec::from_slice(self.as_slice()))
     }
 }
 
@@ -256,7 +256,20 @@ fn is_ascii(&self) -> bool {
     }
 
     #[inline]
-    unsafe fn into_ascii_nocheck(self) -> ~[Ascii] {
+    unsafe fn into_ascii_nocheck(self) -> Vec<Ascii> {
+        let v: ~[u8] = cast::transmute(self);
+        v.into_ascii_nocheck()
+    }
+}
+
+impl OwnedAsciiCast for Vec<u8> {
+    #[inline]
+    fn is_ascii(&self) -> bool {
+        self.as_slice().is_ascii()
+    }
+
+    #[inline]
+    unsafe fn into_ascii_nocheck(self) -> Vec<Ascii> {
         cast::transmute(self)
     }
 }
@@ -268,10 +281,10 @@ pub trait AsciiStr {
     fn as_str_ascii<'a>(&'a self) -> &'a str;
 
     /// Convert to vector representing a lower cased ascii string.
-    fn to_lower(&self) -> ~[Ascii];
+    fn to_lower(&self) -> Vec<Ascii>;
 
     /// Convert to vector representing a upper cased ascii string.
-    fn to_upper(&self) -> ~[Ascii];
+    fn to_upper(&self) -> Vec<Ascii>;
 
     /// Compares two Ascii strings ignoring case.
     fn eq_ignore_case(self, other: &[Ascii]) -> bool;
@@ -284,12 +297,12 @@ fn as_str_ascii<'a>(&'a self) -> &'a str {
     }
 
     #[inline]
-    fn to_lower(&self) -> ~[Ascii] {
+    fn to_lower(&self) -> Vec<Ascii> {
         self.iter().map(|a| a.to_lower()).collect()
     }
 
     #[inline]
-    fn to_upper(&self) -> ~[Ascii] {
+    fn to_upper(&self) -> Vec<Ascii> {
         self.iter().map(|a| a.to_upper()).collect()
     }
 
@@ -309,19 +322,21 @@ fn into_str(self) -> ~str {
 impl IntoStr for Vec<Ascii> {
     #[inline]
     fn into_str(self) -> ~str {
-        let v: ~[Ascii] = self.move_iter().collect();
-        unsafe { cast::transmute(v) }
+        unsafe {
+            let s: &str = cast::transmute(self.as_slice());
+            s.to_owned()
+        }
     }
 }
 
-/// Trait to convert to an owned byte array by consuming self
+/// Trait to convert to an owned byte vector by consuming self
 pub trait IntoBytes {
-    /// Converts to an owned byte array by consuming self
-    fn into_bytes(self) -> ~[u8];
+    /// Converts to an owned byte vector by consuming self
+    fn into_bytes(self) -> Vec<u8>;
 }
 
-impl IntoBytes for ~[Ascii] {
-    fn into_bytes(self) -> ~[u8] {
+impl IntoBytes for Vec<Ascii> {
+    fn into_bytes(self) -> Vec<u8> {
         unsafe { cast::transmute(self) }
     }
 }
@@ -404,9 +419,11 @@ unsafe fn str_map_bytes(string: ~str, map: &'static [u8]) -> ~str {
 
 #[inline]
 unsafe fn str_copy_map_bytes(string: &str, map: &'static [u8]) -> ~str {
-    let bytes = string.bytes().map(|b| map[b as uint]).collect::<~[_]>();
-
-    str::raw::from_utf8_owned(bytes)
+    let mut s = string.to_owned();
+    for b in str::raw::as_owned_vec(&mut s).mut_iter() {
+        *b = map[*b as uint];
+    }
+    s
 }
 
 static ASCII_LOWER_MAP: &'static [u8] = &[
@@ -492,7 +509,6 @@ mod tests {
     macro_rules! v2ascii (
         ( [$($e:expr),*]) => (&[$(Ascii{chr:$e}),*]);
         (&[$($e:expr),*]) => (&[$(Ascii{chr:$e}),*]);
-        (~[$($e:expr),*]) => (box [$(Ascii{chr:$e}),*]);
     )
 
     macro_rules! vec2ascii (
@@ -556,20 +572,17 @@ fn test_ascii_vec() {
 
     #[test]
     fn test_ascii_vec_ng() {
-        assert_eq!(Vec::from_slice("abCDef&?#".to_ascii().to_lower()).into_str(),
-                   "abcdef&?#".to_owned());
-        assert_eq!(Vec::from_slice("abCDef&?#".to_ascii().to_upper()).into_str(),
-                   "ABCDEF&?#".to_owned());
-        assert_eq!(Vec::from_slice("".to_ascii().to_lower()).into_str(), "".to_owned());
-        assert_eq!(Vec::from_slice("YMCA".to_ascii().to_lower()).into_str(), "ymca".to_owned());
-        assert_eq!(Vec::from_slice("abcDEFxyz:.;".to_ascii().to_upper()).into_str(),
-                   "ABCDEFXYZ:.;".to_owned());
+        assert_eq!("abCDef&?#".to_ascii().to_lower().into_str(), "abcdef&?#".to_owned());
+        assert_eq!("abCDef&?#".to_ascii().to_upper().into_str(), "ABCDEF&?#".to_owned());
+        assert_eq!("".to_ascii().to_lower().into_str(), "".to_owned());
+        assert_eq!("YMCA".to_ascii().to_lower().into_str(), "ymca".to_owned());
+        assert_eq!("abcDEFxyz:.;".to_ascii().to_upper().into_str(), "ABCDEFXYZ:.;".to_owned());
     }
 
     #[test]
     fn test_owned_ascii_vec() {
-        assert_eq!(("( ;".to_owned()).into_ascii(), v2ascii!(~[40, 32, 59]));
-        assert_eq!((box [40u8, 32u8, 59u8]).into_ascii(), v2ascii!(~[40, 32, 59]));
+        assert_eq!(("( ;".to_owned()).into_ascii(), vec2ascii![40, 32, 59]);
+        assert_eq!((box [40u8, 32u8, 59u8]).into_ascii(), vec2ascii![40, 32, 59]);
     }
 
     #[test]
@@ -580,13 +593,13 @@ fn test_ascii_as_str() {
 
     #[test]
     fn test_ascii_into_str() {
-        assert_eq!(v2ascii!(~[40, 32, 59]).into_str(), "( ;".to_owned());
+        assert_eq!(vec2ascii![40, 32, 59].into_str(), "( ;".to_owned());
         assert_eq!(vec2ascii!(40, 32, 59).into_str(), "( ;".to_owned());
     }
 
     #[test]
     fn test_ascii_to_bytes() {
-        assert_eq!(v2ascii!(~[40, 32, 59]).into_bytes(), box [40u8, 32u8, 59u8]);
+        assert_eq!(vec2ascii![40, 32, 59].into_bytes(), vec![40u8, 32u8, 59u8]);
     }
 
     #[test] #[should_fail]
@@ -625,10 +638,10 @@ fn test_opt() {
         assert_eq!(v.to_ascii_opt(), Some(v2));
         assert_eq!("zoä华".to_ascii_opt(), None);
 
-        assert_eq!((box [40u8, 32u8, 59u8]).into_ascii_opt(), Some(v2ascii!(~[40, 32, 59])));
-        assert_eq!((box [127u8, 128u8, 255u8]).into_ascii_opt(), None);
+        assert_eq!((vec![40u8, 32u8, 59u8]).into_ascii_opt(), Some(vec2ascii![40, 32, 59]));
+        assert_eq!((vec![127u8, 128u8, 255u8]).into_ascii_opt(), None);
 
-        assert_eq!(("( ;".to_owned()).into_ascii_opt(), Some(v2ascii!(~[40, 32, 59])));
+        assert_eq!(("( ;".to_owned()).into_ascii_opt(), Some(vec2ascii![40, 32, 59]));
         assert_eq!(("zoä华".to_owned()).into_ascii_opt(), None);
     }
 
index a89af05c50ae6a0f4ba6c797601bb891a197895b..4a53a064610cb0e5b8661a283d39cb2d06fb1823 100644 (file)
@@ -76,7 +76,7 @@
 
     let path = Path::new("message.txt");
     let mut file = BufferedReader::new(File::open(&path));
-    let lines: ~[~str] = file.lines().map(|x| x.unwrap()).collect();
+    let lines: Vec<~str> = file.lines().map(|x| x.unwrap()).collect();
     ```
 
 * Make a simple TCP client connection and request
index 4006665e886c6a3d671db65d70648e229dc180e1..879c66e0769d8eaecf80f54ed982df9d26964760 100644 (file)
@@ -24,7 +24,7 @@
 use io::net::ip::{SocketAddr, IpAddr};
 use option::{Option, Some, None};
 use rt::rtio::{IoFactory, LocalIo};
-use slice::OwnedVector;
+use vec::Vec;
 
 /// Hints to the types of sockets that are desired when looking up hosts
 pub enum SocketType {
@@ -73,7 +73,7 @@ pub struct Info {
 
 /// Easy name resolution. Given a hostname, returns the list of IP addresses for
 /// that hostname.
-pub fn get_host_addresses(host: &str) -> IoResult<~[IpAddr]> {
+pub fn get_host_addresses(host: &str) -> IoResult<Vec<IpAddr>> {
     lookup(Some(host), None, None).map(|a| a.move_iter().map(|i| i.address.ip).collect())
 }
 
@@ -90,7 +90,7 @@ pub fn get_host_addresses(host: &str) -> IoResult<~[IpAddr]> {
 /// FIXME: this is not public because the `Hint` structure is not ready for public
 ///      consumption just yet.
 fn lookup(hostname: Option<&str>, servname: Option<&str>, hint: Option<Hint>)
-          -> IoResult<~[Info]> {
+          -> IoResult<Vec<Info>> {
     LocalIo::maybe_raise(|io| io.get_host_addresses(hostname, servname, hint))
 }
 
index 89141155ae4caef1d0094232e15d73b9f8bf0aa5..a9aa871d926bfcc8bd13900d5febb890212ed4f1 100644 (file)
@@ -169,6 +169,7 @@ pub fn close_write(&mut self) -> IoResult<()> { self.obj.close_write() }
     ///
     /// For clarification on the semantics of interrupting a read and a write,
     /// take a look at `set_read_timeout` and `set_write_timeout`.
+    #[experimental = "the timeout argument may change in type and value"]
     pub fn set_timeout(&mut self, timeout_ms: Option<u64>) {
         self.obj.set_timeout(timeout_ms)
     }
@@ -185,6 +186,7 @@ pub fn set_timeout(&mut self, timeout_ms: Option<u64>) {
     /// action is taken. Otherwise, the read operation will be scheduled to
     /// promptly return. If a timeout error is returned, then no data was read
     /// during the timeout period.
+    #[experimental = "the timeout argument may change in type and value"]
     pub fn set_read_timeout(&mut self, timeout_ms: Option<u64>) {
         self.obj.set_read_timeout(timeout_ms)
     }
@@ -211,6 +213,7 @@ pub fn set_read_timeout(&mut self, timeout_ms: Option<u64>) {
     /// does not know how many bytes were written as part of the timeout
     /// operation. It may be the case that bytes continue to be written in an
     /// asynchronous fashion after the call to write returns.
+    #[experimental = "the timeout argument may change in type and value"]
     pub fn set_write_timeout(&mut self, timeout_ms: Option<u64>) {
         self.obj.set_write_timeout(timeout_ms)
     }
@@ -944,21 +947,26 @@ pub fn peer_name(addr: SocketAddr) {
 
         // Also make sure that even though the timeout is expired that we will
         // continue to receive any pending connections.
-        let (tx, rx) = channel();
-        spawn(proc() {
-            tx.send(TcpStream::connect(addr).unwrap());
-        });
-        let l = rx.recv();
-        for i in range(0, 1001) {
-            match a.accept() {
-                Ok(..) => break,
-                Err(ref e) if e.kind == TimedOut => {}
-                Err(e) => fail!("error: {}", e),
+        //
+        // FIXME: freebsd apparently never sees the pending connection, but
+        //        testing manually always works. Need to investigate this
+        //        flakiness.
+        if !cfg!(target_os = "freebsd") {
+            let (tx, rx) = channel();
+            spawn(proc() {
+                tx.send(TcpStream::connect(addr).unwrap());
+            });
+            let l = rx.recv();
+            for i in range(0, 1001) {
+                match a.accept() {
+                    Ok(..) => break,
+                    Err(ref e) if e.kind == TimedOut => {}
+                    Err(e) => fail!("error: {}", e),
+                }
+                ::task::deschedule();
+                if i == 1000 { fail!("should have a pending connection") }
             }
-            ::task::deschedule();
-            if i == 1000 { fail!("should have a pending connection") }
         }
-        drop(l);
 
         // Unset the timeout and make sure that this always blocks.
         a.set_timeout(None);
index 45da872ca119836ae2c0b540f03fbaa0042e6296..e66b2107bb107ce2d1bd4263cf639008a6bbee47 100644 (file)
@@ -147,6 +147,7 @@ pub fn set_broadast(&mut self, broadcast: bool) -> IoResult<()> {
     /// Sets the read/write timeout for this socket.
     ///
     /// For more information, see `TcpStream::set_timeout`
+    #[experimental = "the timeout argument may change in type and value"]
     pub fn set_timeout(&mut self, timeout_ms: Option<u64>) {
         self.obj.set_timeout(timeout_ms)
     }
@@ -154,6 +155,7 @@ pub fn set_timeout(&mut self, timeout_ms: Option<u64>) {
     /// Sets the read timeout for this socket.
     ///
     /// For more information, see `TcpStream::set_timeout`
+    #[experimental = "the timeout argument may change in type and value"]
     pub fn set_read_timeout(&mut self, timeout_ms: Option<u64>) {
         self.obj.set_read_timeout(timeout_ms)
     }
@@ -161,6 +163,7 @@ pub fn set_read_timeout(&mut self, timeout_ms: Option<u64>) {
     /// Sets the write timeout for this socket.
     ///
     /// For more information, see `TcpStream::set_timeout`
+    #[experimental = "the timeout argument may change in type and value"]
     pub fn set_write_timeout(&mut self, timeout_ms: Option<u64>) {
         self.obj.set_write_timeout(timeout_ms)
     }
index ac7a0f5cdce72a79f991d03af1a4cb5f23720fcb..1e320fe1aaed467f115733b9a1327d45d9e7a16e 100644 (file)
@@ -97,6 +97,7 @@ pub fn close_write(&mut self) -> IoResult<()> { self.obj.close_write() }
     /// Sets the read/write timeout for this socket.
     ///
     /// For more information, see `TcpStream::set_timeout`
+    #[experimental = "the timeout argument may change in type and value"]
     pub fn set_timeout(&mut self, timeout_ms: Option<u64>) {
         self.obj.set_timeout(timeout_ms)
     }
@@ -104,6 +105,7 @@ pub fn set_timeout(&mut self, timeout_ms: Option<u64>) {
     /// Sets the read timeout for this socket.
     ///
     /// For more information, see `TcpStream::set_timeout`
+    #[experimental = "the timeout argument may change in type and value"]
     pub fn set_read_timeout(&mut self, timeout_ms: Option<u64>) {
         self.obj.set_read_timeout(timeout_ms)
     }
@@ -111,6 +113,7 @@ pub fn set_read_timeout(&mut self, timeout_ms: Option<u64>) {
     /// Sets the write timeout for this socket.
     ///
     /// For more information, see `TcpStream::set_timeout`
+    #[experimental = "the timeout argument may change in type and value"]
     pub fn set_write_timeout(&mut self, timeout_ms: Option<u64>) {
         self.obj.set_write_timeout(timeout_ms)
     }
index 74f6944f102eab95ae3bee120607eaedf00ef07c..3babef6126e8fcc84e3546677803c88b8d1b2486 100644 (file)
@@ -69,7 +69,7 @@ pub struct Process {
 
     /// Extra I/O handles as configured by the original `ProcessConfig` when
     /// this process was created. This is by default empty.
-    pub extra_io: ~[Option<io::PipeStream>],
+    pub extra_io: Vec<Option<io::PipeStream>>,
 }
 
 /// This configuration describes how a new process should be spawned. A blank
@@ -418,7 +418,7 @@ fn drop(&mut self) {
         drop(self.stdin.take());
         drop(self.stdout.take());
         drop(self.stderr.take());
-        drop(mem::replace(&mut self.extra_io, box []));
+        drop(mem::replace(&mut self.extra_io, Vec::new()));
 
         self.wait();
     }
index 72d41ae1dd2911f7ce4b0b8baef1140874b1bf67..dae28777867793ef0e6566f8d9e0a601ce60282b 100644 (file)
@@ -81,7 +81,7 @@
 //! memory types, including [`atomics`](sync/atomics/index.html).
 //!
 //! Common types of I/O, including files, TCP, UPD, pipes, Unix domain sockets,
-//! timers, and process spawning, are defined in the [`io`](io/index.html).
+//! timers, and process spawning, are defined in the [`io`](io/index.html) module.
 //!
 //! Rust's I/O and concurrency depends on a small runtime interface
 //! that lives, along with its support code, in mod [`rt`](rt/index.html).
 //!
 //! ## The Rust prelude and macros
 //!
-//! Finally, the [`prelude`](prelude/index.html) defines a set of
+//! Finally, the [`prelude`](prelude/index.html) defines a
 //! common set of traits, types, and functions that are made available
 //! to all code by default. [`macros`](macros/index.html) contains
-//! all the standard macros, such as `assert!`, `fail!`, `println!`.
+//! all the standard macros, such as `assert!`, `fail!`, `println!`,
+//! and `format!`, also available to all Rust code.
 
 #![crate_id = "std#0.11-pre"]
 #![comment = "The Rust standard library"]
@@ -278,4 +279,7 @@ mod std {
     pub use ty;
     pub use unstable;
     pub use vec;
+
+    // The test runner requires std::slice::Vector, so re-export std::slice just for it.
+    #[cfg(test)] pub use slice;
 }
index 4bd2ba07634cacd291b895ddf069b8fe25b6ff45..d8f1c108b742d48dd8040b50dba5b578319d7450 100644 (file)
 //! Operations and constants for signed 16-bits integers (`i16` type)
 
 use from_str::FromStr;
-use iter::Iterator;
 use num::{ToStrRadix, FromStrRadix};
 use num::strconv;
 use option::Option;
-use slice::{ImmutableVector, OwnedVector};
+use slice::ImmutableVector;
 use str;
 
 pub use core::i16::{BITS, BYTES, MIN, MAX};
index 3c3acfae3c0f8757ddd80cfe68a237b06c2a976a..9cc8981fc13f422c10d231fd413362088f54723d 100644 (file)
 //! Operations and constants for signed 32-bits integers (`i32` type)
 
 use from_str::FromStr;
-use iter::Iterator;
 use num::{ToStrRadix, FromStrRadix};
 use num::strconv;
 use option::Option;
-use slice::{ImmutableVector, OwnedVector};
+use slice::ImmutableVector;
 use str;
 
 pub use core::i32::{BITS, BYTES, MIN, MAX};
index ad0fe1c08ef04cd621f3873b4b83726bc6cf5a6d..4f7fe32cc7088c9b7d3f171f258840d9e4bad851 100644 (file)
 //! Operations and constants for signed 64-bits integers (`i64` type)
 
 use from_str::FromStr;
-use iter::Iterator;
 use num::{ToStrRadix, FromStrRadix};
 use num::strconv;
 use option::Option;
-use slice::{ImmutableVector, OwnedVector};
+use slice::ImmutableVector;
 use str;
 
 pub use core::i64::{BITS, BYTES, MIN, MAX};
index bd40a2c53b656b0f99fdc8af858c649f904eb7f6..bea315d86837392e42a3236b646b7d747abfd36e 100644 (file)
 //! Operations and constants for signed 8-bits integers (`i8` type)
 
 use from_str::FromStr;
-use iter::Iterator;
 use num::{ToStrRadix, FromStrRadix};
 use num::strconv;
 use option::Option;
-use slice::{ImmutableVector, OwnedVector};
+use slice::ImmutableVector;
 use str;
 
 pub use core::i8::{BITS, BYTES, MIN, MAX};
index d9552ee33400ed5c898a126593009d1bb430beca..d6a7fd1660b42800eb61a8731d6eb86413ba815a 100644 (file)
 //! Operations and constants for architecture-sized signed integers (`int` type)
 
 use from_str::FromStr;
-use iter::Iterator;
 use num::{ToStrRadix, FromStrRadix};
 use num::strconv;
 use option::Option;
-use slice::{ImmutableVector, OwnedVector};
+use slice::ImmutableVector;
 use str;
 
 pub use core::int::{BITS, BYTES, MIN, MAX};
index 8a7bea465851ac21ba122a8866a2855c7af7c7fc..fcdb63f5ad5eb06564fadbc26af502becd07bc3d 100644 (file)
@@ -77,13 +77,16 @@ impl ToStrRadix for $T {
     /// Convert to a string in a given base.
     #[inline]
     fn to_str_radix(&self, radix: uint) -> ~str {
+        use slice::Vector;
+        use str::StrAllocating;
+
         let mut buf = ::vec::Vec::new();
         strconv::int_to_str_bytes_common(*self, radix, strconv::SignNeg, |i| {
             buf.push(i);
         });
         // We know we generated valid utf-8, so we don't need to go through that
         // check.
-        unsafe { str::raw::from_utf8_owned(buf.move_iter().collect()) }
+        unsafe { str::raw::from_utf8(buf.as_slice()).to_owned() }
     }
 }
 
index 8861597bb4c16d50348648dd6ffd882cdf6ab41e..4769b17fb2b84e7d15eb795117fd95311448ef69 100644 (file)
 use num;
 use ops::{Add, Sub, Mul, Div, Rem, Neg};
 use option::{None, Option, Some};
-use slice::OwnedVector;
 use slice::{CloneableVector, ImmutableVector, MutableVector};
 use std::cmp::{Ord, Eq};
-use str::{StrSlice};
-use str;
+use str::{StrAllocating, StrSlice};
+use strbuf::StrBuf;
 use vec::Vec;
 
 /// A flag that specifies whether to use exponential (scientific) notation.
@@ -262,7 +261,7 @@ pub fn float_to_str_bytes_common<T:NumCast+Zero+One+Eq+Ord+Float+
                                   Div<T,T>+Neg<T>+Rem<T,T>+Mul<T,T>>(
         num: T, radix: uint, negative_zero: bool,
         sign: SignFormat, digits: SignificantDigits, exp_format: ExponentFormat, exp_upper: bool
-        ) -> (~[u8], bool) {
+        ) -> (Vec<u8>, bool) {
     assert!(2 <= radix && radix <= 36);
     match exp_format {
         ExpDec if radix >= DIGIT_E_RADIX       // decimal exponent 'e'
@@ -278,17 +277,17 @@ pub fn float_to_str_bytes_common<T:NumCast+Zero+One+Eq+Ord+Float+
     let _1: T = One::one();
 
     match num.classify() {
-        FPNaN => { return ("NaN".as_bytes().to_owned(), true); }
+        FPNaN => { return (Vec::from_slice("NaN".as_bytes()), true); }
         FPInfinite if num > _0 => {
             return match sign {
-                SignAll => ("+inf".as_bytes().to_owned(), true),
-                _       => ("inf".as_bytes().to_owned(), true)
+                SignAll => (Vec::from_slice("+inf".as_bytes()), true),
+                _       => (Vec::from_slice("inf".as_bytes()), true)
             };
         }
         FPInfinite if num < _0 => {
             return match sign {
-                SignNone => ("inf".as_bytes().to_owned(), true),
-                _        => ("-inf".as_bytes().to_owned(), true),
+                SignNone => (Vec::from_slice("inf".as_bytes()), true),
+                _        => (Vec::from_slice("-inf".as_bytes()), true),
             };
         }
         _ => {}
@@ -483,7 +482,7 @@ pub fn float_to_str_bytes_common<T:NumCast+Zero+One+Eq+Ord+Float+
         }
     }
 
-    (buf.move_iter().collect(), false)
+    (buf, false)
 }
 
 /**
@@ -498,7 +497,7 @@ pub fn float_to_str_common<T:NumCast+Zero+One+Eq+Ord+NumStrConv+Float+
         ) -> (~str, bool) {
     let (bytes, special) = float_to_str_bytes_common(num, radix,
                                negative_zero, sign, digits, exp_format, exp_capital);
-    (str::from_utf8_owned(bytes).unwrap(), special)
+    (StrBuf::from_utf8(bytes).unwrap().into_owned(), special)
 }
 
 // Some constants for from_str_bytes_common's input validation,
index dd6a838df9ba649521654bda13a0c51722dd8794..5c93ca6c36b79748b8fba3a704eb353d4dd0feaa 100644 (file)
 //! Operations and constants for unsigned 16-bits integers (`u16` type)
 
 use from_str::FromStr;
-use iter::Iterator;
 use num::{ToStrRadix, FromStrRadix};
 use num::strconv;
 use option::Option;
-use slice::{ImmutableVector, OwnedVector};
+use slice::ImmutableVector;
 use str;
 
 pub use core::u16::{BITS, BYTES, MIN, MAX};
index bb05938969dee5bf60fd42fe0bd5f00f94b75e0c..436eae7cd14d0c839acb9f0a0a617560acaeb478 100644 (file)
 //! Operations and constants for unsigned 32-bits integers (`u32` type)
 
 use from_str::FromStr;
-use iter::Iterator;
 use num::{ToStrRadix, FromStrRadix};
 use num::strconv;
 use option::Option;
-use slice::{ImmutableVector, OwnedVector};
+use slice::ImmutableVector;
 use str;
 
 pub use core::u32::{BITS, BYTES, MIN, MAX};
index f38806e1527fd3b98ebcdcd13559033b8279d713..c654d6fbe3133df7e4e6cf36e0d4a58939a36741 100644 (file)
 //! Operations and constants for unsigned 64-bits integer (`u64` type)
 
 use from_str::FromStr;
-use iter::Iterator;
 use num::{ToStrRadix, FromStrRadix};
 use num::strconv;
 use option::Option;
-use slice::{ImmutableVector, OwnedVector};
+use slice::ImmutableVector;
 use str;
 
 pub use core::u64::{BITS, BYTES, MIN, MAX};
index 87fed563a1535658ddb17ce97274b84ad5dac09d..7051b9191be8158ba668ec23d3b079068383b5ce 100644 (file)
 //! Operations and constants for unsigned 8-bits integers (`u8` type)
 
 use from_str::FromStr;
-use iter::Iterator;
 use num::{ToStrRadix, FromStrRadix};
 use num::strconv;
 use option::Option;
-use slice::{ImmutableVector, OwnedVector};
+use slice::ImmutableVector;
 use str;
 
 pub use core::u8::{BITS, BYTES, MIN, MAX};
index 61ab97e86b87c25350772be94301a73560499ebb..d1c3e96b2c987d7334b82dd6d3dc0b70d88141e1 100644 (file)
 //! Operations and constants for architecture-sized unsigned integers (`uint` type)
 
 use from_str::FromStr;
-use iter::Iterator;
 use num::{ToStrRadix, FromStrRadix};
 use num::strconv;
 use option::Option;
-use slice::{ImmutableVector, OwnedVector};
+use slice::ImmutableVector;
 use str;
 
 pub use core::uint::{BITS, BYTES, MIN, MAX};
index 3e64c17161368bcc1f387918f82d6327f71085a3..0795238a49cff9578865f34f431f431575219533 100644 (file)
@@ -78,13 +78,16 @@ impl ToStrRadix for $T {
     /// Convert to a string in a given base.
     #[inline]
     fn to_str_radix(&self, radix: uint) -> ~str {
+        use slice::Vector;
+        use str::StrAllocating;
+
         let mut buf = ::vec::Vec::new();
         strconv::int_to_str_bytes_common(*self, radix, strconv::SignNone, |i| {
             buf.push(i);
         });
         // We know we generated valid utf-8, so we don't need to go through that
         // check.
-        unsafe { str::raw::from_utf8_owned(buf.move_iter().collect()) }
+        unsafe { str::raw::from_utf8(buf.as_slice()).to_owned() }
     }
 }
 
index 43d642c81ad151cd28fdafbd885eacecb50dade2..134cfa89a37f3bc7e2a50f1ce9f4a80d651ce64b 100644 (file)
@@ -169,7 +169,7 @@ fn with_env_lock<T>(f: || -> T) -> T {
 ///
 /// Invalid UTF-8 bytes are replaced with \uFFFD. See `str::from_utf8_lossy()`
 /// for details.
-pub fn env() -> ~[(~str,~str)] {
+pub fn env() -> Vec<(~str,~str)> {
     env_as_bytes().move_iter().map(|(k,v)| {
         let k = str::from_utf8_lossy(k).into_owned();
         let v = str::from_utf8_lossy(v).into_owned();
@@ -179,7 +179,7 @@ pub fn env() -> ~[(~str,~str)] {
 
 /// Returns a vector of (variable, value) byte-vector pairs for all the
 /// environment variables of the current process.
-pub fn env_as_bytes() -> ~[(~[u8],~[u8])] {
+pub fn env_as_bytes() -> Vec<(~[u8],~[u8])> {
     unsafe {
         #[cfg(windows)]
         unsafe fn get_env_pairs() -> Vec<~[u8]> {
@@ -224,16 +224,16 @@ unsafe fn get_env_pairs() -> Vec<~[u8]> {
         fn env_convert(input: Vec<~[u8]>) -> Vec<(~[u8], ~[u8])> {
             let mut pairs = Vec::new();
             for p in input.iter() {
-                let vs: ~[&[u8]] = p.splitn(1, |b| *b == '=' as u8).collect();
-                let key = vs[0].to_owned();
-                let val = if vs.len() < 2 { box [] } else { vs[1].to_owned() };
+                let mut it = p.splitn(1, |b| *b == '=' as u8);
+                let key = it.next().unwrap().to_owned();
+                let val = it.next().unwrap_or(&[]).to_owned();
                 pairs.push((key, val));
             }
             pairs
         }
         with_env_lock(|| {
             let unparsed_environ = get_env_pairs();
-            env_convert(unparsed_environ).move_iter().collect()
+            env_convert(unparsed_environ)
         })
     }
 }
@@ -416,7 +416,7 @@ pub fn dll_filename(base: &str) -> ~str {
 pub fn self_exe_name() -> Option<Path> {
 
     #[cfg(target_os = "freebsd")]
-    fn load_self() -> Option<~[u8]> {
+    fn load_self() -> Option<Vec<u8>> {
         unsafe {
             use libc::funcs::bsd44::*;
             use libc::consts::os::extra::*;
@@ -436,23 +436,23 @@ fn load_self() -> Option<~[u8]> {
             if err != 0 { return None; }
             if sz == 0 { return None; }
             v.set_len(sz as uint - 1); // chop off trailing NUL
-            Some(v.move_iter().collect())
+            Some(v)
         }
     }
 
     #[cfg(target_os = "linux")]
     #[cfg(target_os = "android")]
-    fn load_self() -> Option<~[u8]> {
+    fn load_self() -> Option<Vec<u8>> {
         use std::io;
 
         match io::fs::readlink(&Path::new("/proc/self/exe")) {
-            Ok(path) => Some(path.as_vec().to_owned()),
+            Ok(path) => Some(path.into_vec()),
             Err(..) => None
         }
     }
 
     #[cfg(target_os = "macos")]
-    fn load_self() -> Option<~[u8]> {
+    fn load_self() -> Option<Vec<u8>> {
         unsafe {
             use libc::funcs::extra::_NSGetExecutablePath;
             let mut sz: u32 = 0;
@@ -462,19 +462,19 @@ fn load_self() -> Option<~[u8]> {
             let err = _NSGetExecutablePath(v.as_mut_ptr() as *mut i8, &mut sz);
             if err != 0 { return None; }
             v.set_len(sz as uint - 1); // chop off trailing NUL
-            Some(v.move_iter().collect())
+            Some(v)
         }
     }
 
     #[cfg(windows)]
-    fn load_self() -> Option<~[u8]> {
+    fn load_self() -> Option<Vec<u8>> {
         use str::OwnedStr;
 
         unsafe {
             use os::win32::fill_utf16_buf_and_decode;
             fill_utf16_buf_and_decode(|buf, sz| {
                 libc::GetModuleFileNameW(0u as libc::DWORD, buf, sz)
-            }).map(|s| s.into_bytes())
+            }).map(|s| s.into_strbuf().into_bytes())
         }
     }
 
@@ -791,12 +791,12 @@ pub fn get_exit_status() -> int {
 }
 
 #[cfg(target_os = "macos")]
-unsafe fn load_argc_and_argv(argc: int, argv: **c_char) -> ~[~[u8]] {
+unsafe fn load_argc_and_argv(argc: int, argv: **c_char) -> Vec<~[u8]> {
     use c_str::CString;
 
     Vec::from_fn(argc as uint, |i| {
         CString::new(*argv.offset(i as int), false).as_bytes_no_nul().to_owned()
-    }).move_iter().collect()
+    })
 }
 
 /**
@@ -805,7 +805,7 @@ unsafe fn load_argc_and_argv(argc: int, argv: **c_char) -> ~[~[u8]] {
  * Returns a list of the command line arguments.
  */
 #[cfg(target_os = "macos")]
-fn real_args_as_bytes() -> ~[~[u8]] {
+fn real_args_as_bytes() -> Vec<~[u8]> {
     unsafe {
         let (argc, argv) = (*_NSGetArgc() as int,
                             *_NSGetArgv() as **c_char);
@@ -816,7 +816,7 @@ fn real_args_as_bytes() -> ~[~[u8]] {
 #[cfg(target_os = "linux")]
 #[cfg(target_os = "android")]
 #[cfg(target_os = "freebsd")]
-fn real_args_as_bytes() -> ~[~[u8]] {
+fn real_args_as_bytes() -> Vec<~[u8]> {
     use rt;
 
     match rt::args::clone() {
@@ -826,12 +826,12 @@ fn real_args_as_bytes() -> ~[~[u8]] {
 }
 
 #[cfg(not(windows))]
-fn real_args() -> ~[~str] {
+fn real_args() -> Vec<~str> {
     real_args_as_bytes().move_iter().map(|v| str::from_utf8_lossy(v).into_owned()).collect()
 }
 
 #[cfg(windows)]
-fn real_args() -> ~[~str] {
+fn real_args() -> Vec<~str> {
     use slice;
     use option::Expect;
 
@@ -857,11 +857,11 @@ fn real_args() -> ~[~str] {
         LocalFree(szArgList as *c_void);
     }
 
-    return args.move_iter().collect();
+    return args
 }
 
 #[cfg(windows)]
-fn real_args_as_bytes() -> ~[~[u8]] {
+fn real_args_as_bytes() -> Vec<~[u8]> {
     real_args().move_iter().map(|s| s.into_bytes()).collect()
 }
 
@@ -885,13 +885,13 @@ fn real_args_as_bytes() -> ~[~[u8]] {
 ///
 /// The arguments are interpreted as utf-8, with invalid bytes replaced with \uFFFD.
 /// See `str::from_utf8_lossy` for details.
-pub fn args() -> ~[~str] {
+pub fn args() -> Vec<~str> {
     real_args()
 }
 
 /// Returns the arguments which this program was started with (normally passed
 /// via the command line) as byte vectors.
-pub fn args_as_bytes() -> ~[~[u8]] {
+pub fn args_as_bytes() -> Vec<~[u8]> {
     real_args_as_bytes()
 }
 
index ac1692e6bb33ab327bebdbb2285ef976e01cfa56..df0f1d8d449e44f44919b7351a45b0d366eb3ae6 100644 (file)
@@ -21,6 +21,7 @@
 //! FIXME #7756: This has a lot of C glue for lack of globals.
 
 use option::Option;
+use vec::Vec;
 #[cfg(test)] use option::{Some, None};
 #[cfg(test)] use realstd;
 #[cfg(test)] use realargs = realstd::rt::args;
@@ -36,10 +37,10 @@ pub unsafe fn init(argc: int, argv: **u8) { realargs::init(argc, argv) }
 #[cfg(test)]      pub unsafe fn cleanup() { realargs::cleanup() }
 
 /// Take the global arguments from global storage.
-#[cfg(not(test))] pub fn take() -> Option<~[~[u8]]> { imp::take() }
-#[cfg(test)]      pub fn take() -> Option<~[~[u8]]> {
+#[cfg(not(test))] pub fn take() -> Option<Vec<~[u8]>> { imp::take() }
+#[cfg(test)]      pub fn take() -> Option<Vec<~[u8]>> {
     match realargs::take() {
-        realstd::option::Some(a) => Some(a),
+        realstd::option::Some(v) => Some(unsafe{ ::cast::transmute(v) }),
         realstd::option::None => None,
     }
 }
@@ -47,14 +48,14 @@ pub unsafe fn init(argc: int, argv: **u8) { realargs::init(argc, argv) }
 /// Give the global arguments to global storage.
 ///
 /// It is an error if the arguments already exist.
-#[cfg(not(test))] pub fn put(args: ~[~[u8]]) { imp::put(args) }
-#[cfg(test)]      pub fn put(args: ~[~[u8]]) { realargs::put(args) }
+#[cfg(not(test))] pub fn put(args: Vec<~[u8]>) { imp::put(args) }
+#[cfg(test)]      pub fn put(args: Vec<~[u8]>) { realargs::put(unsafe { ::cast::transmute(args) }) }
 
 /// Make a clone of the global arguments.
-#[cfg(not(test))] pub fn clone() -> Option<~[~[u8]]> { imp::clone() }
-#[cfg(test)]      pub fn clone() -> Option<~[~[u8]]> {
+#[cfg(not(test))] pub fn clone() -> Option<Vec<~[u8]>> { imp::clone() }
+#[cfg(test)]      pub fn clone() -> Option<Vec<~[u8]>> {
     match realargs::clone() {
-        realstd::option::Some(a) => Some(a),
+        realstd::option::Some(v) => Some(unsafe { ::cast::transmute(v) }),
         realstd::option::None => None,
     }
 }
@@ -70,6 +71,7 @@ mod imp {
     use owned::Box;
     use unstable::mutex::{StaticNativeMutex, NATIVE_MUTEX_INIT};
     use mem;
+    use vec::Vec;
     #[cfg(not(test))] use ptr::RawPtr;
 
     static mut global_args_ptr: uint = 0;
@@ -87,15 +89,15 @@ pub unsafe fn cleanup() {
         lock.destroy();
     }
 
-    pub fn take() -> Option<~[~[u8]]> {
+    pub fn take() -> Option<Vec<~[u8]>> {
         with_lock(|| unsafe {
             let ptr = get_global_ptr();
             let val = mem::replace(&mut *ptr, None);
-            val.as_ref().map(|s: &Box<~[~[u8]]>| (**s).clone())
+            val.as_ref().map(|s: &Box<Vec<~[u8]>>| (**s).clone())
         })
     }
 
-    pub fn put(args: ~[~[u8]]) {
+    pub fn put(args: Vec<~[u8]>) {
         with_lock(|| unsafe {
             let ptr = get_global_ptr();
             rtassert!((*ptr).is_none());
@@ -103,10 +105,10 @@ pub fn put(args: ~[~[u8]]) {
         })
     }
 
-    pub fn clone() -> Option<~[~[u8]]> {
+    pub fn clone() -> Option<Vec<~[u8]>> {
         with_lock(|| unsafe {
             let ptr = get_global_ptr();
-            (*ptr).as_ref().map(|s: &Box<~[~[u8]]>| (**s).clone())
+            (*ptr).as_ref().map(|s: &Box<Vec<~[u8]>>| (**s).clone())
         })
     }
 
@@ -117,13 +119,13 @@ fn with_lock<T>(f: || -> T) -> T {
         }
     }
 
-    fn get_global_ptr() -> *mut Option<Box<~[~[u8]]>> {
+    fn get_global_ptr() -> *mut Option<Box<Vec<~[u8]>>> {
         unsafe { cast::transmute(&global_args_ptr) }
     }
 
     // Copied from `os`.
     #[cfg(not(test))]
-    unsafe fn load_argc_and_argv(argc: int, argv: **u8) -> ~[~[u8]] {
+    unsafe fn load_argc_and_argv(argc: int, argv: **u8) -> Vec<~[u8]> {
         use c_str::CString;
         use ptr::RawPtr;
         use libc;
@@ -133,7 +135,7 @@ unsafe fn load_argc_and_argv(argc: int, argv: **u8) -> ~[~[u8]] {
         Vec::from_fn(argc as uint, |i| {
             let cs = CString::new(*(argv as **libc::c_char).offset(i as int), false);
             cs.as_bytes_no_nul().to_owned()
-        }).move_iter().collect()
+        })
     }
 
     #[cfg(test)]
@@ -147,7 +149,7 @@ fn smoke_test() {
             // Preserve the actual global state.
             let saved_value = take();
 
-            let expected = box [bytes!("happy").to_owned(), bytes!("today?").to_owned()];
+            let expected = vec![bytes!("happy").to_owned(), bytes!("today?").to_owned()];
 
             put(expected.clone());
             assert!(clone() == Some(expected.clone()));
@@ -170,6 +172,7 @@ fn smoke_test() {
 #[cfg(target_os = "win32", not(test))]
 mod imp {
     use option::Option;
+    use vec::Vec;
 
     pub unsafe fn init(_argc: int, _argv: **u8) {
     }
@@ -177,15 +180,15 @@ pub unsafe fn init(_argc: int, _argv: **u8) {
     pub fn cleanup() {
     }
 
-    pub fn take() -> Option<~[~[u8]]> {
+    pub fn take() -> Option<Vec<~[u8]>> {
         fail!()
     }
 
-    pub fn put(_args: ~[~[u8]]) {
+    pub fn put(_args: Vec<~[u8]>) {
         fail!()
     }
 
-    pub fn clone() -> Option<~[~[u8]]> {
+    pub fn clone() -> Option<Vec<~[u8]>> {
         fail!()
     }
 }
index 16882624ab71aa8b656d0856cfa0f0a84c4885cf..ccde8d9c96af08cf15bcc141624531a4d5009aab 100644 (file)
@@ -161,7 +161,7 @@ fn unix_bind(&mut self, path: &CString)
     fn unix_connect(&mut self, path: &CString,
                     timeout: Option<u64>) -> IoResult<Box<RtioPipe:Send>>;
     fn get_host_addresses(&mut self, host: Option<&str>, servname: Option<&str>,
-                          hint: Option<ai::Hint>) -> IoResult<~[ai::Info]>;
+                          hint: Option<ai::Hint>) -> IoResult<Vec<ai::Info>>;
 
     // filesystem operations
     fn fs_from_raw_fd(&mut self, fd: c_int, close: CloseBehavior)
@@ -191,7 +191,7 @@ fn fs_utime(&mut self, src: &CString, atime: u64, mtime: u64) ->
     fn timer_init(&mut self) -> IoResult<Box<RtioTimer:Send>>;
     fn spawn(&mut self, config: ProcessConfig)
             -> IoResult<(Box<RtioProcess:Send>,
-                         ~[Option<Box<RtioPipe:Send>>])>;
+                         Vec<Option<Box<RtioPipe:Send>>>)>;
     fn kill(&mut self, pid: libc::pid_t, signal: int) -> IoResult<()>;
     fn pipe_open(&mut self, fd: c_int) -> IoResult<Box<RtioPipe:Send>>;
     fn tty_open(&mut self, fd: c_int, readable: bool)
index c7cefbb28eef9d0e1a143f919db3f720f2723c3b..21084407b8d09db070560c5f4a64e06246f86311 100644 (file)
@@ -127,23 +127,23 @@ pub trait VectorVector<T> {
     // FIXME #5898: calling these .concat and .connect conflicts with
     // StrVector::con{cat,nect}, since they have generic contents.
     /// Flattens a vector of vectors of T into a single vector of T.
-    fn concat_vec(&self) -> ~[T];
+    fn concat_vec(&self) -> Vec<T>;
 
     /// Concatenate a vector of vectors, placing a given separator between each.
-    fn connect_vec(&self, sep: &T) -> ~[T];
+    fn connect_vec(&self, sep: &T) -> Vec<T>;
 }
 
 impl<'a, T: Clone, V: Vector<T>> VectorVector<T> for &'a [V] {
-    fn concat_vec(&self) -> ~[T] {
+    fn concat_vec(&self) -> Vec<T> {
         let size = self.iter().fold(0u, |acc, v| acc + v.as_slice().len());
         let mut result = Vec::with_capacity(size);
         for v in self.iter() {
             result.push_all(v.as_slice())
         }
-        result.move_iter().collect()
+        result
     }
 
-    fn connect_vec(&self, sep: &T) -> ~[T] {
+    fn connect_vec(&self, sep: &T) -> Vec<T> {
         let size = self.iter().fold(0u, |acc, v| acc + v.as_slice().len());
         let mut result = Vec::with_capacity(size + self.len());
         let mut first = true;
@@ -151,29 +151,10 @@ fn connect_vec(&self, sep: &T) -> ~[T] {
             if first { first = false } else { result.push(sep.clone()) }
             result.push_all(v.as_slice())
         }
-        result.move_iter().collect()
+        result
     }
 }
 
-/**
- * Convert an iterator of pairs into a pair of vectors.
- *
- * Returns a tuple containing two vectors where the i-th element of the first
- * vector contains the first element of the i-th tuple of the input iterator,
- * and the i-th element of the second vector contains the second element
- * of the i-th tuple of the input iterator.
- */
-pub fn unzip<T, U, V: Iterator<(T, U)>>(mut iter: V) -> (~[T], ~[U]) {
-    let (lo, _) = iter.size_hint();
-    let mut ts = Vec::with_capacity(lo);
-    let mut us = Vec::with_capacity(lo);
-    for (t, u) in iter {
-        ts.push(t);
-        us.push(u);
-    }
-    (ts.move_iter().collect(), us.move_iter().collect())
-}
-
 /// An Iterator that yields the element swaps needed to produce
 /// a sequence of all possible permutations for an indexed sequence of
 /// elements. Each permutation is only a single swap apart.
@@ -185,7 +166,7 @@ pub fn unzip<T, U, V: Iterator<(T, U)>>(mut iter: V) -> (~[T], ~[U]) {
 /// The last generated swap is always (0, 1), and it returns the
 /// sequence to its initial order.
 pub struct ElementSwaps {
-    sdir: ~[SizeDirection],
+    sdir: Vec<SizeDirection>,
     /// If true, emit the last swap that returns the sequence to initial state
     emit_reset: bool,
     swaps_made : uint,
@@ -199,9 +180,7 @@ pub fn new(length: uint) -> ElementSwaps {
         // element (equal to the original index).
         ElementSwaps{
             emit_reset: true,
-            sdir: range(0, length)
-                    .map(|i| SizeDirection{ size: i, dir: Neg })
-                    .collect::<~[_]>(),
+            sdir: range(0, length).map(|i| SizeDirection{ size: i, dir: Neg }).collect(),
             swaps_made: 0
         }
     }
@@ -228,12 +207,12 @@ fn new_pos(i: uint, s: Direction) -> uint {
         let max = self.sdir.iter().map(|&x| x).enumerate()
                            .filter(|&(i, sd)|
                                 new_pos(i, sd.dir) < self.sdir.len() &&
-                                self.sdir[new_pos(i, sd.dir)].size < sd.size)
+                                self.sdir.get(new_pos(i, sd.dir)).size < sd.size)
                            .max_by(|&(_, sd)| sd.size);
         match max {
             Some((i, sd)) => {
                 let j = new_pos(i, sd.dir);
-                self.sdir.swap(i, j);
+                self.sdir.as_mut_slice().swap(i, j);
 
                 // Swap the direction of each larger SizeDirection
                 for x in self.sdir.mut_iter() {
@@ -314,16 +293,29 @@ impl<'a, T: Clone> CloneableVector<T> for &'a [T] {
     /// Returns a copy of `v`.
     #[inline]
     fn to_owned(&self) -> ~[T] {
+        use RawVec = core::raw::Vec;
+        use rt::global_heap::{malloc_raw, exchange_free};
+        use num::{CheckedAdd, CheckedMul};
+        use option::Expect;
+
         let len = self.len();
-        let mut result = Vec::with_capacity(len);
-        // Unsafe code so this can be optimised to a memcpy (or something
-        // similarly fast) when T is Copy. LLVM is easily confused, so any
-        // extra operations during the loop can prevent this optimisation
+        let data_size = len.checked_mul(&mem::size_of::<T>());
+        let data_size = data_size.expect("overflow in to_owned()");
+        let size = mem::size_of::<RawVec<()>>().checked_add(&data_size);
+        let size = size.expect("overflow in to_owned()");
+
         unsafe {
+            let ret = malloc_raw(size) as *mut RawVec<()>;
+
+            (*ret).fill = len * mem::nonzero_size_of::<T>();
+            (*ret).alloc = len * mem::nonzero_size_of::<T>();
+
+            // Be careful with the following loop. We want it to be optimized
+            // to a memcpy (or something similarly fast) when T is Copy. LLVM
+            // is easily confused, so any extra operations during the loop can
+            // prevent this optimization.
             let mut i = 0;
-            let p = result.as_mut_ptr();
-            // Use try_finally here otherwise the write to length
-            // inside the loop stops LLVM from optimising this.
+            let p = &mut (*ret).data as *mut _ as *mut T;
             try_finally(
                 &mut i, (),
                 |i, ()| while *i < len {
@@ -332,9 +324,15 @@ fn to_owned(&self) -> ~[T] {
                         self.unsafe_ref(*i).clone());
                     *i += 1;
                 },
-                |i| result.set_len(*i));
+                |i| if *i < len {
+                    // we must be failing, clean up after ourselves
+                    for j in range(0, *i as int) {
+                        ptr::read(&*p.offset(j));
+                    }
+                    exchange_free(ret as *u8);
+                });
+            cast::transmute(ret)
         }
-        result.move_iter().collect()
     }
 
     #[inline(always)]
@@ -354,7 +352,7 @@ fn into_owned(self) -> ~[T] { self }
 pub trait ImmutableCloneableVector<T> {
     /// Partitions the vector into two vectors `(A,B)`, where all
     /// elements of `A` satisfy `f` and all elements of `B` do not.
-    fn partitioned(&self, f: |&T| -> bool) -> (~[T], ~[T]);
+    fn partitioned(&self, f: |&T| -> bool) -> (Vec<T>, Vec<T>);
 
     /// Create an iterator that yields every possible permutation of the
     /// vector in succession.
@@ -363,7 +361,7 @@ pub trait ImmutableCloneableVector<T> {
 
 impl<'a,T:Clone> ImmutableCloneableVector<T> for &'a [T] {
     #[inline]
-    fn partitioned(&self, f: |&T| -> bool) -> (~[T], ~[T]) {
+    fn partitioned(&self, f: |&T| -> bool) -> (Vec<T>, Vec<T>) {
         let mut lefts  = Vec::new();
         let mut rights = Vec::new();
 
@@ -375,7 +373,7 @@ fn partitioned(&self, f: |&T| -> bool) -> (~[T], ~[T]) {
             }
         }
 
-        (lefts.move_iter().collect(), rights.move_iter().collect())
+        (lefts, rights)
     }
 
     fn permutations(self) -> Permutations<T> {
@@ -412,7 +410,7 @@ pub trait OwnedVector<T> {
      * Partitions the vector into two vectors `(A,B)`, where all
      * elements of `A` satisfy `f` and all elements of `B` do not.
      */
-    fn partition(self, f: |&T| -> bool) -> (~[T], ~[T]);
+    fn partition(self, f: |&T| -> bool) -> (Vec<T>, Vec<T>);
 }
 
 impl<T> OwnedVector<T> for ~[T] {
@@ -432,7 +430,7 @@ fn move_rev_iter(self) -> Rev<MoveItems<T>> {
     }
 
     #[inline]
-    fn partition(self, f: |&T| -> bool) -> (~[T], ~[T]) {
+    fn partition(self, f: |&T| -> bool) -> (Vec<T>, Vec<T>) {
         let mut lefts  = Vec::new();
         let mut rights = Vec::new();
 
@@ -444,7 +442,7 @@ fn partition(self, f: |&T| -> bool) -> (~[T], ~[T]) {
             }
         }
 
-        (lefts.move_iter().collect(), rights.move_iter().collect())
+        (lefts, rights)
     }
 }
 
@@ -729,45 +727,10 @@ fn sort(self) {
     }
 }
 
-/**
-* Constructs a vector from an unsafe pointer to a buffer
-*
-* # Arguments
-*
-* * ptr - An unsafe pointer to a buffer of `T`
-* * elts - The number of elements in the buffer
-*/
-// Wrapper for fn in raw: needs to be called by net_tcp::on_tcp_read_cb
-pub unsafe fn from_buf<T>(ptr: *T, elts: uint) -> ~[T] {
-    raw::from_buf_raw(ptr, elts)
-}
-
 /// Unsafe operations
 pub mod raw {
-    use iter::Iterator;
-    use ptr;
-    use slice::{MutableVector, OwnedVector};
-    use vec::Vec;
-
     pub use core::slice::raw::{buf_as_slice, mut_buf_as_slice};
     pub use core::slice::raw::{shift_ptr, pop_ptr};
-
-    /**
-    * Constructs a vector from an unsafe pointer to a buffer
-    *
-    * # Arguments
-    *
-    * * ptr - An unsafe pointer to a buffer of `T`
-    * * elts - The number of elements in the buffer
-    */
-    // Was in raw, but needs to be called by net_tcp::on_tcp_read_cb
-    #[inline]
-    pub unsafe fn from_buf_raw<T>(ptr: *T, elts: uint) -> ~[T] {
-        let mut dst = Vec::with_capacity(elts);
-        dst.set_len(elts);
-        ptr::copy_memory(dst.as_mut_ptr(), ptr, elts);
-        dst.move_iter().collect()
-    }
 }
 
 /// An iterator that moves out of a vector.
@@ -827,31 +790,6 @@ fn square(n: uint) -> uint { n * n }
 
     fn is_odd(n: &uint) -> bool { *n % 2u == 1u }
 
-    #[test]
-    fn test_unsafe_ptrs() {
-        unsafe {
-            // Test on-stack copy-from-buf.
-            let a = box [1, 2, 3];
-            let mut ptr = a.as_ptr();
-            let b = from_buf(ptr, 3u);
-            assert_eq!(b.len(), 3u);
-            assert_eq!(b[0], 1);
-            assert_eq!(b[1], 2);
-            assert_eq!(b[2], 3);
-
-            // Test on-heap copy-from-buf.
-            let c = box [1, 2, 3, 4, 5];
-            ptr = c.as_ptr();
-            let d = from_buf(ptr, 5u);
-            assert_eq!(d.len(), 5u);
-            assert_eq!(d[0], 1);
-            assert_eq!(d[1], 2);
-            assert_eq!(d[2], 3);
-            assert_eq!(d[3], 4);
-            assert_eq!(d[4], 5);
-        }
-    }
-
     #[test]
     fn test_from_fn() {
         // Test on-stack from_fn.
@@ -1230,17 +1168,6 @@ fn test_retain() {
         assert_eq!(v, vec![1, 3, 5]);
     }
 
-    #[test]
-    fn test_zip_unzip() {
-        let z1 = vec![(1, 4), (2, 5), (3, 6)];
-
-        let (left, right) = unzip(z1.iter().map(|&x| x));
-
-        assert_eq!((1, 4), (left[0], right[0]));
-        assert_eq!((2, 5), (left[1], right[1]));
-        assert_eq!((3, 6), (left[2], right[2]));
-    }
-
     #[test]
     fn test_element_swaps() {
         let mut v = [1, 2, 3];
@@ -1425,7 +1352,7 @@ fn test_sort_stability() {
                         let n = task_rng().gen::<uint>() % 10;
                         counts[n] += 1;
                         (n, counts[n])
-                    }).collect::<~[(uint, int)]>();
+                    }).collect::<Vec<(uint, int)>>();
 
                 // only sort on the first element, so an unstable sort
                 // may mix up the counts.
@@ -1436,46 +1363,45 @@ fn test_sort_stability() {
                 // will need to be ordered with increasing
                 // counts... i.e. exactly asserting that this sort is
                 // stable.
-                assert!(v.windows(2).all(|w| w[0] <= w[1]));
+                assert!(v.as_slice().windows(2).all(|w| w[0] <= w[1]));
             }
         }
     }
 
     #[test]
     fn test_partition() {
-        assert_eq!((box []).partition(|x: &int| *x < 3), (box [], box []));
-        assert_eq!((box [1, 2, 3]).partition(|x: &int| *x < 4), (box [1, 2, 3], box []));
-        assert_eq!((box [1, 2, 3]).partition(|x: &int| *x < 2), (box [1], box [2, 3]));
-        assert_eq!((box [1, 2, 3]).partition(|x: &int| *x < 0), (box [], box [1, 2, 3]));
+        assert_eq!((box []).partition(|x: &int| *x < 3), (vec![], vec![]));
+        assert_eq!((box [1, 2, 3]).partition(|x: &int| *x < 4), (vec![1, 2, 3], vec![]));
+        assert_eq!((box [1, 2, 3]).partition(|x: &int| *x < 2), (vec![1], vec![2, 3]));
+        assert_eq!((box [1, 2, 3]).partition(|x: &int| *x < 0), (vec![], vec![1, 2, 3]));
     }
 
     #[test]
     fn test_partitioned() {
-        assert_eq!(([]).partitioned(|x: &int| *x < 3), (box [], box []))
-        assert_eq!(([1, 2, 3]).partitioned(|x: &int| *x < 4), (box [1, 2, 3], box []));
-        assert_eq!(([1, 2, 3]).partitioned(|x: &int| *x < 2), (box [1], box [2, 3]));
-        assert_eq!(([1, 2, 3]).partitioned(|x: &int| *x < 0), (box [], box [1, 2, 3]));
+        assert_eq!(([]).partitioned(|x: &int| *x < 3), (vec![], vec![]));
+        assert_eq!(([1, 2, 3]).partitioned(|x: &int| *x < 4), (vec![1, 2, 3], vec![]));
+        assert_eq!(([1, 2, 3]).partitioned(|x: &int| *x < 2), (vec![1], vec![2, 3]));
+        assert_eq!(([1, 2, 3]).partitioned(|x: &int| *x < 0), (vec![], vec![1, 2, 3]));
     }
 
     #[test]
     fn test_concat() {
         let v: [~[int], ..0] = [];
-        assert_eq!(v.concat_vec(), box []);
-        assert_eq!([box [1], box [2,3]].concat_vec(), box [1, 2, 3]);
+        assert_eq!(v.concat_vec(), vec![]);
+        assert_eq!([box [1], box [2,3]].concat_vec(), vec![1, 2, 3]);
 
-        assert_eq!([&[1], &[2,3]].concat_vec(), box [1, 2, 3]);
+        assert_eq!([&[1], &[2,3]].concat_vec(), vec![1, 2, 3]);
     }
 
     #[test]
     fn test_connect() {
         let v: [~[int], ..0] = [];
-        assert_eq!(v.connect_vec(&0), box []);
-        assert_eq!([box [1], box [2, 3]].connect_vec(&0), box [1, 0, 2, 3]);
-        assert_eq!([box [1], box [2], box [3]].connect_vec(&0), box [1, 0, 2, 0, 3]);
+        assert_eq!(v.connect_vec(&0), vec![]);
+        assert_eq!([box [1], box [2, 3]].connect_vec(&0), vec![1, 0, 2, 3]);
+        assert_eq!([box [1], box [2], box [3]].connect_vec(&0), vec![1, 0, 2, 0, 3]);
 
-        assert_eq!(v.connect_vec(&0), box []);
-        assert_eq!([&[1], &[2, 3]].connect_vec(&0), box [1, 0, 2, 3]);
-        assert_eq!([&[1], &[2], &[3]].connect_vec(&0), box [1, 0, 2, 0, 3]);
+        assert_eq!([&[1], &[2, 3]].connect_vec(&0), vec![1, 0, 2, 3]);
+        assert_eq!([&[1], &[2], &[3]].connect_vec(&0), vec![1, 0, 2, 0, 3]);
     }
 
     #[test]
@@ -1773,74 +1699,74 @@ fn test_move_rev_iterator() {
     fn test_splitator() {
         let xs = &[1i,2,3,4,5];
 
-        assert_eq!(xs.split(|x| *x % 2 == 0).collect::<~[&[int]]>(),
-                   box [&[1], &[3], &[5]]);
-        assert_eq!(xs.split(|x| *x == 1).collect::<~[&[int]]>(),
-                   box [&[], &[2,3,4,5]]);
-        assert_eq!(xs.split(|x| *x == 5).collect::<~[&[int]]>(),
-                   box [&[1,2,3,4], &[]]);
-        assert_eq!(xs.split(|x| *x == 10).collect::<~[&[int]]>(),
-                   box [&[1,2,3,4,5]]);
-        assert_eq!(xs.split(|_| true).collect::<~[&[int]]>(),
-                   box [&[], &[], &[], &[], &[], &[]]);
+        assert_eq!(xs.split(|x| *x % 2 == 0).collect::<Vec<&[int]>>().as_slice(),
+                   &[&[1], &[3], &[5]]);
+        assert_eq!(xs.split(|x| *x == 1).collect::<Vec<&[int]>>().as_slice(),
+                   &[&[], &[2,3,4,5]]);
+        assert_eq!(xs.split(|x| *x == 5).collect::<Vec<&[int]>>().as_slice(),
+                   &[&[1,2,3,4], &[]]);
+        assert_eq!(xs.split(|x| *x == 10).collect::<Vec<&[int]>>().as_slice(),
+                   &[&[1,2,3,4,5]]);
+        assert_eq!(xs.split(|_| true).collect::<Vec<&[int]>>().as_slice(),
+                   &[&[], &[], &[], &[], &[], &[]]);
 
         let xs: &[int] = &[];
-        assert_eq!(xs.split(|x| *x == 5).collect::<~[&[int]]>(), box [&[]]);
+        assert_eq!(xs.split(|x| *x == 5).collect::<Vec<&[int]>>().as_slice(), &[&[]]);
     }
 
     #[test]
     fn test_splitnator() {
         let xs = &[1i,2,3,4,5];
 
-        assert_eq!(xs.splitn(0, |x| *x % 2 == 0).collect::<~[&[int]]>(),
-                   box [&[1,2,3,4,5]]);
-        assert_eq!(xs.splitn(1, |x| *x % 2 == 0).collect::<~[&[int]]>(),
-                   box [&[1], &[3,4,5]]);
-        assert_eq!(xs.splitn(3, |_| true).collect::<~[&[int]]>(),
-                   box [&[], &[], &[], &[4,5]]);
+        assert_eq!(xs.splitn(0, |x| *x % 2 == 0).collect::<Vec<&[int]>>().as_slice(),
+                   &[&[1,2,3,4,5]]);
+        assert_eq!(xs.splitn(1, |x| *x % 2 == 0).collect::<Vec<&[int]>>().as_slice(),
+                   &[&[1], &[3,4,5]]);
+        assert_eq!(xs.splitn(3, |_| true).collect::<Vec<&[int]>>().as_slice(),
+                   &[&[], &[], &[], &[4,5]]);
 
         let xs: &[int] = &[];
-        assert_eq!(xs.splitn(1, |x| *x == 5).collect::<~[&[int]]>(), box [&[]]);
+        assert_eq!(xs.splitn(1, |x| *x == 5).collect::<Vec<&[int]>>().as_slice(), &[&[]]);
     }
 
     #[test]
     fn test_rsplitator() {
         let xs = &[1i,2,3,4,5];
 
-        assert_eq!(xs.split(|x| *x % 2 == 0).rev().collect::<~[&[int]]>(),
-                   box [&[5], &[3], &[1]]);
-        assert_eq!(xs.split(|x| *x == 1).rev().collect::<~[&[int]]>(),
-                   box [&[2,3,4,5], &[]]);
-        assert_eq!(xs.split(|x| *x == 5).rev().collect::<~[&[int]]>(),
-                   box [&[], &[1,2,3,4]]);
-        assert_eq!(xs.split(|x| *x == 10).rev().collect::<~[&[int]]>(),
-                   box [&[1,2,3,4,5]]);
+        assert_eq!(xs.split(|x| *x % 2 == 0).rev().collect::<Vec<&[int]>>().as_slice(),
+                   &[&[5], &[3], &[1]]);
+        assert_eq!(xs.split(|x| *x == 1).rev().collect::<Vec<&[int]>>().as_slice(),
+                   &[&[2,3,4,5], &[]]);
+        assert_eq!(xs.split(|x| *x == 5).rev().collect::<Vec<&[int]>>().as_slice(),
+                   &[&[], &[1,2,3,4]]);
+        assert_eq!(xs.split(|x| *x == 10).rev().collect::<Vec<&[int]>>().as_slice(),
+                   &[&[1,2,3,4,5]]);
 
         let xs: &[int] = &[];
-        assert_eq!(xs.split(|x| *x == 5).rev().collect::<~[&[int]]>(), box [&[]]);
+        assert_eq!(xs.split(|x| *x == 5).rev().collect::<Vec<&[int]>>().as_slice(), &[&[]]);
     }
 
     #[test]
     fn test_rsplitnator() {
         let xs = &[1,2,3,4,5];
 
-        assert_eq!(xs.rsplitn(0, |x| *x % 2 == 0).collect::<~[&[int]]>(),
-                   box [&[1,2,3,4,5]]);
-        assert_eq!(xs.rsplitn(1, |x| *x % 2 == 0).collect::<~[&[int]]>(),
-                   box [&[5], &[1,2,3]]);
-        assert_eq!(xs.rsplitn(3, |_| true).collect::<~[&[int]]>(),
-                   box [&[], &[], &[], &[1,2]]);
+        assert_eq!(xs.rsplitn(0, |x| *x % 2 == 0).collect::<Vec<&[int]>>().as_slice(),
+                   &[&[1,2,3,4,5]]);
+        assert_eq!(xs.rsplitn(1, |x| *x % 2 == 0).collect::<Vec<&[int]>>().as_slice(),
+                   &[&[5], &[1,2,3]]);
+        assert_eq!(xs.rsplitn(3, |_| true).collect::<Vec<&[int]>>().as_slice(),
+                   &[&[], &[], &[], &[1,2]]);
 
         let xs: &[int] = &[];
-        assert_eq!(xs.rsplitn(1, |x| *x == 5).collect::<~[&[int]]>(), box [&[]]);
+        assert_eq!(xs.rsplitn(1, |x| *x == 5).collect::<Vec<&[int]>>().as_slice(), &[&[]]);
     }
 
     #[test]
     fn test_windowsator() {
         let v = &[1i,2,3,4];
 
-        assert_eq!(v.windows(2).collect::<~[&[int]]>(), box [&[1,2], &[2,3], &[3,4]]);
-        assert_eq!(v.windows(3).collect::<~[&[int]]>(), box [&[1i,2,3], &[2,3,4]]);
+        assert_eq!(v.windows(2).collect::<Vec<&[int]>>().as_slice(), &[&[1,2], &[2,3], &[3,4]]);
+        assert_eq!(v.windows(3).collect::<Vec<&[int]>>().as_slice(), &[&[1i,2,3], &[2,3,4]]);
         assert!(v.windows(6).next().is_none());
     }
 
@@ -1855,11 +1781,11 @@ fn test_windowsator_0() {
     fn test_chunksator() {
         let v = &[1i,2,3,4,5];
 
-        assert_eq!(v.chunks(2).collect::<~[&[int]]>(), box [&[1i,2], &[3,4], &[5]]);
-        assert_eq!(v.chunks(3).collect::<~[&[int]]>(), box [&[1i,2,3], &[4,5]]);
-        assert_eq!(v.chunks(6).collect::<~[&[int]]>(), box [&[1i,2,3,4,5]]);
+        assert_eq!(v.chunks(2).collect::<Vec<&[int]>>().as_slice(), &[&[1i,2], &[3,4], &[5]]);
+        assert_eq!(v.chunks(3).collect::<Vec<&[int]>>().as_slice(), &[&[1i,2,3], &[4,5]]);
+        assert_eq!(v.chunks(6).collect::<Vec<&[int]>>().as_slice(), &[&[1i,2,3,4,5]]);
 
-        assert_eq!(v.chunks(2).rev().collect::<~[&[int]]>(), box [&[5i], &[3,4], &[1,2]]);
+        assert_eq!(v.chunks(2).rev().collect::<Vec<&[int]>>().as_slice(), &[&[5i], &[3,4], &[1,2]]);
         let mut it = v.chunks(2);
         assert_eq!(it.indexable(), 3);
         assert_eq!(it.idx(0).unwrap(), &[1,2]);
@@ -2237,15 +2163,6 @@ fn mut_iterator(b: &mut Bencher) {
         })
     }
 
-    #[bench]
-    fn add(b: &mut Bencher) {
-        let xs: &[int] = [5, ..10];
-        let ys: &[int] = [5, ..10];
-        b.iter(|| {
-            xs + ys;
-        });
-    }
-
     #[bench]
     fn concat(b: &mut Bencher) {
         let xss: Vec<Vec<uint>> = Vec::from_fn(100, |i| range(0, i).collect());
index 666c0a58b3351b1d2b37473a4491de3312661f80..fb3dcc972871d67ac51fb365bd2ad57767e7ea26 100644 (file)
@@ -85,10 +85,9 @@ fn main() {
 use io::Writer;
 use iter::{Iterator, range, AdditiveIterator};
 use option::{None, Option, Some};
-use ptr;
 use from_str::FromStr;
-use slice::{OwnedVector, ImmutableVector, MutableVector};
-use slice::{Vector};
+use slice::{ImmutableVector, MutableVector, CloneableVector};
+use slice::Vector;
 use vec::Vec;
 use default::Default;
 use strbuf::StrBuf;
@@ -668,25 +667,22 @@ fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
 /// Unsafe operations
 pub mod raw {
     use cast;
-    use iter::Iterator;
     use libc;
     use ptr::RawPtr;
-    use ptr;
-    use slice::{MutableVector, OwnedVector, Vector};
-    use str::{is_utf8};
-    use vec::Vec;
+    use raw::Slice;
+    use slice::CloneableVector;
+    use str::{is_utf8, StrAllocating};
 
     pub use core::str::raw::{from_utf8, c_str_to_static_slice, slice_bytes};
     pub use core::str::raw::{slice_unchecked};
 
     /// Create a Rust string from a *u8 buffer of the given length
     pub unsafe fn from_buf_len(buf: *u8, len: uint) -> ~str {
-        let mut v = Vec::with_capacity(len);
-        ptr::copy_memory(v.as_mut_ptr(), buf, len);
-        v.set_len(len);
-
-        assert!(is_utf8(v.as_slice()));
-        ::cast::transmute(v.move_iter().collect::<~[u8]>())
+        let v = Slice { data: buf, len: len };
+        let bytes: &[u8] = ::cast::transmute(v);
+        assert!(is_utf8(bytes));
+        let s: &str = ::cast::transmute(bytes);
+        s.to_owned()
     }
 
     #[lang="strdup_uniq"]
@@ -824,27 +820,23 @@ fn replace(&self, from: &str, to: &str) -> ~str {
     /// Copy a slice into a new owned str.
     #[inline]
     fn to_owned(&self) -> ~str {
-        let me = self.as_slice();
-        let len = me.len();
-        unsafe {
-            let mut v = Vec::with_capacity(len);
+        use slice::Vector;
 
-            ptr::copy_memory(v.as_mut_ptr(), me.as_ptr(), len);
-            v.set_len(len);
-            ::cast::transmute(v.move_iter().collect::<~[u8]>())
+        unsafe {
+            ::cast::transmute(self.as_slice().as_bytes().to_owned())
         }
     }
 
     /// Converts to a vector of `u16` encoded as UTF-16.
-    fn to_utf16(&self) -> ~[u16] {
+    fn to_utf16(&self) -> Vec<u16> {
         let me = self.as_slice();
-        let mut u = Vec::new();;
+        let mut u = Vec::new();
         for ch in me.chars() {
             let mut buf = [0u16, ..2];
             let n = ch.encode_utf16(buf /* as mut slice! */);
             u.push_all(buf.slice_to(n));
         }
-        u.move_iter().collect()
+        u
     }
 
     /// Given a string, make a new string with repeated copies of it.
@@ -1554,7 +1546,8 @@ fn test_subslice_offset() {
         assert_eq!(a.subslice_offset(c), 0);
 
         let string = "a\nb\nc";
-        let lines: ~[&str] = string.lines().collect();
+        let lines: Vec<&str> = string.lines().collect();
+        let lines = lines.as_slice();
         assert_eq!(string.subslice_offset(lines[0]), 0);
         assert_eq!(string.subslice_offset(lines[1]), 2);
         assert_eq!(string.subslice_offset(lines[2]), 4);
@@ -1617,13 +1610,13 @@ fn test_contains_char() {
     fn test_utf16() {
         let pairs =
             [("𐍅𐌿𐌻𐍆𐌹𐌻𐌰\n".to_owned(),
-              box [0xd800_u16, 0xdf45_u16, 0xd800_u16, 0xdf3f_u16,
+              vec![0xd800_u16, 0xdf45_u16, 0xd800_u16, 0xdf3f_u16,
                 0xd800_u16, 0xdf3b_u16, 0xd800_u16, 0xdf46_u16,
                 0xd800_u16, 0xdf39_u16, 0xd800_u16, 0xdf3b_u16,
                 0xd800_u16, 0xdf30_u16, 0x000a_u16]),
 
              ("𐐒𐑉𐐮𐑀𐐲𐑋 𐐏𐐲𐑍\n".to_owned(),
-              box [0xd801_u16, 0xdc12_u16, 0xd801_u16,
+              vec![0xd801_u16, 0xdc12_u16, 0xd801_u16,
                 0xdc49_u16, 0xd801_u16, 0xdc2e_u16, 0xd801_u16,
                 0xdc40_u16, 0xd801_u16, 0xdc32_u16, 0xd801_u16,
                 0xdc4b_u16, 0x0020_u16, 0xd801_u16, 0xdc0f_u16,
@@ -1631,7 +1624,7 @@ fn test_utf16() {
                 0x000a_u16]),
 
              ("𐌀𐌖𐌋𐌄𐌑𐌉·𐌌𐌄𐌕𐌄𐌋𐌉𐌑\n".to_owned(),
-              box [0xd800_u16, 0xdf00_u16, 0xd800_u16, 0xdf16_u16,
+              vec![0xd800_u16, 0xdf00_u16, 0xd800_u16, 0xdf16_u16,
                 0xd800_u16, 0xdf0b_u16, 0xd800_u16, 0xdf04_u16,
                 0xd800_u16, 0xdf11_u16, 0xd800_u16, 0xdf09_u16,
                 0x00b7_u16, 0xd800_u16, 0xdf0c_u16, 0xd800_u16,
@@ -1640,7 +1633,7 @@ fn test_utf16() {
                 0xdf09_u16, 0xd800_u16, 0xdf11_u16, 0x000a_u16 ]),
 
              ("𐒋𐒘𐒈𐒑𐒛𐒒 𐒕𐒓 𐒈𐒚𐒍 𐒏𐒜𐒒𐒖𐒆 𐒕𐒆\n".to_owned(),
-              box [0xd801_u16, 0xdc8b_u16, 0xd801_u16, 0xdc98_u16,
+              vec![0xd801_u16, 0xdc8b_u16, 0xd801_u16, 0xdc98_u16,
                 0xd801_u16, 0xdc88_u16, 0xd801_u16, 0xdc91_u16,
                 0xd801_u16, 0xdc9b_u16, 0xd801_u16, 0xdc92_u16,
                 0x0020_u16, 0xd801_u16, 0xdc95_u16, 0xd801_u16,
@@ -1653,18 +1646,18 @@ fn test_utf16() {
                 0x000a_u16 ]),
              // Issue #12318, even-numbered non-BMP planes
              ("\U00020000".to_owned(),
-              box [0xD840, 0xDC00])];
+              vec![0xD840, 0xDC00])];
 
         for p in pairs.iter() {
             let (s, u) = (*p).clone();
-            assert!(is_utf16(u));
+            assert!(is_utf16(u.as_slice()));
             assert_eq!(s.to_utf16(), u);
 
-            assert_eq!(from_utf16(u).unwrap(), s);
-            assert_eq!(from_utf16_lossy(u), s);
+            assert_eq!(from_utf16(u.as_slice()).unwrap(), s);
+            assert_eq!(from_utf16_lossy(u.as_slice()), s);
 
-            assert_eq!(from_utf16(s.to_utf16()).unwrap(), s);
-            assert_eq!(from_utf16(u).unwrap().to_utf16(), u);
+            assert_eq!(from_utf16(s.to_utf16().as_slice()).unwrap(), s);
+            assert_eq!(from_utf16(u.as_slice()).unwrap().to_utf16(), u);
         }
     }
 
@@ -1921,105 +1914,105 @@ fn test_char_indices_revator() {
     fn test_split_char_iterator() {
         let data = "\nMäry häd ä little lämb\nLittle lämb\n";
 
-        let split: ~[&str] = data.split(' ').collect();
-        assert_eq!( split, box ["\nMäry", "häd", "ä", "little", "lämb\nLittle", "lämb\n"]);
+        let split: Vec<&str> = data.split(' ').collect();
+        assert_eq!( split, vec!["\nMäry", "häd", "ä", "little", "lämb\nLittle", "lämb\n"]);
 
-        let mut rsplit: ~[&str] = data.split(' ').rev().collect();
+        let mut rsplit: Vec<&str> = data.split(' ').rev().collect();
         rsplit.reverse();
-        assert_eq!(rsplit, box ["\nMäry", "häd", "ä", "little", "lämb\nLittle", "lämb\n"]);
+        assert_eq!(rsplit, vec!["\nMäry", "häd", "ä", "little", "lämb\nLittle", "lämb\n"]);
 
-        let split: ~[&str] = data.split(|c: char| c == ' ').collect();
-        assert_eq!( split, box ["\nMäry", "häd", "ä", "little", "lämb\nLittle", "lämb\n"]);
+        let split: Vec<&str> = data.split(|c: char| c == ' ').collect();
+        assert_eq!( split, vec!["\nMäry", "häd", "ä", "little", "lämb\nLittle", "lämb\n"]);
 
-        let mut rsplit: ~[&str] = data.split(|c: char| c == ' ').rev().collect();
+        let mut rsplit: Vec<&str> = data.split(|c: char| c == ' ').rev().collect();
         rsplit.reverse();
-        assert_eq!(rsplit, box ["\nMäry", "häd", "ä", "little", "lämb\nLittle", "lämb\n"]);
+        assert_eq!(rsplit, vec!["\nMäry", "häd", "ä", "little", "lämb\nLittle", "lämb\n"]);
 
         // Unicode
-        let split: ~[&str] = data.split('ä').collect();
-        assert_eq!( split, box ["\nM", "ry h", "d ", " little l", "mb\nLittle l", "mb\n"]);
+        let split: Vec<&str> = data.split('ä').collect();
+        assert_eq!( split, vec!["\nM", "ry h", "d ", " little l", "mb\nLittle l", "mb\n"]);
 
-        let mut rsplit: ~[&str] = data.split('ä').rev().collect();
+        let mut rsplit: Vec<&str> = data.split('ä').rev().collect();
         rsplit.reverse();
-        assert_eq!(rsplit, box ["\nM", "ry h", "d ", " little l", "mb\nLittle l", "mb\n"]);
+        assert_eq!(rsplit, vec!["\nM", "ry h", "d ", " little l", "mb\nLittle l", "mb\n"]);
 
-        let split: ~[&str] = data.split(|c: char| c == 'ä').collect();
-        assert_eq!( split, box ["\nM", "ry h", "d ", " little l", "mb\nLittle l", "mb\n"]);
+        let split: Vec<&str> = data.split(|c: char| c == 'ä').collect();
+        assert_eq!( split, vec!["\nM", "ry h", "d ", " little l", "mb\nLittle l", "mb\n"]);
 
-        let mut rsplit: ~[&str] = data.split(|c: char| c == 'ä').rev().collect();
+        let mut rsplit: Vec<&str> = data.split(|c: char| c == 'ä').rev().collect();
         rsplit.reverse();
-        assert_eq!(rsplit, box ["\nM", "ry h", "d ", " little l", "mb\nLittle l", "mb\n"]);
+        assert_eq!(rsplit, vec!["\nM", "ry h", "d ", " little l", "mb\nLittle l", "mb\n"]);
     }
 
     #[test]
     fn test_splitn_char_iterator() {
         let data = "\nMäry häd ä little lämb\nLittle lämb\n";
 
-        let split: ~[&str] = data.splitn(' ', 3).collect();
-        assert_eq!(split, box ["\nMäry", "häd", "ä", "little lämb\nLittle lämb\n"]);
+        let split: Vec<&str> = data.splitn(' ', 3).collect();
+        assert_eq!(split, vec!["\nMäry", "häd", "ä", "little lämb\nLittle lämb\n"]);
 
-        let split: ~[&str] = data.splitn(|c: char| c == ' ', 3).collect();
-        assert_eq!(split, box ["\nMäry", "häd", "ä", "little lämb\nLittle lämb\n"]);
+        let split: Vec<&str> = data.splitn(|c: char| c == ' ', 3).collect();
+        assert_eq!(split, vec!["\nMäry", "häd", "ä", "little lämb\nLittle lämb\n"]);
 
         // Unicode
-        let split: ~[&str] = data.splitn('ä', 3).collect();
-        assert_eq!(split, box ["\nM", "ry h", "d ", " little lämb\nLittle lämb\n"]);
+        let split: Vec<&str> = data.splitn('ä', 3).collect();
+        assert_eq!(split, vec!["\nM", "ry h", "d ", " little lämb\nLittle lämb\n"]);
 
-        let split: ~[&str] = data.splitn(|c: char| c == 'ä', 3).collect();
-        assert_eq!(split, box ["\nM", "ry h", "d ", " little lämb\nLittle lämb\n"]);
+        let split: Vec<&str> = data.splitn(|c: char| c == 'ä', 3).collect();
+        assert_eq!(split, vec!["\nM", "ry h", "d ", " little lämb\nLittle lämb\n"]);
     }
 
     #[test]
     fn test_rsplitn_char_iterator() {
         let data = "\nMäry häd ä little lämb\nLittle lämb\n";
 
-        let mut split: ~[&str] = data.rsplitn(' ', 3).collect();
+        let mut split: Vec<&str> = data.rsplitn(' ', 3).collect();
         split.reverse();
-        assert_eq!(split, box ["\nMäry häd ä", "little", "lämb\nLittle", "lämb\n"]);
+        assert_eq!(split, vec!["\nMäry häd ä", "little", "lämb\nLittle", "lämb\n"]);
 
-        let mut split: ~[&str] = data.rsplitn(|c: char| c == ' ', 3).collect();
+        let mut split: Vec<&str> = data.rsplitn(|c: char| c == ' ', 3).collect();
         split.reverse();
-        assert_eq!(split, box ["\nMäry häd ä", "little", "lämb\nLittle", "lämb\n"]);
+        assert_eq!(split, vec!["\nMäry häd ä", "little", "lämb\nLittle", "lämb\n"]);
 
         // Unicode
-        let mut split: ~[&str] = data.rsplitn('ä', 3).collect();
+        let mut split: Vec<&str> = data.rsplitn('ä', 3).collect();
         split.reverse();
-        assert_eq!(split, box ["\nMäry häd ", " little l", "mb\nLittle l", "mb\n"]);
+        assert_eq!(split, vec!["\nMäry häd ", " little l", "mb\nLittle l", "mb\n"]);
 
-        let mut split: ~[&str] = data.rsplitn(|c: char| c == 'ä', 3).collect();
+        let mut split: Vec<&str> = data.rsplitn(|c: char| c == 'ä', 3).collect();
         split.reverse();
-        assert_eq!(split, box ["\nMäry häd ", " little l", "mb\nLittle l", "mb\n"]);
+        assert_eq!(split, vec!["\nMäry häd ", " little l", "mb\nLittle l", "mb\n"]);
     }
 
     #[test]
     fn test_split_char_iterator_no_trailing() {
         let data = "\nMäry häd ä little lämb\nLittle lämb\n";
 
-        let split: ~[&str] = data.split('\n').collect();
-        assert_eq!(split, box ["", "Märy häd ä little lämb", "Little lämb", ""]);
+        let split: Vec<&str> = data.split('\n').collect();
+        assert_eq!(split, vec!["", "Märy häd ä little lämb", "Little lämb", ""]);
 
-        let split: ~[&str] = data.split_terminator('\n').collect();
-        assert_eq!(split, box ["", "Märy häd ä little lämb", "Little lämb"]);
+        let split: Vec<&str> = data.split_terminator('\n').collect();
+        assert_eq!(split, vec!["", "Märy häd ä little lämb", "Little lämb"]);
     }
 
     #[test]
     fn test_rev_split_char_iterator_no_trailing() {
         let data = "\nMäry häd ä little lämb\nLittle lämb\n";
 
-        let mut split: ~[&str] = data.split('\n').rev().collect();
+        let mut split: Vec<&str> = data.split('\n').rev().collect();
         split.reverse();
-        assert_eq!(split, box ["", "Märy häd ä little lämb", "Little lämb", ""]);
+        assert_eq!(split, vec!["", "Märy häd ä little lämb", "Little lämb", ""]);
 
-        let mut split: ~[&str] = data.split_terminator('\n').rev().collect();
+        let mut split: Vec<&str> = data.split_terminator('\n').rev().collect();
         split.reverse();
-        assert_eq!(split, box ["", "Märy häd ä little lämb", "Little lämb"]);
+        assert_eq!(split, vec!["", "Märy häd ä little lämb", "Little lämb"]);
     }
 
     #[test]
     fn test_words() {
         let data = "\n \tMäry   häd\tä  little lämb\nLittle lämb\n";
-        let words: ~[&str] = data.words().collect();
-        assert_eq!(words, box ["Märy", "häd", "ä", "little", "lämb", "Little", "lämb"])
+        let words: Vec<&str> = data.words().collect();
+        assert_eq!(words, vec!["Märy", "häd", "ä", "little", "lämb", "Little", "lämb"])
     }
 
     #[test]
@@ -2053,34 +2046,34 @@ fn test_nfkd_chars() {
     #[test]
     fn test_lines() {
         let data = "\nMäry häd ä little lämb\n\nLittle lämb\n";
-        let lines: ~[&str] = data.lines().collect();
-        assert_eq!(lines, box ["", "Märy häd ä little lämb", "", "Little lämb"]);
+        let lines: Vec<&str> = data.lines().collect();
+        assert_eq!(lines, vec!["", "Märy häd ä little lämb", "", "Little lämb"]);
 
         let data = "\nMäry häd ä little lämb\n\nLittle lämb"; // no trailing \n
-        let lines: ~[&str] = data.lines().collect();
-        assert_eq!(lines, box ["", "Märy häd ä little lämb", "", "Little lämb"]);
+        let lines: Vec<&str> = data.lines().collect();
+        assert_eq!(lines, vec!["", "Märy häd ä little lämb", "", "Little lämb"]);
     }
 
     #[test]
     fn test_split_strator() {
-        fn t<'a>(s: &str, sep: &'a str, u: ~[&str]) {
-            let v: ~[&str] = s.split_str(sep).collect();
-            assert_eq!(v, u);
+        fn t(s: &str, sep: &str, u: &[&str]) {
+            let v: Vec<&str> = s.split_str(sep).collect();
+            assert_eq!(v.as_slice(), u.as_slice());
         }
-        t("--1233345--", "12345", box ["--1233345--"]);
-        t("abc::hello::there", "::", box ["abc", "hello", "there"]);
-        t("::hello::there", "::", box ["", "hello", "there"]);
-        t("hello::there::", "::", box ["hello", "there", ""]);
-        t("::hello::there::", "::", box ["", "hello", "there", ""]);
-        t("ประเทศไทย中华Việt Nam", "中华", box ["ประเทศไทย", "Việt Nam"]);
-        t("zzXXXzzYYYzz", "zz", box ["", "XXX", "YYY", ""]);
-        t("zzXXXzYYYz", "XXX", box ["zz", "zYYYz"]);
-        t(".XXX.YYY.", ".", box ["", "XXX", "YYY", ""]);
-        t("", ".", box [""]);
-        t("zz", "zz", box ["",""]);
-        t("ok", "z", box ["ok"]);
-        t("zzz", "zz", box ["","z"]);
-        t("zzzzz", "zz", box ["","","z"]);
+        t("--1233345--", "12345", ["--1233345--"]);
+        t("abc::hello::there", "::", ["abc", "hello", "there"]);
+        t("::hello::there", "::", ["", "hello", "there"]);
+        t("hello::there::", "::", ["hello", "there", ""]);
+        t("::hello::there::", "::", ["", "hello", "there", ""]);
+        t("ประเทศไทย中华Việt Nam", "中华", ["ประเทศไทย", "Việt Nam"]);
+        t("zzXXXzzYYYzz", "zz", ["", "XXX", "YYY", ""]);
+        t("zzXXXzYYYz", "XXX", ["zz", "zYYYz"]);
+        t(".XXX.YYY.", ".", ["", "XXX", "YYY", ""]);
+        t("", ".", [""]);
+        t("zz", "zz", ["",""]);
+        t("ok", "z", ["ok"]);
+        t("zzz", "zz", ["","z"]);
+        t("zzzzz", "zz", ["","","z"]);
     }
 
     #[test]
index ad703b8054b0bcf6e1c25201527e41ed2d41ab6b..8e05b2f527d0830903ad9dead6ec053099906be0 100644 (file)
@@ -19,7 +19,7 @@
 use iter::{Extendable, FromIterator, Iterator, range};
 use option::{None, Option, Some};
 use ptr::RawPtr;
-use slice::{OwnedVector, Vector};
+use slice::{OwnedVector, Vector, CloneableVector};
 use str::{OwnedStr, Str, StrSlice, StrAllocating};
 use str;
 use vec::Vec;
@@ -273,11 +273,8 @@ fn as_slice<'a>(&'a self) -> &'a str {
 impl StrAllocating for StrBuf {
     #[inline]
     fn into_owned(self) -> ~str {
-        let StrBuf {
-            vec: vec
-        } = self;
         unsafe {
-            cast::transmute::<~[u8],~str>(vec.move_iter().collect())
+            cast::transmute(self.vec.as_slice().to_owned())
         }
     }
 
index d277c514e444f4e4591572426379b78571dec465..676c836c459d72458a6abd468ea213dda1ad628c 100644 (file)
@@ -69,14 +69,14 @@ pub fn new2(data: T) -> (UnsafeArc<T>, UnsafeArc<T>) {
 
     /// As new(), but returns a vector of as many pre-cloned handles as
     /// requested.
-    pub fn newN(data: T, num_handles: uint) -> ~[UnsafeArc<T>] {
+    pub fn newN(data: T, num_handles: uint) -> Vec<UnsafeArc<T>> {
         unsafe {
             if num_handles == 0 {
-                box [] // need to free data here
+                vec![] // need to free data here
             } else {
                 let ptr = new_inner(data, num_handles);
                 let v = Vec::from_fn(num_handles, |_| UnsafeArc { data: ptr });
-                v.move_iter().collect()
+                v
             }
         }
     }
index d06062f02ac8adf4c22a7ca2f6484097e54635fa..8dfd691e6ffdc09f500af0e84d4d8c26a5aad01f 100644 (file)
@@ -407,7 +407,7 @@ mod tests {
     use rand::Rng;
     use sync::atomics::{AtomicBool, INIT_ATOMIC_BOOL, SeqCst,
                         AtomicUint, INIT_ATOMIC_UINT};
-    use slice;
+    use vec;
 
     #[test]
     fn smoke() {
@@ -603,7 +603,7 @@ fn no_starvation() {
         let mut pool = BufferPool::<(int, uint)>::new();
         let (mut w, s) = pool.deque();
 
-        let (threads, hits) = slice::unzip(range(0, NTHREADS).map(|_| {
+        let (threads, hits) = vec::unzip(range(0, NTHREADS).map(|_| {
             let s = s.clone();
             let unique_box = box AtomicUint::new(0);
             let thread_box = unsafe {
index 68f0aaab05b1b034075d23b691fb6911632ea318..e2a9f6a5c4821c481ace94816a41577fcdf4c6fa 100644 (file)
 
 use c_str::ToCStr;
 use cast;
+use iter::Iterator;
 use ops::*;
 use option::*;
 use os;
 use path::GenericPath;
 use path;
 use result::*;
+use slice::{Vector,OwnedVector};
 use str;
+use vec::Vec;
 
 pub struct DynamicLibrary { handle: *u8}
 
@@ -73,8 +76,10 @@ pub fn add_search_path(path: &path::Path) {
             ("LD_LIBRARY_PATH", ':' as u8)
         };
         let newenv = os::getenv_as_bytes(envvar).unwrap_or(box []);
-        let newenv = newenv + &[sep] + path.as_vec();
-        os::setenv(envvar, str::from_utf8(newenv).unwrap());
+        let mut newenv = newenv.move_iter().collect::<Vec<_>>();
+        newenv.push_all(&[sep]);
+        newenv.push_all(path.as_vec());
+        os::setenv(envvar, str::from_utf8(newenv.as_slice()).unwrap());
     }
 
     /// Access the value at the symbol of the dynamic library
index af146b96e505a1c3128baed38c241ec21b7c6435..da01da26709598e95df0ca54dad5ed4fc0964504 100644 (file)
 use mem;
 use num;
 use num::{CheckedMul, CheckedAdd};
-use ops::Drop;
+use ops::{Add, Drop};
 use option::{None, Option, Some, Expect};
 use ptr::RawPtr;
 use ptr;
 use rt::global_heap::{malloc_raw, realloc_raw};
 use raw::Slice;
+use RawVec = raw::Vec;
 use slice::{ImmutableEqVector, ImmutableVector, Items, MutItems, MutableVector};
 use slice::{MutableTotalOrdVector, OwnedVector, Vector};
 use slice::{MutableVectorAllocating};
@@ -1370,6 +1371,16 @@ fn as_slice<'a>(&'a self) -> &'a [T] {
     }
 }
 
+impl<T: Clone, V: Vector<T>> Add<V, Vec<T>> for Vec<T> {
+    #[inline]
+    fn add(&self, rhs: &V) -> Vec<T> {
+        let mut res = Vec::with_capacity(self.len() + rhs.as_slice().len());
+        res.push_all(self.as_slice());
+        res.push_all(rhs.as_slice());
+        res
+    }
+}
+
 #[unsafe_destructor]
 impl<T> Drop for Vec<T> {
     fn drop(&mut self) {
@@ -1436,10 +1447,94 @@ fn drop(&mut self) {
     }
 }
 
+/**
+ * Convert an iterator of pairs into a pair of vectors.
+ *
+ * Returns a tuple containing two vectors where the i-th element of the first
+ * vector contains the first element of the i-th tuple of the input iterator,
+ * and the i-th element of the second vector contains the second element
+ * of the i-th tuple of the input iterator.
+ */
+pub fn unzip<T, U, V: Iterator<(T, U)>>(mut iter: V) -> (Vec<T>, Vec<U>) {
+    let (lo, _) = iter.size_hint();
+    let mut ts = Vec::with_capacity(lo);
+    let mut us = Vec::with_capacity(lo);
+    for (t, u) in iter {
+        ts.push(t);
+        us.push(u);
+    }
+    (ts, us)
+}
+
+/// Mechanism to convert from a `Vec<T>` to a `[T]`.
+///
+/// In a post-DST world this will be used to convert to any `Ptr<[T]>`.
+///
+/// This could be implemented on more types than just pointers to vectors, but
+/// the recommended approach for those types is to implement `FromIterator`.
+// FIXME(#12938): Update doc comment when DST lands
+pub trait FromVec<T> {
+    /// Convert a `Vec<T>` into the receiver type.
+    fn from_vec(v: Vec<T>) -> Self;
+}
+
+impl<T> FromVec<T> for ~[T] {
+    fn from_vec(mut v: Vec<T>) -> ~[T] {
+        let len = v.len();
+        let data_size = len.checked_mul(&mem::size_of::<T>());
+        let data_size = data_size.expect("overflow in from_vec()");
+        let size = mem::size_of::<RawVec<()>>().checked_add(&data_size);
+        let size = size.expect("overflow in from_vec()");
+
+        // In a post-DST world, we can attempt to reuse the Vec allocation by calling
+        // shrink_to_fit() on it. That may involve a reallocation+memcpy, but that's no
+        // diffrent than what we're doing manually here.
+
+        let vp = v.as_mut_ptr();
+
+        unsafe {
+            let ret = malloc_raw(size) as *mut RawVec<()>;
+
+            (*ret).fill = len * mem::nonzero_size_of::<T>();
+            (*ret).alloc = len * mem::nonzero_size_of::<T>();
+
+            ptr::copy_nonoverlapping_memory(&mut (*ret).data as *mut _ as *mut u8,
+                                            vp as *u8, data_size);
+
+            // we've transferred ownership of the contents from v, but we can't drop it
+            // as it still needs to free its own allocation.
+            v.set_len(0);
+
+            transmute(ret)
+        }
+    }
+}
+
+/// Unsafe operations
+pub mod raw {
+    use super::Vec;
+    use ptr;
+
+    /// Constructs a vector from an unsafe pointer to a buffer.
+    ///
+    /// The elements of the buffer are copied into the vector without cloning,
+    /// as if `ptr::read()` were called on them.
+    #[inline]
+    pub unsafe fn from_buf<T>(ptr: *T, elts: uint) -> Vec<T> {
+        let mut dst = Vec::with_capacity(elts);
+        dst.set_len(elts);
+        ptr::copy_nonoverlapping_memory(dst.as_mut_ptr(), ptr, elts);
+        dst
+    }
+}
+
+
 #[cfg(test)]
 mod tests {
     use prelude::*;
     use mem::size_of;
+    use kinds::marker;
+    use super::{unzip, raw, FromVec};
 
     #[test]
     fn test_small_vec_struct() {
@@ -1649,4 +1744,75 @@ fn zero_sized_values() {
         unsafe { v.set_len(0); }
         assert_eq!(v.mut_iter().len(), 0);
     }
+
+    #[test]
+    fn test_partition() {
+        assert_eq!(vec![].partition(|x: &int| *x < 3), (vec![], vec![]));
+        assert_eq!(vec![1, 2, 3].partition(|x: &int| *x < 4), (vec![1, 2, 3], vec![]));
+        assert_eq!(vec![1, 2, 3].partition(|x: &int| *x < 2), (vec![1], vec![2, 3]));
+        assert_eq!(vec![1, 2, 3].partition(|x: &int| *x < 0), (vec![], vec![1, 2, 3]));
+    }
+
+    #[test]
+    fn test_partitioned() {
+        assert_eq!(vec![].partitioned(|x: &int| *x < 3), (vec![], vec![]))
+        assert_eq!(vec![1, 2, 3].partitioned(|x: &int| *x < 4), (vec![1, 2, 3], vec![]));
+        assert_eq!(vec![1, 2, 3].partitioned(|x: &int| *x < 2), (vec![1], vec![2, 3]));
+        assert_eq!(vec![1, 2, 3].partitioned(|x: &int| *x < 0), (vec![], vec![1, 2, 3]));
+    }
+
+    #[test]
+    fn test_zip_unzip() {
+        let z1 = vec![(1, 4), (2, 5), (3, 6)];
+
+        let (left, right) = unzip(z1.iter().map(|&x| x));
+
+        let (left, right) = (left.as_slice(), right.as_slice());
+        assert_eq!((1, 4), (left[0], right[0]));
+        assert_eq!((2, 5), (left[1], right[1]));
+        assert_eq!((3, 6), (left[2], right[2]));
+    }
+
+    #[test]
+    fn test_unsafe_ptrs() {
+        unsafe {
+            // Test on-stack copy-from-buf.
+            let a = [1, 2, 3];
+            let ptr = a.as_ptr();
+            let b = raw::from_buf(ptr, 3u);
+            assert_eq!(b, vec![1, 2, 3]);
+
+            // Test on-heap copy-from-buf.
+            let c = box [1, 2, 3, 4, 5];
+            let ptr = c.as_ptr();
+            let d = raw::from_buf(ptr, 5u);
+            assert_eq!(d, vec![1, 2, 3, 4, 5]);
+        }
+    }
+
+    #[test]
+    fn test_from_vec() {
+        let a = vec![1u, 2, 3];
+        let b: ~[uint] = FromVec::from_vec(a);
+        assert_eq!(b.as_slice(), &[1u, 2, 3]);
+
+        let a = vec![];
+        let b: ~[u8] = FromVec::from_vec(a);
+        assert_eq!(b.as_slice(), &[]);
+
+        let a = vec!["one".to_owned(), "two".to_owned()];
+        let b: ~[~str] = FromVec::from_vec(a);
+        assert_eq!(b.as_slice(), &["one".to_owned(), "two".to_owned()]);
+
+        struct Foo {
+            x: uint,
+            nocopy: marker::NoCopy
+        }
+
+        let a = vec![Foo{x: 42, nocopy: marker::NoCopy}, Foo{x: 84, nocopy: marker::NoCopy}];
+        let b: ~[Foo] = FromVec::from_vec(a);
+        assert_eq!(b.len(), 2);
+        assert_eq!(b[0].x, 42);
+        assert_eq!(b[1].x, 84);
+    }
 }
diff --git a/src/test/auxiliary/issue-11680.rs b/src/test/auxiliary/issue-11680.rs
new file mode 100644 (file)
index 0000000..249a1ba
--- /dev/null
@@ -0,0 +1,19 @@
+// Copyright 2014 The Rust Project Developers. See the COPYRIGHT
+// file at the top-level directory of this distribution and at
+// http://rust-lang.org/COPYRIGHT.
+//
+// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
+// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
+// <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your
+// option. This file may not be copied, modified, or distributed
+// except according to those terms.
+
+enum Foo {
+    Bar(int)
+}
+
+pub mod test {
+    enum Foo {
+        Bar(int)
+    }
+}
index 4405245b9a0e1279e72add3e5bb5d55cc47598e2..6a8a56b4f1f8a2a4ce036226ef5e37775b7bdc20 100644 (file)
@@ -90,6 +90,7 @@ fn vector<M: MutableMap<uint, uint>>(map: &mut M, n_keys: uint, dist: &[uint]) {
 
 fn main() {
     let args = os::args();
+    let args = args.as_slice();
     let n_keys = {
         if args.len() == 2 {
             from_str::<uint>(args[1]).unwrap()
index 96f3c6814ab931f6170e1a4b77fb29cd606c8723..b1181a3c17c5ad24d8a3666e45043236fbcf8229 100644 (file)
@@ -155,6 +155,7 @@ fn empty_results() -> Results {
 
 fn main() {
     let args = os::args();
+    let args = args.as_slice();
     let num_keys = {
         if args.len() == 2 {
             from_str::<uint>(args[1]).unwrap()
index 902f2c72409ef8b8ceda31ecb8d6eb764ef491ae..7e54198bd3961655e4313fbfe103b942fc55f8c4 100644 (file)
@@ -24,7 +24,7 @@
 use std::io::File;
 
 macro_rules! bench (
-    ($argv:expr, $id:ident) => (maybe_run_test($argv, stringify!($id).to_owned(), $id))
+    ($argv:expr, $id:ident) => (maybe_run_test($argv.as_slice(), stringify!($id).to_owned(), $id))
 )
 
 fn main() {
index 044c4b07d443e5a896e7a65e98fa11cd5c634e7a..bbe6b6c23f0f97082a618803abc7d7a00887b997 100644 (file)
@@ -61,6 +61,7 @@ fn run_pair(n: uint) {
 fn main() {
 
     let args = os::args();
+    let args = args.as_slice();
     let n = if args.len() == 3 {
         from_str::<uint>(args[1]).unwrap()
     } else {
index 1a7302207d968857a30e34ece9624c669915fe82..29cee668389f873d89d557508625e63f43b6d265 100644 (file)
@@ -31,6 +31,7 @@ fn parfib(n: uint) -> uint {
 fn main() {
 
     let args = os::args();
+    let args = args.as_slice();
     let n = if args.len() == 2 {
         from_str::<uint>(args[1]).unwrap()
     } else {
index 4f07660779b2692c8c5a3c9647cda6017f221fd2..48d4a41c1a39aae1f9d7032ffc8d990bccd3a7f4 100644 (file)
@@ -28,6 +28,7 @@ fn start(argc: int, argv: **u8) -> int {
 fn main() {
 
     let args = os::args();
+    let args = args.as_slice();
     let n = if args.len() == 2 {
         from_str::<uint>(args[1]).unwrap()
     } else {
index 49184e188ebb61fbcd08efb0e93a91f3028c18b9..8914c5b327ecc6f843699269ca576a4684a4e31c 100644 (file)
@@ -40,6 +40,7 @@ fn bottom_up_tree<'r>(arena: &'r TypedArena<Tree<'r>>, item: int, depth: int)
 
 fn main() {
     let args = std::os::args();
+    let args = args.as_slice();
     let n = if std::os::getenv("RUST_BENCH").is_some() {
         17
     } else if args.len() <= 1u {
index 7587a21a9df0d0d20aec525d0a18bea7e6b2293f..07e5b08c37ccb996ce33065e420968f728359b2b 100644 (file)
@@ -194,7 +194,7 @@ fn main() {
     let nn = if std::os::getenv("RUST_BENCH").is_some() {
         200000
     } else {
-        std::os::args().get(1).and_then(|arg| from_str(*arg)).unwrap_or(600)
+        std::os::args().as_slice().get(1).and_then(|arg| from_str(*arg)).unwrap_or(600)
     };
 
     print_complements();
index 4bea355472de17838940fe727bf6c56614d3fcbe..3525b90d3f681c2fddbefa8aefc5aed08cd847a2 100644 (file)
@@ -53,7 +53,7 @@ fn fannkuch(n: uint, i: uint) -> (int, int) {
 }
 
 fn main() {
-    let n = std::os::args().get(1).and_then(|arg| from_str(*arg)).unwrap_or(2u);
+    let n = std::os::args().as_slice().get(1).and_then(|arg| from_str(*arg)).unwrap_or(2u);
 
     let (tx, rx) = channel();
     for i in range(0, n) {
index 01b75fa422f924474eb9a2e5bdfcb6923e740bc8..3f8d3275b64f9456c33312b2da515b2b2e0abc3a 100644 (file)
@@ -177,6 +177,7 @@ fn make(&mut self, n: uint) -> IoResult<()> {
 
 fn main() {
     let args = os::args();
+    let args = args.as_slice();
     let n = if args.len() > 1 {
         from_str::<uint>(args[1]).unwrap()
     } else {
index 76ac8407d60c57a77fb1332d2334445e6f219c40..c526ef54caff2277c9af923bca84ec485929ca07 100644 (file)
@@ -74,6 +74,7 @@ fn make_fasta<W: Writer, I: Iterator<u8>>(
 
 fn run<W: Writer>(writer: &mut W) {
     let args = os::args();
+    let args = args.as_slice();
     let n = if os::getenv("RUST_BENCH").is_some() {
         25000000
     } else if args.len() <= 1u {
index 659270b555427773ea941a367800e1ca2a0a04a8..e2bcc55d139828ca5da5186c4f25b242ce27a17a 100644 (file)
@@ -72,7 +72,7 @@ fn sortKV(mut orig: Vec<(Vec<u8> ,f64)> ) -> Vec<(Vec<u8> ,f64)> {
 
 // given a map, search for the frequency of a pattern
 fn find(mm: &HashMap<Vec<u8> , uint>, key: ~str) -> uint {
-   let key = key.into_ascii().to_lower().into_str();
+   let key = key.into_ascii().as_slice().to_lower().into_str();
    match mm.find_equiv(&key.as_bytes()) {
       option::None      => { return 0u; }
       option::Some(&num) => { return num; }
index e7b4d0a5c1c6d346bb5e92a0f5c4e48fe1e2f69e..ee715aecec4fcb9ff1a76ed6658dfdbf372b3bf9 100644 (file)
@@ -65,6 +65,7 @@ fn mandelbrot<W: io::Writer>(w: uint, mut out: W) -> io::IoResult<()> {
 
 fn main() {
     let args = std::os::args();
+    let args = args.as_slice();
     let res = if args.len() < 2 {
         println!("Test mode: do not dump the image because it's not utf8, \
                   which interferes with the test runner.");
index 6e86f5205f017a84ad06d44b0609032763214737..cb46c542f5bc84c03af85f141d9877f5226b301c 100644 (file)
@@ -190,7 +190,7 @@ fn to_utf8(raw_sol: &List<u64>) -> ~str {
             }
         }
     }
-    std::str::from_utf8_owned(sol.move_iter().collect()).unwrap()
+    std::str::from_utf8(sol.as_slice()).unwrap().to_owned()
 }
 
 // Prints a solution in ~str form.
@@ -270,6 +270,7 @@ fn search(
 
 fn main () {
     let args = std::os::args();
+    let args = args.as_slice();
     let stop_after = if args.len() <= 1 {
         2098
     } else {
index 71cd176a836ff86c0e9b941088f1afb43de3054b..49356e6e6458ebaf9a4444910c449ca2c28b6b96 100644 (file)
@@ -88,6 +88,7 @@ fn pidigits(n: int) {
 
 fn main() {
     let args = std::os::args();
+    let args = args.as_slice();
     let n = if args.len() < 2 {
         512
     } else {
index e63c78d50af72272a88eba230d5ae86d3e8ebd6e..70a0e7a957c6b0aa9aa68f5c425f7eed374e7e45 100644 (file)
@@ -94,6 +94,7 @@ fn mult_AtAv(v: Arc<RWLock<Vec<f64>>>, out: Arc<RWLock<Vec<f64>>>,
 
 fn main() {
     let args = os::args();
+    let args = args.as_slice();
     let n = if os::getenv("RUST_BENCH").is_some() {
         5500
     } else if args.len() < 2 {
index a845481f0e0283c3606ab947a4d0a3d828f97e59..60485f40ba4e0f064e268b0fe8420082d8c2e151 100644 (file)
@@ -35,6 +35,7 @@ fn roundtrip(id: int, tx: Sender<int>, rx: Receiver<int>) {
 
 fn main() {
     let args = std::os::args();
+    let args = args.as_slice();
     let token = if std::os::getenv("RUST_BENCH").is_some() {
         2000000
     } else {
diff --git a/src/test/compile-fail/issue-11493.rs b/src/test/compile-fail/issue-11493.rs
new file mode 100644 (file)
index 0000000..af42a93
--- /dev/null
@@ -0,0 +1,16 @@
+// Copyright 2014 The Rust Project Developers. See the COPYRIGHT
+// file at the top-level directory of this distribution and at
+// http://rust-lang.org/COPYRIGHT.
+//
+// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
+// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
+// <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your
+// option. This file may not be copied, modified, or distributed
+// except according to those terms.
+
+// This file must never have a trailing newline
+
+fn main() {
+    let x = Some(3);
+    let y = x.as_ref().unwrap_or(&5); //~ ERROR: borrowed value does not live long enough
+}
\ No newline at end of file
diff --git a/src/test/compile-fail/issue-11680.rs b/src/test/compile-fail/issue-11680.rs
new file mode 100644 (file)
index 0000000..9c9663a
--- /dev/null
@@ -0,0 +1,21 @@
+// Copyright 2014 The Rust Project Developers. See the COPYRIGHT
+// file at the top-level directory of this distribution and at
+// http://rust-lang.org/COPYRIGHT.
+//
+// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
+// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
+// <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your
+// option. This file may not be copied, modified, or distributed
+// except according to those terms.
+
+// aux-build:issue-11680.rs
+
+extern crate other = "issue-11680";
+
+fn main() {
+    let _b = other::Bar(1);
+    //~^ ERROR: variant `Bar` is private
+
+    let _b = other::test::Bar(1);
+    //~^ ERROR: variant `Bar` is private
+}
index b372720467e3f88ccb07e301d6394b8a751beb05..671fecc4e22e7581d57ffca4a3f463b86c56dbfe 100644 (file)
@@ -28,6 +28,13 @@ fn main() {
     match 30 {
         mut x => {} //~ ERROR: variable does not need to be mutable
     }
+    match (30, 2) {
+      (mut x, 1) | //~ ERROR: variable does not need to be mutable
+      (mut x, 2) |
+      (mut x, 3) => {
+      }
+      _ => {}
+    }
 
     let x = |mut y: int| 10; //~ ERROR: variable does not need to be mutable
     fn what(mut foo: int) {} //~ ERROR: variable does not need to be mutable
@@ -50,6 +57,15 @@ fn what(mut foo: int) {} //~ ERROR: variable does not need to be mutable
         }
     }
 
+    match (30, 2) {
+      (mut x, 1) |
+      (mut x, 2) |
+      (mut x, 3) => {
+        x = 21
+      }
+      _ => {}
+    }
+
     let x = |mut y: int| y = 32;
     fn nothing(mut foo: int) { foo = 37; }
 
index d54c04b77b0d8fbc9a5d1848de53ca6ac74998c0..a08d6bb0bf87fdb45ea3c309e80a0be2305225bd 100644 (file)
@@ -36,8 +36,8 @@ fn random_char() -> char {
 
 fn main() {
     let args = os::args();
-    let rustc = args[1].as_slice();
-    let tmpdir = Path::new(args[2].as_slice());
+    let rustc = args.get(1).as_slice();
+    let tmpdir = Path::new(args.get(2).as_slice());
 
     let main_file = tmpdir.join("unicode_input_multiple_files_main.rs");
     let main_file_str = main_file.as_str().unwrap();
index 5f4af50753ec7c04afc4251f7964bd8ec8191ddf..13f141008b7929775a1a979a8dace1317896b2fd 100644 (file)
@@ -35,8 +35,8 @@ fn random_char() -> char {
 
 fn main() {
     let args = os::args();
-    let rustc = args[1].as_slice();
-    let tmpdir = Path::new(args[2].as_slice());
+    let rustc = args.get(1).as_slice();
+    let tmpdir = Path::new(args.get(2).as_slice());
 
     let main_file = tmpdir.join("span_main.rs");
     let main_file_str = main_file.as_str().unwrap();
index 0277cb35f528635b64f1ae0aa2c3c489c1339096..989453d8570d169ae14b1dafb3d966dd479261c1 100644 (file)
@@ -100,6 +100,7 @@ fn runtest(me: &str) {
 
 fn main() {
     let args = os::args();
+    let args = args.as_slice();
     if args.len() >= 2 && args[1].as_slice() == "fail" {
         foo();
     } else if args.len() >= 2 && args[1].as_slice() == "double-fail" {
index 76d73fd5b8705874a88652906215a51ab064c8e0..c409852c6736cd63022a2cf9bbe2d4eb8266fede 100644 (file)
@@ -24,6 +24,7 @@
 
 pub fn main() {
     let args = os::args();
+    let args = args.as_slice();
 
     // Here, the rvalue `"signal".to_owned()` requires cleanup. Older versions
     // of the code had a problem that the cleanup scope for this
index a430e1c8de91668c485ec0d974f3601f71015bd8..38030eb6c1fdcb72cb0a1c70ffb114795958665f 100644 (file)
@@ -17,6 +17,7 @@
 
 pub fn main () {
     let args = os::args();
+    let args = args.as_slice();
     if args.len() > 1 && args[1] == "child".to_owned() {
         for _ in range(0, 1000) {
             println!("hello?");
index aa4deeb73c9317c33f7de375169fab42278b91bc..f66b943d85f64fbedc624ceb0e81923fc4e74b67 100644 (file)
@@ -25,6 +25,7 @@ fn start(argc: int, argv: **u8) -> int {
 
 fn main() {
     let args = os::args();
+    let args = args.as_slice();
     if args.len() > 1 && args[1].as_slice() == "child" {
         if args[2].as_slice() == "green" {
             child();
@@ -48,6 +49,7 @@ fn main() {
 
 fn parent(flavor: ~str) {
     let args = os::args();
+    let args = args.as_slice();
     let mut p = io::Process::new(args[0].as_slice(), ["child".to_owned(), flavor]).unwrap();
     p.stdin.get_mut_ref().write_str("test1\ntest2\ntest3").unwrap();
     let out = p.wait_with_output();
index adc5c86aa4aeb5acb46372673f7d4e842e18002b..f05b1932b738dd2916663b7655f628faabef65ec 100644 (file)
@@ -10,6 +10,7 @@
 
 fn parse_args() -> ~str {
     let args = ::std::os::args();
+    let args = args.as_slice();
     let mut n = 0;
 
     while n < args.len() {
index d051f91811507f7bca42beccc67138828b0c190d..a5e632b94a28888c7437d2dae2d2ad10885d0e7c 100644 (file)
@@ -22,6 +22,7 @@
 
 fn main() {
     let args = os::args();
+    let args = args.as_slice();
     if args.len() > 1 && args[1].as_slice() == "child" {
         debug!("foo");
         debug!("bar");
index 674286751cbae5ee96c87a6f3c89314a092feda6..ac3a9ef2d533089cea13c32ad362136e1f05e3f5 100644 (file)
@@ -34,6 +34,7 @@ fn loud_recurse() {
 
 fn main() {
     let args = os::args();
+    let args = args.as_slice();
     if args.len() > 1 && args[1].as_slice() == "silent" {
         silent_recurse();
     } else if args.len() > 1 && args[1].as_slice() == "loud" {
index ce748d8684dd8bace87c697d6ead93335d9a1038..e4a935eae7f431af3ebd99082bdc74d9ca9a266b 100644 (file)
@@ -62,7 +62,7 @@ pub fn main() {
 
     assert!(map.pop(&Slice("foo")).is_some());
     assert_eq!(map.move_iter().map(|(k, v)| k.to_str() + v.to_str())
-                              .collect::<~[~str]>()
+                              .collect::<Vec<~str>>()
                               .concat(),
                "abc50bcd51cde52def53".to_owned());
 }
index 4afdec1ac06c518f11eb3823f5b5c7e0ab34cb55..a0459e6e8c1ada7d6d3f9fea5af9c2101b7543d6 100644 (file)
@@ -25,6 +25,7 @@
 
 pub fn main() {
     let args = os::args();
+    let args = args.as_slice();
     if args.len() >= 2 && args[1] == "signal".to_owned() {
         // Raise a segfault.
         unsafe { *(0 as *mut int) = 0; }
index b923bb91427fe64a111df82a5abd543138431fd5..34d1f5e66c6782a66f700aad2b67933d8a5a94e5 100644 (file)
@@ -25,6 +25,7 @@ fn test() {
 
 fn main() {
     let args = os::args();
+    let args = args.as_slice();
     if args.len() > 1 && args[1].as_slice() == "test" {
         return test();
     }
index e104f92a8bc93eed92d1f680fb20239a4e05d144..794f810165dcb46380f3f1d011ed121ebc45dac7 100644 (file)
@@ -20,7 +20,7 @@ fn to_string(&self) -> ~str { self.to_str() }
 
 impl<T:to_str> to_str for Vec<T> {
     fn to_string(&self) -> ~str {
-        format!("[{}]", self.iter().map(|e| e.to_string()).collect::<~[~str]>().connect(", "))
+        format!("[{}]", self.iter().map(|e| e.to_string()).collect::<Vec<~str>>().connect(", "))
     }
 }