diff --git a/src/compiletest/runtest.rs b/src/compiletest/runtest.rs index 858e7334cff06..cea440afd9028 100644 --- a/src/compiletest/runtest.rs +++ b/src/compiletest/runtest.rs @@ -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())) } } diff --git a/src/doc/guide-container.md b/src/doc/guide-container.md index 6a54dc7ea1809..1ab92d453785e 100644 --- a/src/doc/guide-container.md +++ b/src/doc/guide-container.md @@ -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::>(); +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 FromIterator for ~[A] { - pub fn from_iter>(iterator: &mut T) -> ~[A] { +impl FromIterator for Vec { + fn from_iter>(mut iterator: I) -> Vec { 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 } } ~~~ diff --git a/src/doc/rust.md b/src/doc/rust.md index 9a9e37479631f..e4c95538d3012 100644 --- a/src/doc/rust.md +++ b/src/doc/rust.md @@ -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(f: |A| -> B, xs: &[A]) -> ~[B] { +fn map(f: |A| -> B, xs: &[A]) -> Vec { 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 = 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`, a vector type with element type `B`. ### Self types diff --git a/src/doc/tutorial.md b/src/doc/tutorial.md index 56f9e8e5cbd7d..9b9153fe57946 100644 --- a/src/doc/tutorial.md +++ b/src/doc/tutorial.md @@ -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` +let more_numbers: Vec = 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 diff --git a/src/libcore/iter.rs b/src/libcore/iter.rs index 5ee642cd8100d..10ae30cf39d0c 100644 --- a/src/libcore/iter.rs +++ b/src/libcore/iter.rs @@ -455,8 +455,8 @@ pub trait Iterator { /// /// ```rust /// let a = [1, 2, 3, 4, 5]; - /// let b: ~[int] = a.iter().map(|&x| x).collect(); - /// assert!(a == b); + /// let b: Vec = a.iter().map(|&x| x).collect(); + /// assert!(a.as_slice() == b.as_slice()); /// ``` #[inline] fn collect>(&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 = FromIterator::from_iter(it); + assert_eq!(xs, vec![0, 5, 10, 15, 20, 25, 30, 35, 40, 45]); } #[test] @@ -2371,7 +2371,7 @@ mod tests { 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![0*0, 2*2, 4*4, 6*6, 8*8]); } #[test] @@ -2493,7 +2493,7 @@ mod tests { let ys = xs.iter() .map(|&x| x) .inspect(|_| n += 1) - .collect::<~[uint]>(); + .collect::>(); assert_eq!(n, xs.len()); assert_eq!(xs.as_slice(), ys.as_slice()); @@ -2628,8 +2628,8 @@ mod tests { #[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 = a.iter().map(|&x| x).collect(); assert_eq!(a, b); } @@ -2702,7 +2702,7 @@ mod tests { 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![16, 14, 12, 10, 8, 6]); } #[test] @@ -2940,12 +2940,12 @@ mod tests { #[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![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![13u, 12, 11]); for _ in range(10u, 0).rev() { fail!("unreachable"); } @@ -2997,13 +2997,14 @@ mod tests { } } - 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![0i, 1, 2, 3, 4]); + assert_eq!(range(-10i, -1).collect::>(), + vec![-10, -9, -8, -7, -6, -5, -4, -3, -2]); + assert_eq!(range(0i, 5).rev().collect::>(), vec![4, 3, 2, 1, 0]); + assert_eq!(range(200, -5).collect::>(), vec![]); + assert_eq!(range(200, -5).rev().collect::>(), vec![]); + assert_eq!(range(200, 200).collect::>(), vec![]); + assert_eq!(range(200, 200).rev().collect::>(), 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 @@ mod tests { #[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![0i, 1, 2, 3, 4, 5]); + assert_eq!(range_inclusive(0i, 5).rev().collect::>(), vec![5i, 4, 3, 2, 1, 0]); + assert_eq!(range_inclusive(200, -5).collect::>(), vec![]); + assert_eq!(range_inclusive(200, -5).rev().collect::>(), vec![]); + assert_eq!(range_inclusive(200, 200).collect::>(), vec![200]); + assert_eq!(range_inclusive(200, 200).rev().collect::>(), 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![0, 5, 10, 15]); + assert_eq!(range_step(20i, 0, -5).collect::>(), vec![20, 15, 10, 5]); + assert_eq!(range_step(20i, 0, -6).collect::>(), vec![20, 14, 8, 2]); + assert_eq!(range_step(200u8, 255, 50).collect::>(), vec![200u8, 250]); + assert_eq!(range_step(200, -5, 1).collect::>(), vec![]); + assert_eq!(range_step(200, 200, 1).collect::>(), 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![0, 5, 10, 15, 20]); + assert_eq!(range_step_inclusive(20i, 0, -5).collect::>(), vec![20, 15, 10, 5, 0]); + assert_eq!(range_step_inclusive(20i, 0, -6).collect::>(), vec![20, 14, 8, 2]); + assert_eq!(range_step_inclusive(200u8, 255, 50).collect::>(), vec![200u8, 250]); + assert_eq!(range_step_inclusive(200, -5, 1).collect::>(), vec![]); + assert_eq!(range_step_inclusive(200, 200, 1).collect::>(), vec![200]); } #[test] diff --git a/src/libcore/lib.rs b/src/libcore/lib.rs index 53de765b89c1d..a771f30dfd197 100644 --- a/src/libcore/lib.rs +++ b/src/libcore/lib.rs @@ -111,4 +111,6 @@ mod std { #[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![] } diff --git a/src/libcore/option.rs b/src/libcore/option.rs index c6884a8002f79..2f8457e93f671 100644 --- a/src/libcore/option.rs +++ b/src/libcore/option.rs @@ -844,22 +844,22 @@ mod tests { #[test] fn test_collect() { - let v: Option<~[int]> = collect(range(0, 0) - .map(|_| Some(0))); - assert_eq!(v, Some(box [])); + let v: Option> = 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> = 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> = 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> = collect(functions.mut_iter().map(|f| (*f)())); assert_eq!(v, None); } diff --git a/src/libcore/result.rs b/src/libcore/result.rs index 337b2ac89dd7a..27ae2ad9946f5 100644 --- a/src/libcore/result.rs +++ b/src/libcore/result.rs @@ -653,20 +653,20 @@ mod tests { #[test] fn test_collect() { - let v: Result<~[int], ()> = collect(range(0, 0).map(|_| Ok::(0))); - assert_eq!(v, Ok(box [])); + let v: Result, ()> = collect(range(0, 0).map(|_| Ok::(0))); + assert_eq!(v, Ok(vec![])); - let v: Result<~[int], ()> = collect(range(0, 3).map(|x| Ok::(x))); - assert_eq!(v, Ok(box [0, 1, 2])); + let v: Result, ()> = collect(range(0, 3).map(|x| Ok::(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, 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, int> = collect(functions.mut_iter().map(|f| (*f)())); assert_eq!(v, Err(1)); } diff --git a/src/libcore/should_not_exist.rs b/src/libcore/should_not_exist.rs index 50447f0c5b375..0e6baaa518a73 100644 --- a/src/libcore/should_not_exist.rs +++ b/src/libcore/should_not_exist.rs @@ -13,8 +13,9 @@ use char::Char; 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 slice::ImmutableVector; use str::StrSlice; #[cfg(not(test))] use ops::Add; -#[cfg(not(test))] use slice::Vector; #[allow(ctypes)] extern { @@ -147,56 +147,34 @@ impl<'a> Add<&'a str,~str> for &'a str { impl Clone for ~[A] { #[inline] fn clone(&self) -> ~[A] { - self.iter().map(|a| a.clone()).collect() - } -} - -impl FromIterator for ~[A] { - fn from_iter>(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::()).unwrap(); - let mut len = 0; + let len = self.len(); + let data_size = len.checked_mul(&mem::size_of::()).unwrap(); + let size = mem::size_of::>().checked_add(&data_size).unwrap(); unsafe { - let mut ptr = alloc(cap) as *mut Vec; - let mut ret = cast::transmute(ptr); - for elt in iterator { - if len * mem::size_of::() >= cap { - cap = cap.checked_mul(&2).unwrap(); - let ptr2 = alloc(cap) as *mut Vec; - 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::(); - } - ret + let ret = alloc(size) as *mut Vec; + + (*ret).fill = len * mem::nonzero_size_of::(); + (*ret).alloc = len * mem::nonzero_size_of::(); + + 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> Add 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> Add for ~[T] { - #[inline] - fn add(&self, rhs: &V) -> ~[T] { - self.as_slice() + rhs.as_slice() - } -} diff --git a/src/libcore/str.rs b/src/libcore/str.rs index 9d9e12d0ad594..689f59b471c90 100644 --- a/src/libcore/str.rs +++ b/src/libcore/str.rs @@ -621,12 +621,12 @@ impl<'a> Iterator for UTF16Items<'a> { /// 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![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 = "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(&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(&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(&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(&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" diff --git a/src/libgetopts/lib.rs b/src/libgetopts/lib.rs index 78c2b6c99e955..3de1dde240c97 100644 --- a/src/libgetopts/lib.rs +++ b/src/libgetopts/lib.rs @@ -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"), diff --git a/src/libnative/io/addrinfo.rs b/src/libnative/io/addrinfo.rs index 71944202205ff..57b87f21521e8 100644 --- a/src/libnative/io/addrinfo.rs +++ b/src/libnative/io/addrinfo.rs @@ -22,7 +22,7 @@ pub struct GetAddrInfoRequest; impl GetAddrInfoRequest { pub fn run(host: Option<&str>, servname: Option<&str>, - hint: Option) -> Result<~[ai::Info], IoError> { + hint: Option) -> Result, 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 @@ impl GetAddrInfoRequest { unsafe { freeaddrinfo(res); } - Ok(addrs.move_iter().collect()) + Ok(addrs) } } diff --git a/src/libnative/io/file_win32.rs b/src/libnative/io/file_win32.rs index 282f9c2e34347..42e5ad062ee84 100644 --- a/src/libnative/io/file_win32.rs +++ b/src/libnative/io/file_win32.rs @@ -22,7 +22,7 @@ use std::ptr; 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 @@ pub fn readdir(p: &CString) -> IoResult> { 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)); diff --git a/src/libnative/io/mod.rs b/src/libnative/io/mod.rs index 58fcd60f13815..f2c2c66e1425f 100644 --- a/src/libnative/io/mod.rs +++ b/src/libnative/io/mod.rs @@ -194,7 +194,7 @@ impl rtio::IoFactory for IoFactory { }) } fn get_host_addresses(&mut self, host: Option<&str>, servname: Option<&str>, - hint: Option) -> IoResult<~[ai::Info]> { + hint: Option) -> IoResult> { addrinfo::GetAddrInfoRequest::run(host, servname, hint) } @@ -260,7 +260,7 @@ impl rtio::IoFactory for IoFactory { } fn spawn(&mut self, config: ProcessConfig) -> IoResult<(Box, - ~[Option>])> { + Vec>>)> { process::Process::spawn(config).map(|(p, io)| { (box p as Box, io.move_iter().map(|p| p.map(|p| { diff --git a/src/libnative/io/process.rs b/src/libnative/io/process.rs index efdab990d1822..c83af20d1d84e 100644 --- a/src/libnative/io/process.rs +++ b/src/libnative/io/process.rs @@ -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]), io::IoError> + -> Result<(Process, Vec>), io::IoError> { // right now we only handle stdin/stdout/stderr. if config.extra_io.len() > 0 { @@ -117,7 +117,7 @@ impl Process { exit_code: None, exit_signal: None, }, - ret_io.move_iter().collect())) + ret_io)) } Err(e) => Err(e) } diff --git a/src/librustc/back/rpath.rs b/src/librustc/back/rpath.rs index 8c0aa494d6f80..c49adce904a51 100644 --- a/src/librustc/back/rpath.rs +++ b/src/librustc/back/rpath.rs @@ -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::>(); - 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 diff --git a/src/librustc/front/test.rs b/src/librustc/front/test.rs index 732443f1d4211..eaf6527ea829b 100644 --- a/src/librustc/front/test.rs +++ b/src/librustc/front/test.rs @@ -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(); diff --git a/src/librustc/lib.rs b/src/librustc/lib.rs index ab755b39f1a39..0962acd0a2ebf 100644 --- a/src/librustc/lib.rs +++ b/src/librustc/lib.rs @@ -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 { diff --git a/src/librustc/middle/trans/base.rs b/src/librustc/middle/trans/base.rs index 3bef0eae0acbc..400aa83a61514 100644 --- a/src/librustc/middle/trans/base.rs +++ b/src/librustc/middle/trans/base.rs @@ -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::>().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 { 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); diff --git a/src/librustc/middle/trans/consts.rs b/src/librustc/middle/trans/consts.rs index eae9da84a1fe6..548746362cf23 100644 --- a/src/librustc/middle/trans/consts.rs +++ b/src/librustc/middle/trans/consts.rs @@ -33,7 +33,7 @@ use middle::ty; 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)) }) } diff --git a/src/librustc/middle/trans/monomorphize.rs b/src/librustc/middle/trans/monomorphize.rs index b8f50fcb1e58c..4fd4f2f9d6ef0 100644 --- a/src/librustc/middle/trans/monomorphize.rs +++ b/src/librustc/middle/trans/monomorphize.rs @@ -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) } }; diff --git a/src/librustdoc/html/format.rs b/src/librustdoc/html/format.rs index b544c939e936e..06996df169254 100644 --- a/src/librustdoc/html/format.rs +++ b/src/librustdoc/html/format.rs @@ -380,7 +380,7 @@ impl fmt::Show for clean::Type { "".to_owned() } else { let mut m = decl.bounds.iter().map(|s| s.to_str()); - ": " + m.collect::<~[~str]>().connect(" + ") + ": " + m.collect::>().connect(" + ") }, arrow = match decl.decl.output { clean::Unit => "no", _ => "yes" }, ret = decl.decl.output) diff --git a/src/librustdoc/html/render.rs b/src/librustdoc/html/render.rs index fe80d26d10933..0bdf0818c8e82 100644 --- a/src/librustdoc/html/render.rs +++ b/src/librustdoc/html/render.rs @@ -549,7 +549,8 @@ impl<'a> SourceCollector<'a> { 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()); diff --git a/src/librustdoc/lib.rs b/src/librustdoc/lib.rs index a79c8b30bbad2..72b474147335c 100644 --- a/src/librustdoc/lib.rs +++ b/src/librustdoc/lib.rs @@ -85,7 +85,7 @@ local_data_key!(pub analysiskey: core::CrateAnalysis) type Output = (clean::Crate, Vec ); 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 { diff --git a/src/librustuv/addrinfo.rs b/src/librustuv/addrinfo.rs index 94a084fe055ae..4766630b0f421 100644 --- a/src/librustuv/addrinfo.rs +++ b/src/librustuv/addrinfo.rs @@ -33,7 +33,7 @@ pub struct GetAddrInfoRequest; impl GetAddrInfoRequest { pub fn run(loop_: &Loop, node: Option<&str>, service: Option<&str>, - hints: Option) -> Result<~[ai::Info], UvError> { + hints: Option) -> Result, 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 { unsafe { let mut addr = addr.handle; @@ -180,6 +180,6 @@ pub fn accum_addrinfo(addr: &Addrinfo) -> ~[ai::Info] { } } - return addrs.move_iter().collect(); + addrs } } diff --git a/src/librustuv/process.rs b/src/librustuv/process.rs index d744607050fc6..d671e20868c5c 100644 --- a/src/librustuv/process.rs +++ b/src/librustuv/process.rs @@ -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, ~[Option]), UvError> { + -> Result<(Box, Vec>), 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 @@ impl Process { }); match ret { - Ok(p) => Ok((p, ret_io.move_iter().collect())), + Ok(p) => Ok((p, ret_io)), Err(e) => Err(e), } } diff --git a/src/librustuv/uvio.rs b/src/librustuv/uvio.rs index 17a64fdb51760..50258c2583c65 100644 --- a/src/librustuv/uvio.rs +++ b/src/librustuv/uvio.rs @@ -178,7 +178,7 @@ impl IoFactory for UvIoFactory { } fn get_host_addresses(&mut self, host: Option<&str>, servname: Option<&str>, - hint: Option) -> Result<~[ai::Info], IoError> { + hint: Option) -> Result, IoError> { let r = GetAddrInfoRequest::run(&self.loop_, host, servname, hint); r.map_err(uv_error_to_io_error) } @@ -272,7 +272,7 @@ impl IoFactory for UvIoFactory { fn spawn(&mut self, config: ProcessConfig) -> Result<(Box, - ~[Option>]), + Vec>>), IoError> { match Process::spawn(self, config) { diff --git a/src/libserialize/base64.rs b/src/libserialize/base64.rs index 426894aeff7dd..4709365ebff53 100644 --- a/src/libserialize/base64.rs +++ b/src/libserialize/base64.rs @@ -146,7 +146,7 @@ impl<'a> ToBase64 for &'a [u8] { } unsafe { - str::raw::from_utf8_owned(v.move_iter().collect()) + str::raw::from_utf8(v.as_slice()).to_owned() } } } @@ -155,7 +155,7 @@ impl<'a> ToBase64 for &'a [u8] { 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, 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, FromBase64Error> { let mut r = Vec::new(); let mut buf: u32 = 0; let mut modulus = 0; @@ -256,7 +255,7 @@ impl<'a> FromBase64 for &'a str { _ => return Err(InvalidBase64Length), } - Ok(r.move_iter().collect()) + Ok(r) } } @@ -301,21 +300,21 @@ mod tests { #[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 @@ mod tests { for _ in range(0, 1000) { let times = task_rng().gen_range(1u, 100); let v = Vec::from_fn(times, |_| random::()); - 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()); } } diff --git a/src/libserialize/hex.rs b/src/libserialize/hex.rs index cbed0656e4de2..c463d97dba4d4 100644 --- a/src/libserialize/hex.rs +++ b/src/libserialize/hex.rs @@ -45,7 +45,7 @@ impl<'a> ToHex for &'a [u8] { } unsafe { - str::raw::from_utf8_owned(v.move_iter().collect()) + str::raw::from_utf8(v.as_slice()).to_owned() } } } @@ -54,7 +54,7 @@ impl<'a> ToHex for &'a [u8] { 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, 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, 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 @@ mod tests { #[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 @@ mod tests { #[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 @@ mod tests { #[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]); } } diff --git a/src/libserialize/json.rs b/src/libserialize/json.rs index 29315c458108f..2e4d7696c44d0 100644 --- a/src/libserialize/json.rs +++ b/src/libserialize/json.rs @@ -166,14 +166,14 @@ use serialize::{json, Encodable, Decodable}; pub struct TestStruct1 { data_int: u8, data_str: ~str, - data_vector: ~[u8], + data_vector: Vec, } // 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 @@ use collections::TreeMap; pub struct TestStruct1 { data_int: u8, data_str: ~str, - data_vector: ~[u8], + data_vector: Vec, } 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; pub type Object = TreeMap<~str, Json>; /// The errors that can arise while parsing a JSON stream. @@ -2211,7 +2211,7 @@ impl 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 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 @@ mod tests { struct Inner { a: (), b: uint, - c: ~[~str], + c: Vec<~str>, } #[deriving(Eq, Encodable, Decodable, Show)] struct Outer { - inner: ~[Inner], + inner: Vec, } fn mk_object(items: &[(~str, Json)]) -> Json { @@ -2360,22 +2360,22 @@ mod tests { #[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 @@ mod tests { ); 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 @@ mod tests { 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 @@ mod tests { 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 = 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 = 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 = 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> = Decodable::decode(&mut decoder).unwrap(); + assert_eq!(v, vec![vec![3], vec![1, 2]]); } #[test] @@ -2750,7 +2750,7 @@ mod tests { "{\"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 @@ mod tests { "}").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 @@ mod tests { 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 @@ mod tests { x: f64, y: bool, z: ~str, - w: ~[DecodeStruct] + w: Vec } #[deriving(Decodable)] enum DecodeEnum { diff --git a/src/libserialize/serialize.rs b/src/libserialize/serialize.rs index 9d68705fca73f..7914dd8c7d2aa 100644 --- a/src/libserialize/serialize.rs +++ b/src/libserialize/serialize.rs @@ -453,12 +453,14 @@ impl,T:Encodable> Encodable for ~[T] { impl,T:Decodable> Decodable for ~[T] { fn decode(d: &mut D) -> Result<~[T], E> { + use std::vec::FromVec; + d.read_seq(|d, len| { let mut v: Vec = 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 @@ impl> Encodable for path::posix::Path { impl> Decodable for path::posix::Path { fn decode(d: &mut D) -> Result { - let bytes: ~[u8] = try!(Decodable::decode(d)); + let bytes: Vec = try!(Decodable::decode(d)); Ok(path::posix::Path::new(bytes)) } } @@ -570,7 +572,7 @@ impl> Encodable for path::windows::Path { impl> Decodable for path::windows::Path { fn decode(d: &mut D) -> Result { - let bytes: ~[u8] = try!(Decodable::decode(d)); + let bytes: Vec = try!(Decodable::decode(d)); Ok(path::windows::Path::new(bytes)) } } @@ -600,17 +602,17 @@ impl> EncoderHelpers for S { } pub trait DecoderHelpers { - fn read_to_vec(&mut self, f: |&mut Self| -> Result) -> Result<~[T], E>; + fn read_to_vec(&mut self, f: |&mut Self| -> Result) -> Result, E>; } impl> DecoderHelpers for D { - fn read_to_vec(&mut self, f: |&mut D| -> Result) -> Result<~[T], E> { + fn read_to_vec(&mut self, f: |&mut D| -> Result) -> Result, 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) }) } } diff --git a/src/libstd/ascii.rs b/src/libstd/ascii.rs index 5b4400593b483..f45ec8a6742a2 100644 --- a/src/libstd/ascii.rs +++ b/src/libstd/ascii.rs @@ -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 { 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> { if self.is_ascii() { Some(unsafe { self.into_ascii_nocheck() }) } else { @@ -234,7 +234,7 @@ pub trait OwnedAsciiCast { /// 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; } impl OwnedAsciiCast for ~[u8] { @@ -244,8 +244,8 @@ impl OwnedAsciiCast for ~[u8] { } #[inline] - unsafe fn into_ascii_nocheck(self) -> ~[Ascii] { - cast::transmute(self) + unsafe fn into_ascii_nocheck(self) -> Vec { + cast::transmute(Vec::from_slice(self.as_slice())) } } @@ -256,7 +256,20 @@ impl OwnedAsciiCast for ~str { } #[inline] - unsafe fn into_ascii_nocheck(self) -> ~[Ascii] { + unsafe fn into_ascii_nocheck(self) -> Vec { + let v: ~[u8] = cast::transmute(self); + v.into_ascii_nocheck() + } +} + +impl OwnedAsciiCast for Vec { + #[inline] + fn is_ascii(&self) -> bool { + self.as_slice().is_ascii() + } + + #[inline] + unsafe fn into_ascii_nocheck(self) -> Vec { 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; /// Convert to vector representing a upper cased ascii string. - fn to_upper(&self) -> ~[Ascii]; + fn to_upper(&self) -> Vec; /// Compares two Ascii strings ignoring case. fn eq_ignore_case(self, other: &[Ascii]) -> bool; @@ -284,12 +297,12 @@ impl<'a> AsciiStr for &'a [Ascii] { } #[inline] - fn to_lower(&self) -> ~[Ascii] { + fn to_lower(&self) -> Vec { self.iter().map(|a| a.to_lower()).collect() } #[inline] - fn to_upper(&self) -> ~[Ascii] { + fn to_upper(&self) -> Vec { self.iter().map(|a| a.to_upper()).collect() } @@ -309,19 +322,21 @@ impl IntoStr for ~[Ascii] { impl IntoStr for Vec { #[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; } -impl IntoBytes for ~[Ascii] { - fn into_bytes(self) -> ~[u8] { +impl IntoBytes for Vec { + fn into_bytes(self) -> Vec { 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 @@ mod tests { #[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 @@ mod tests { #[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 @@ mod tests { 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); } diff --git a/src/libstd/io/mod.rs b/src/libstd/io/mod.rs index a89af05c50ae6..4a53a064610cb 100644 --- a/src/libstd/io/mod.rs +++ b/src/libstd/io/mod.rs @@ -76,7 +76,7 @@ Some examples of obvious things you might want to do 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 diff --git a/src/libstd/io/net/addrinfo.rs b/src/libstd/io/net/addrinfo.rs index 4006665e886c6..879c66e0769d8 100644 --- a/src/libstd/io/net/addrinfo.rs +++ b/src/libstd/io/net/addrinfo.rs @@ -24,7 +24,7 @@ use io::IoResult; 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> { 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) - -> IoResult<~[Info]> { + -> IoResult> { LocalIo::maybe_raise(|io| io.get_host_addresses(hostname, servname, hint)) } diff --git a/src/libstd/io/process.rs b/src/libstd/io/process.rs index 74f6944f102ea..3babef6126e8f 100644 --- a/src/libstd/io/process.rs +++ b/src/libstd/io/process.rs @@ -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], + pub extra_io: Vec>, } /// This configuration describes how a new process should be spawned. A blank @@ -418,7 +418,7 @@ impl Drop for Process { 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(); } diff --git a/src/libstd/lib.rs b/src/libstd/lib.rs index 72d41ae1dd291..8a783b6f378e2 100644 --- a/src/libstd/lib.rs +++ b/src/libstd/lib.rs @@ -278,4 +278,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; } diff --git a/src/libstd/num/i16.rs b/src/libstd/num/i16.rs index 4bd2ba07634ca..d8f1c108b742d 100644 --- a/src/libstd/num/i16.rs +++ b/src/libstd/num/i16.rs @@ -11,11 +11,10 @@ //! 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}; diff --git a/src/libstd/num/i32.rs b/src/libstd/num/i32.rs index 3c3acfae3c0f8..9cc8981fc13f4 100644 --- a/src/libstd/num/i32.rs +++ b/src/libstd/num/i32.rs @@ -11,11 +11,10 @@ //! 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}; diff --git a/src/libstd/num/i64.rs b/src/libstd/num/i64.rs index ad0fe1c08ef04..4f7fe32cc7088 100644 --- a/src/libstd/num/i64.rs +++ b/src/libstd/num/i64.rs @@ -11,11 +11,10 @@ //! 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}; diff --git a/src/libstd/num/i8.rs b/src/libstd/num/i8.rs index bd40a2c53b656..bea315d868373 100644 --- a/src/libstd/num/i8.rs +++ b/src/libstd/num/i8.rs @@ -11,11 +11,10 @@ //! 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}; diff --git a/src/libstd/num/int.rs b/src/libstd/num/int.rs index d9552ee33400e..d6a7fd1660b42 100644 --- a/src/libstd/num/int.rs +++ b/src/libstd/num/int.rs @@ -11,11 +11,10 @@ //! 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}; diff --git a/src/libstd/num/int_macros.rs b/src/libstd/num/int_macros.rs index 8a7bea465851a..fcdb63f5ad5eb 100644 --- a/src/libstd/num/int_macros.rs +++ b/src/libstd/num/int_macros.rs @@ -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() } } } diff --git a/src/libstd/num/strconv.rs b/src/libstd/num/strconv.rs index 8861597bb4c16..4769b17fb2b84 100644 --- a/src/libstd/num/strconv.rs +++ b/src/libstd/num/strconv.rs @@ -19,11 +19,10 @@ use num::{Float, FPNaN, FPInfinite, ToPrimitive}; 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+Neg+Rem+Mul>( num: T, radix: uint, negative_zero: bool, sign: SignFormat, digits: SignificantDigits, exp_format: ExponentFormat, exp_upper: bool - ) -> (~[u8], bool) { + ) -> (Vec, 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 { 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 (~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, diff --git a/src/libstd/num/u16.rs b/src/libstd/num/u16.rs index dd6a838df9ba6..5c93ca6c36b79 100644 --- a/src/libstd/num/u16.rs +++ b/src/libstd/num/u16.rs @@ -11,11 +11,10 @@ //! 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}; diff --git a/src/libstd/num/u32.rs b/src/libstd/num/u32.rs index bb05938969dee..436eae7cd14d0 100644 --- a/src/libstd/num/u32.rs +++ b/src/libstd/num/u32.rs @@ -11,11 +11,10 @@ //! 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}; diff --git a/src/libstd/num/u64.rs b/src/libstd/num/u64.rs index f38806e1527fd..c654d6fbe3133 100644 --- a/src/libstd/num/u64.rs +++ b/src/libstd/num/u64.rs @@ -11,11 +11,10 @@ //! 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}; diff --git a/src/libstd/num/u8.rs b/src/libstd/num/u8.rs index 87fed563a1535..7051b9191be81 100644 --- a/src/libstd/num/u8.rs +++ b/src/libstd/num/u8.rs @@ -11,11 +11,10 @@ //! 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}; diff --git a/src/libstd/num/uint.rs b/src/libstd/num/uint.rs index 61ab97e86b87c..d1c3e96b2c987 100644 --- a/src/libstd/num/uint.rs +++ b/src/libstd/num/uint.rs @@ -11,11 +11,10 @@ //! 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}; diff --git a/src/libstd/num/uint_macros.rs b/src/libstd/num/uint_macros.rs index 3e64c17161368..0795238a49cff 100644 --- a/src/libstd/num/uint_macros.rs +++ b/src/libstd/num/uint_macros.rs @@ -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() } } } diff --git a/src/libstd/os.rs b/src/libstd/os.rs index 809757aaf4d02..66143b40d5251 100644 --- a/src/libstd/os.rs +++ b/src/libstd/os.rs @@ -169,7 +169,7 @@ fn with_env_lock(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 @@ pub fn env_as_bytes() -> ~[(~[u8],~[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 { #[cfg(target_os = "freebsd")] - fn load_self() -> Option<~[u8]> { + fn load_self() -> Option> { unsafe { use libc::funcs::bsd44::*; use libc::consts::os::extra::*; @@ -436,23 +436,23 @@ pub fn self_exe_name() -> Option { 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> { 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> { unsafe { use libc::funcs::extra::_NSGetExecutablePath; let mut sz: u32 = 0; @@ -462,19 +462,19 @@ pub fn self_exe_name() -> Option { 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> { 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()) } } @@ -789,12 +789,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() + }) } /** @@ -803,7 +803,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); @@ -814,7 +814,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() { @@ -824,12 +824,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; @@ -855,11 +855,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() } @@ -883,13 +883,13 @@ extern "system" { /// /// 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() } diff --git a/src/libstd/rt/args.rs b/src/libstd/rt/args.rs index ac1692e6bb33a..df0f1d8d449e4 100644 --- a/src/libstd/rt/args.rs +++ b/src/libstd/rt/args.rs @@ -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> { imp::take() } +#[cfg(test)] pub fn take() -> Option> { 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> { imp::clone() } +#[cfg(test)] pub fn clone() -> Option> { 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 @@ mod imp { lock.destroy(); } - pub fn take() -> Option<~[~[u8]]> { + pub fn take() -> Option> { 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>| (**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 @@ mod imp { }) } - pub fn clone() -> Option<~[~[u8]]> { + pub fn clone() -> Option> { with_lock(|| unsafe { let ptr = get_global_ptr(); - (*ptr).as_ref().map(|s: &Box<~[~[u8]]>| (**s).clone()) + (*ptr).as_ref().map(|s: &Box>| (**s).clone()) }) } @@ -117,13 +119,13 @@ mod imp { } } - fn get_global_ptr() -> *mut Option> { + fn get_global_ptr() -> *mut Option>> { 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 @@ mod imp { 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 @@ mod imp { // 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 @@ mod imp { #[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 @@ mod imp { pub fn cleanup() { } - pub fn take() -> Option<~[~[u8]]> { + pub fn take() -> Option> { fail!() } - pub fn put(_args: ~[~[u8]]) { + pub fn put(_args: Vec<~[u8]>) { fail!() } - pub fn clone() -> Option<~[~[u8]]> { + pub fn clone() -> Option> { fail!() } } diff --git a/src/libstd/rt/rtio.rs b/src/libstd/rt/rtio.rs index 16882624ab71a..ccde8d9c96af0 100644 --- a/src/libstd/rt/rtio.rs +++ b/src/libstd/rt/rtio.rs @@ -161,7 +161,7 @@ pub trait IoFactory { fn unix_connect(&mut self, path: &CString, timeout: Option) -> IoResult>; fn get_host_addresses(&mut self, host: Option<&str>, servname: Option<&str>, - hint: Option) -> IoResult<~[ai::Info]>; + hint: Option) -> IoResult>; // filesystem operations fn fs_from_raw_fd(&mut self, fd: c_int, close: CloseBehavior) @@ -191,7 +191,7 @@ pub trait IoFactory { fn timer_init(&mut self) -> IoResult>; fn spawn(&mut self, config: ProcessConfig) -> IoResult<(Box, - ~[Option>])>; + Vec>>)>; fn kill(&mut self, pid: libc::pid_t, signal: int) -> IoResult<()>; fn pipe_open(&mut self, fd: c_int) -> IoResult>; fn tty_open(&mut self, fd: c_int, readable: bool) diff --git a/src/libstd/slice.rs b/src/libstd/slice.rs index c7cefbb28eef9..21084407b8d09 100644 --- a/src/libstd/slice.rs +++ b/src/libstd/slice.rs @@ -127,23 +127,23 @@ pub trait VectorVector { // 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; /// 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; } impl<'a, T: Clone, V: Vector> VectorVector for &'a [V] { - fn concat_vec(&self) -> ~[T] { + fn concat_vec(&self) -> Vec { 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 { 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 @@ impl<'a, T: Clone, V: Vector> VectorVector for &'a [V] { 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>(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>(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, /// If true, emit the last swap that returns the sequence to initial state emit_reset: bool, swaps_made : uint, @@ -199,9 +180,7 @@ impl 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 @@ impl Iterator<(uint, uint)> for ElementSwaps { 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 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::()); + let data_size = data_size.expect("overflow in to_owned()"); + let size = mem::size_of::>().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::(); + (*ret).alloc = len * mem::nonzero_size_of::(); + + // 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 @@ impl<'a, T: Clone> CloneableVector for &'a [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 @@ impl CloneableVector for ~[T] { pub trait ImmutableCloneableVector { /// 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, Vec); /// Create an iterator that yields every possible permutation of the /// vector in succession. @@ -363,7 +361,7 @@ pub trait ImmutableCloneableVector { impl<'a,T:Clone> ImmutableCloneableVector for &'a [T] { #[inline] - fn partitioned(&self, f: |&T| -> bool) -> (~[T], ~[T]) { + fn partitioned(&self, f: |&T| -> bool) -> (Vec, Vec) { let mut lefts = Vec::new(); let mut rights = Vec::new(); @@ -375,7 +373,7 @@ impl<'a,T:Clone> ImmutableCloneableVector for &'a [T] { } } - (lefts.move_iter().collect(), rights.move_iter().collect()) + (lefts, rights) } fn permutations(self) -> Permutations { @@ -412,7 +410,7 @@ pub trait OwnedVector { * 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, Vec); } impl OwnedVector for ~[T] { @@ -432,7 +430,7 @@ impl OwnedVector for ~[T] { } #[inline] - fn partition(self, f: |&T| -> bool) -> (~[T], ~[T]) { + fn partition(self, f: |&T| -> bool) -> (Vec, Vec) { let mut lefts = Vec::new(); let mut rights = Vec::new(); @@ -444,7 +442,7 @@ impl OwnedVector for ~[T] { } } - (lefts.move_iter().collect(), rights.move_iter().collect()) + (lefts, rights) } } @@ -729,45 +727,10 @@ impl<'a, T: TotalOrd> MutableTotalOrdVector for &'a mut [T] { } } -/** -* 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(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(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 @@ mod tests { 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 @@ mod tests { 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 @@ mod tests { let n = task_rng().gen::() % 10; counts[n] += 1; (n, counts[n]) - }).collect::<~[(uint, int)]>(); + }).collect::>(); // only sort on the first element, so an unstable sort // may mix up the counts. @@ -1436,46 +1363,45 @@ mod tests { // 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 @@ mod tests { 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::>().as_slice(), + &[&[1], &[3], &[5]]); + assert_eq!(xs.split(|x| *x == 1).collect::>().as_slice(), + &[&[], &[2,3,4,5]]); + assert_eq!(xs.split(|x| *x == 5).collect::>().as_slice(), + &[&[1,2,3,4], &[]]); + assert_eq!(xs.split(|x| *x == 10).collect::>().as_slice(), + &[&[1,2,3,4,5]]); + assert_eq!(xs.split(|_| true).collect::>().as_slice(), + &[&[], &[], &[], &[], &[], &[]]); let xs: &[int] = &[]; - assert_eq!(xs.split(|x| *x == 5).collect::<~[&[int]]>(), box [&[]]); + assert_eq!(xs.split(|x| *x == 5).collect::>().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::>().as_slice(), + &[&[1,2,3,4,5]]); + assert_eq!(xs.splitn(1, |x| *x % 2 == 0).collect::>().as_slice(), + &[&[1], &[3,4,5]]); + assert_eq!(xs.splitn(3, |_| true).collect::>().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::>().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::>().as_slice(), + &[&[5], &[3], &[1]]); + assert_eq!(xs.split(|x| *x == 1).rev().collect::>().as_slice(), + &[&[2,3,4,5], &[]]); + assert_eq!(xs.split(|x| *x == 5).rev().collect::>().as_slice(), + &[&[], &[1,2,3,4]]); + assert_eq!(xs.split(|x| *x == 10).rev().collect::>().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::>().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::>().as_slice(), + &[&[1,2,3,4,5]]); + assert_eq!(xs.rsplitn(1, |x| *x % 2 == 0).collect::>().as_slice(), + &[&[5], &[1,2,3]]); + assert_eq!(xs.rsplitn(3, |_| true).collect::>().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::>().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::>().as_slice(), &[&[1,2], &[2,3], &[3,4]]); + assert_eq!(v.windows(3).collect::>().as_slice(), &[&[1i,2,3], &[2,3,4]]); assert!(v.windows(6).next().is_none()); } @@ -1855,11 +1781,11 @@ mod tests { 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::>().as_slice(), &[&[1i,2], &[3,4], &[5]]); + assert_eq!(v.chunks(3).collect::>().as_slice(), &[&[1i,2,3], &[4,5]]); + assert_eq!(v.chunks(6).collect::>().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::>().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 @@ mod bench { }) } - #[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::from_fn(100, |i| range(0, i).collect()); diff --git a/src/libstd/str.rs b/src/libstd/str.rs index 666c0a58b3351..fb3dcc972871d 100644 --- a/src/libstd/str.rs +++ b/src/libstd/str.rs @@ -85,10 +85,9 @@ use fmt; 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 @@ impl<'a> fmt::Show for MaybeOwned<'a> { /// 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 @@ pub trait StrAllocating: 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 { 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 @@ mod tests { 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 @@ mod tests { 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 @@ mod tests { 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 @@ mod tests { 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 @@ mod tests { 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 @@ mod tests { 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 @@ mod tests { #[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] diff --git a/src/libstd/strbuf.rs b/src/libstd/strbuf.rs index ad703b8054b0b..8e05b2f527d08 100644 --- a/src/libstd/strbuf.rs +++ b/src/libstd/strbuf.rs @@ -19,7 +19,7 @@ use io::Writer; 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 @@ impl Str for StrBuf { 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()) } } diff --git a/src/libstd/sync/arc.rs b/src/libstd/sync/arc.rs index d277c514e444f..676c836c459d7 100644 --- a/src/libstd/sync/arc.rs +++ b/src/libstd/sync/arc.rs @@ -69,14 +69,14 @@ impl UnsafeArc { /// As new(), but returns a vector of as many pre-cloned handles as /// requested. - pub fn newN(data: T, num_handles: uint) -> ~[UnsafeArc] { + pub fn newN(data: T, num_handles: uint) -> Vec> { 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 } } } diff --git a/src/libstd/sync/deque.rs b/src/libstd/sync/deque.rs index d06062f02ac8a..8dfd691e6ffdc 100644 --- a/src/libstd/sync/deque.rs +++ b/src/libstd/sync/deque.rs @@ -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 @@ mod tests { 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 { diff --git a/src/libstd/unstable/dynamic_lib.rs b/src/libstd/unstable/dynamic_lib.rs index 68f0aaab05b1b..e2a9f6a5c4821 100644 --- a/src/libstd/unstable/dynamic_lib.rs +++ b/src/libstd/unstable/dynamic_lib.rs @@ -18,13 +18,16 @@ A simple wrapper over the platform's dynamic library facilities 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 @@ impl DynamicLibrary { ("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::>(); + 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 diff --git a/src/libstd/vec.rs b/src/libstd/vec.rs index af146b96e505a..da01da2670959 100644 --- a/src/libstd/vec.rs +++ b/src/libstd/vec.rs @@ -22,12 +22,13 @@ use mem::{size_of, move_val_init}; 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 @@ impl Vector for Vec { } } +impl> Add> for Vec { + #[inline] + fn add(&self, rhs: &V) -> Vec { + 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 Drop for Vec { fn drop(&mut self) { @@ -1436,10 +1447,94 @@ impl Drop for MoveItems { } } +/** + * 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>(mut iter: V) -> (Vec, Vec) { + 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` 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 { + /// Convert a `Vec` into the receiver type. + fn from_vec(v: Vec) -> Self; +} + +impl FromVec for ~[T] { + fn from_vec(mut v: Vec) -> ~[T] { + let len = v.len(); + let data_size = len.checked_mul(&mem::size_of::()); + let data_size = data_size.expect("overflow in from_vec()"); + let size = mem::size_of::>().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::(); + (*ret).alloc = len * mem::nonzero_size_of::(); + + 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(ptr: *T, elts: uint) -> Vec { + 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 @@ mod tests { 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/bench/core-map.rs b/src/test/bench/core-map.rs index 4405245b9a0e1..6a8a56b4f1f8a 100644 --- a/src/test/bench/core-map.rs +++ b/src/test/bench/core-map.rs @@ -90,6 +90,7 @@ fn vector>(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::(args[1]).unwrap() diff --git a/src/test/bench/core-set.rs b/src/test/bench/core-set.rs index 96f3c6814ab93..b1181a3c17c5a 100644 --- a/src/test/bench/core-set.rs +++ b/src/test/bench/core-set.rs @@ -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::(args[1]).unwrap() diff --git a/src/test/bench/core-std.rs b/src/test/bench/core-std.rs index 902f2c72409ef..7e54198bd3961 100644 --- a/src/test/bench/core-std.rs +++ b/src/test/bench/core-std.rs @@ -24,7 +24,7 @@ use std::vec; 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() { diff --git a/src/test/bench/rt-messaging-ping-pong.rs b/src/test/bench/rt-messaging-ping-pong.rs index 044c4b07d443e..bbe6b6c23f0f9 100644 --- a/src/test/bench/rt-messaging-ping-pong.rs +++ b/src/test/bench/rt-messaging-ping-pong.rs @@ -61,6 +61,7 @@ fn ping_pong_bench(n: uint, m: uint) { fn main() { let args = os::args(); + let args = args.as_slice(); let n = if args.len() == 3 { from_str::(args[1]).unwrap() } else { diff --git a/src/test/bench/rt-parfib.rs b/src/test/bench/rt-parfib.rs index 1a7302207d968..29cee668389f8 100644 --- a/src/test/bench/rt-parfib.rs +++ b/src/test/bench/rt-parfib.rs @@ -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::(args[1]).unwrap() } else { diff --git a/src/test/bench/rt-spawn-rate.rs b/src/test/bench/rt-spawn-rate.rs index 4f07660779b26..48d4a41c1a39a 100644 --- a/src/test/bench/rt-spawn-rate.rs +++ b/src/test/bench/rt-spawn-rate.rs @@ -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::(args[1]).unwrap() } else { diff --git a/src/test/bench/shootout-binarytrees.rs b/src/test/bench/shootout-binarytrees.rs index 49184e188ebb6..8914c5b327ecc 100644 --- a/src/test/bench/shootout-binarytrees.rs +++ b/src/test/bench/shootout-binarytrees.rs @@ -40,6 +40,7 @@ fn bottom_up_tree<'r>(arena: &'r TypedArena>, 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 { diff --git a/src/test/bench/shootout-chameneos-redux.rs b/src/test/bench/shootout-chameneos-redux.rs index 7587a21a9df0d..07e5b08c37ccb 100644 --- a/src/test/bench/shootout-chameneos-redux.rs +++ b/src/test/bench/shootout-chameneos-redux.rs @@ -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(); diff --git a/src/test/bench/shootout-fannkuch-redux.rs b/src/test/bench/shootout-fannkuch-redux.rs index 4bea355472de1..3525b90d3f681 100644 --- a/src/test/bench/shootout-fannkuch-redux.rs +++ b/src/test/bench/shootout-fannkuch-redux.rs @@ -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) { diff --git a/src/test/bench/shootout-fasta-redux.rs b/src/test/bench/shootout-fasta-redux.rs index 01b75fa422f92..3f8d3275b64f9 100644 --- a/src/test/bench/shootout-fasta-redux.rs +++ b/src/test/bench/shootout-fasta-redux.rs @@ -177,6 +177,7 @@ impl<'a, W: Writer> RandomFasta<'a, W> { fn main() { let args = os::args(); + let args = args.as_slice(); let n = if args.len() > 1 { from_str::(args[1]).unwrap() } else { diff --git a/src/test/bench/shootout-fasta.rs b/src/test/bench/shootout-fasta.rs index 76ac8407d60c5..c526ef54caff2 100644 --- a/src/test/bench/shootout-fasta.rs +++ b/src/test/bench/shootout-fasta.rs @@ -74,6 +74,7 @@ fn make_fasta>( fn run(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 { diff --git a/src/test/bench/shootout-k-nucleotide-pipes.rs b/src/test/bench/shootout-k-nucleotide-pipes.rs index 659270b555427..e2bcc55d13982 100644 --- a/src/test/bench/shootout-k-nucleotide-pipes.rs +++ b/src/test/bench/shootout-k-nucleotide-pipes.rs @@ -72,7 +72,7 @@ fn sort_and_fmt(mm: &HashMap , uint>, total: uint) -> ~str { // given a map, search for the frequency of a pattern fn find(mm: &HashMap , 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; } diff --git a/src/test/bench/shootout-mandelbrot.rs b/src/test/bench/shootout-mandelbrot.rs index e7b4d0a5c1c6d..ee715aecec4fc 100644 --- a/src/test/bench/shootout-mandelbrot.rs +++ b/src/test/bench/shootout-mandelbrot.rs @@ -65,6 +65,7 @@ fn mandelbrot(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."); diff --git a/src/test/bench/shootout-meteor.rs b/src/test/bench/shootout-meteor.rs index 6e86f5205f017..cb46c542f5bc8 100644 --- a/src/test/bench/shootout-meteor.rs +++ b/src/test/bench/shootout-meteor.rs @@ -190,7 +190,7 @@ fn to_utf8(raw_sol: &List) -> ~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 { diff --git a/src/test/bench/shootout-pidigits.rs b/src/test/bench/shootout-pidigits.rs index 71cd176a836ff..49356e6e6458e 100644 --- a/src/test/bench/shootout-pidigits.rs +++ b/src/test/bench/shootout-pidigits.rs @@ -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 { diff --git a/src/test/bench/shootout-spectralnorm.rs b/src/test/bench/shootout-spectralnorm.rs index e63c78d50af72..70a0e7a957c6b 100644 --- a/src/test/bench/shootout-spectralnorm.rs +++ b/src/test/bench/shootout-spectralnorm.rs @@ -94,6 +94,7 @@ fn mult_AtAv(v: Arc>>, out: Arc>>, 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 { diff --git a/src/test/bench/shootout-threadring.rs b/src/test/bench/shootout-threadring.rs index a845481f0e028..60485f40ba4e0 100644 --- a/src/test/bench/shootout-threadring.rs +++ b/src/test/bench/shootout-threadring.rs @@ -35,6 +35,7 @@ fn roundtrip(id: int, tx: Sender, rx: Receiver) { 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/run-make/unicode-input/multiple_files.rs b/src/test/run-make/unicode-input/multiple_files.rs index d54c04b77b0d8..a08d6bb0bf87f 100644 --- a/src/test/run-make/unicode-input/multiple_files.rs +++ b/src/test/run-make/unicode-input/multiple_files.rs @@ -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(); diff --git a/src/test/run-make/unicode-input/span_length.rs b/src/test/run-make/unicode-input/span_length.rs index 5f4af50753ec7..13f141008b792 100644 --- a/src/test/run-make/unicode-input/span_length.rs +++ b/src/test/run-make/unicode-input/span_length.rs @@ -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(); diff --git a/src/test/run-pass/backtrace.rs b/src/test/run-pass/backtrace.rs index 0277cb35f5286..989453d8570d1 100644 --- a/src/test/run-pass/backtrace.rs +++ b/src/test/run-pass/backtrace.rs @@ -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" { diff --git a/src/test/run-pass/cleanup-shortcircuit.rs b/src/test/run-pass/cleanup-shortcircuit.rs index 76d73fd5b8705..c409852c6736c 100644 --- a/src/test/run-pass/cleanup-shortcircuit.rs +++ b/src/test/run-pass/cleanup-shortcircuit.rs @@ -24,6 +24,7 @@ use std::os; 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 diff --git a/src/test/run-pass/issue-10626.rs b/src/test/run-pass/issue-10626.rs index a430e1c8de916..38030eb6c1fdc 100644 --- a/src/test/run-pass/issue-10626.rs +++ b/src/test/run-pass/issue-10626.rs @@ -17,6 +17,7 @@ use std::io::process; 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?"); diff --git a/src/test/run-pass/issue-13304.rs b/src/test/run-pass/issue-13304.rs index aa4deeb73c931..f66b943d85f64 100644 --- a/src/test/run-pass/issue-13304.rs +++ b/src/test/run-pass/issue-13304.rs @@ -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(); diff --git a/src/test/run-pass/issue-4541.rs b/src/test/run-pass/issue-4541.rs index adc5c86aa4aeb..f05b1932b738d 100644 --- a/src/test/run-pass/issue-4541.rs +++ b/src/test/run-pass/issue-4541.rs @@ -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() { diff --git a/src/test/run-pass/logging-separate-lines.rs b/src/test/run-pass/logging-separate-lines.rs index d051f91811507..a5e632b94a288 100644 --- a/src/test/run-pass/logging-separate-lines.rs +++ b/src/test/run-pass/logging-separate-lines.rs @@ -22,6 +22,7 @@ use std::str; fn main() { let args = os::args(); + let args = args.as_slice(); if args.len() > 1 && args[1].as_slice() == "child" { debug!("foo"); debug!("bar"); diff --git a/src/test/run-pass/out-of-stack.rs b/src/test/run-pass/out-of-stack.rs index 674286751cbae..ac3a9ef2d5330 100644 --- a/src/test/run-pass/out-of-stack.rs +++ b/src/test/run-pass/out-of-stack.rs @@ -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" { diff --git a/src/test/run-pass/send_str_treemap.rs b/src/test/run-pass/send_str_treemap.rs index ce748d8684dd8..e4a935eae7f43 100644 --- a/src/test/run-pass/send_str_treemap.rs +++ b/src/test/run-pass/send_str_treemap.rs @@ -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::>() .concat(), "abc50bcd51cde52def53".to_owned()); } diff --git a/src/test/run-pass/signal-exit-status.rs b/src/test/run-pass/signal-exit-status.rs index 4afdec1ac06c5..a0459e6e8c1ad 100644 --- a/src/test/run-pass/signal-exit-status.rs +++ b/src/test/run-pass/signal-exit-status.rs @@ -25,6 +25,7 @@ use std::io::process::{Process, ExitSignal, ExitStatus}; 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; } diff --git a/src/test/run-pass/sigpipe-should-be-ignored.rs b/src/test/run-pass/sigpipe-should-be-ignored.rs index b923bb91427fe..34d1f5e66c678 100644 --- a/src/test/run-pass/sigpipe-should-be-ignored.rs +++ b/src/test/run-pass/sigpipe-should-be-ignored.rs @@ -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(); } diff --git a/src/test/run-pass/trait-to-str.rs b/src/test/run-pass/trait-to-str.rs index e104f92a8bc93..794f810165dcb 100644 --- a/src/test/run-pass/trait-to-str.rs +++ b/src/test/run-pass/trait-to-str.rs @@ -20,7 +20,7 @@ impl to_str for int { impl to_str for Vec { 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::>().connect(", ")) } }