auto merge of #13963 : kballard/rust/remove_owned_vec_from_iterator, r=pcwalton

With `~[T]` no longer growable, the `FromIterator` impl for `~[T]` doesn't make
much sense. Not only that, but nearly everywhere it is used is to convert from
a `Vec<T>` into a `~[T]`, for the sake of maintaining existing APIs. This turns
out to be a performance loss, as it means every API that returns `~[T]`, even a
supposedly non-copying one, is in fact doing extra allocations and memcpy's.
Even `&[T].to_owned()` is going through `Vec<T>` first.

Remove the `FromIterator` impl for `~[T]`, and adjust all the APIs that relied
on it to start using `Vec<T>` instead. This includes rewriting
`&[T].to_owned()` to be more efficient, among other performance wins.

Also add a new mechanism to go from `Vec<T>` -> `~[T]`, just in case anyone
truly needs that, using the new trait `FromVec`.

[breaking-change]
This commit is contained in:
bors 2014-05-08 21:01:42 -07:00
commit a990920c6f
89 changed files with 828 additions and 726 deletions

View File

@ -997,7 +997,7 @@ fn make_lib_name(config: &config, auxfile: &Path, testfile: &Path) -> Path {
fn make_exe_name(config: &config, testfile: &Path) -> Path {
let mut f = output_base_name(config, testfile);
if !os::consts::EXE_SUFFIX.is_empty() {
match f.filename().map(|s| s + os::consts::EXE_SUFFIX.as_bytes()) {
match f.filename().map(|s| Vec::from_slice(s).append(os::consts::EXE_SUFFIX.as_bytes())) {
Some(v) => f.set_filename(v),
None => ()
}
@ -1091,7 +1091,7 @@ fn make_out_name(config: &config, testfile: &Path, extension: &str) -> Path {
fn aux_output_dir_name(config: &config, testfile: &Path) -> Path {
let mut f = output_base_name(config, testfile);
match f.filename().map(|s| s + bytes!(".libaux")) {
match f.filename().map(|s| Vec::from_slice(s).append(bytes!(".libaux"))) {
Some(v) => f.set_filename(v),
None => ()
}
@ -1273,7 +1273,7 @@ fn append_suffix_to_stem(p: &Path, suffix: &str) -> Path {
(*p).clone()
} else {
let stem = p.filestem().unwrap();
p.with_filename(stem + bytes!("-") + suffix.as_bytes())
p.with_filename(Vec::from_slice(stem).append(bytes!("-")).append(suffix.as_bytes()))
}
}

View File

@ -266,8 +266,8 @@ Iterators offer generic conversion to containers with the `collect` adaptor:
~~~
let xs = [0, 1, 1, 2, 3, 5, 8];
let ys = xs.iter().rev().skip(1).map(|&x| x * 2).collect::<~[int]>();
assert_eq!(ys, ~[10, 6, 4, 2, 2, 0]);
let ys = xs.iter().rev().skip(1).map(|&x| x * 2).collect::<Vec<int>>();
assert_eq!(ys, vec![10, 6, 4, 2, 2, 0]);
~~~
The method requires a type hint for the container type, if the surrounding code
@ -278,14 +278,14 @@ implementing the `FromIterator` trait. For example, the implementation for
vectors is as follows:
~~~ {.ignore}
impl<A> FromIterator<A> for ~[A] {
pub fn from_iter<T: Iterator<A>>(iterator: &mut T) -> ~[A] {
impl<T> FromIterator<T> for Vec<T> {
fn from_iter<I:Iterator<A>>(mut iterator: I) -> Vec<T> {
let (lower, _) = iterator.size_hint();
let mut xs = with_capacity(lower);
for x in iterator {
xs.push(x);
let mut vector = Vec::with_capacity(lower);
for element in iterator {
vector.push(element);
}
xs
vector
}
}
~~~

View File

@ -3598,18 +3598,18 @@ and the cast expression in `main`.
Within the body of an item that has type parameter declarations, the names of its type parameters are types:
~~~~
fn map<A: Clone, B: Clone>(f: |A| -> B, xs: &[A]) -> ~[B] {
fn map<A: Clone, B: Clone>(f: |A| -> B, xs: &[A]) -> Vec<B> {
if xs.len() == 0 {
return ~[];
return vec![];
}
let first: B = f(xs[0].clone());
let rest: ~[B] = map(f, xs.slice(1, xs.len()));
return ~[first] + rest;
let rest: Vec<B> = map(f, xs.slice(1, xs.len()));
return vec![first].append(rest.as_slice());
}
~~~~
Here, `first` has type `B`, referring to `map`'s `B` type parameter;
and `rest` has type `~[B]`, a vector type with element type `B`.
and `rest` has type `Vec<B>`, a vector type with element type `B`.
### Self types

View File

@ -1588,8 +1588,8 @@ let mut numbers = vec![1, 2, 3];
numbers.push(4);
numbers.push(5);
// The type of a unique vector is written as `~[int]`
let more_numbers: ~[int] = numbers.move_iter().collect();
// The type of a unique vector is written as `Vec<int>`
let more_numbers: Vec<int> = numbers.move_iter().map(|i| i+1).collect();
// The original `numbers` value can no longer be used, due to move semantics.
@ -1633,7 +1633,7 @@ view[0] = 5;
let ys: &mut [int] = &mut [1, 2, 3];
~~~
Square brackets denote indexing into a vector:
Square brackets denote indexing into a slice or fixed-size vector:
~~~~
# enum Crayon { Almond, AntiqueBrass, Apricot,
@ -1647,7 +1647,7 @@ match crayons[0] {
}
~~~~
A vector can be destructured using pattern matching:
A slice or fixed-size vector can be destructured using pattern matching:
~~~~
let numbers: &[int] = &[1, 2, 3];
@ -1660,9 +1660,10 @@ let score = match numbers {
~~~~
Both vectors and strings support a number of useful [methods](#methods),
defined in [`std::vec`] and [`std::str`].
defined in [`std::vec`], [`std::slice`], and [`std::str`].
[`std::vec`]: std/vec/index.html
[`std::slice`]: std/slice/index.html
[`std::str`]: std/str/index.html
# Ownership escape hatches

View File

@ -455,8 +455,8 @@ pub trait Iterator<A> {
///
/// ```rust
/// let a = [1, 2, 3, 4, 5];
/// let b: ~[int] = a.iter().map(|&x| x).collect();
/// assert!(a == b);
/// let b: Vec<int> = a.iter().map(|&x| x).collect();
/// assert!(a.as_slice() == b.as_slice());
/// ```
#[inline]
fn collect<B: FromIterator<A>>(&mut self) -> B {
@ -2340,8 +2340,8 @@ mod tests {
#[test]
fn test_counter_from_iter() {
let it = count(0, 5).take(10);
let xs: ~[int] = FromIterator::from_iter(it);
assert_eq!(xs, box [0, 5, 10, 15, 20, 25, 30, 35, 40, 45]);
let xs: Vec<int> = FromIterator::from_iter(it);
assert_eq!(xs, vec![0, 5, 10, 15, 20, 25, 30, 35, 40, 45]);
}
#[test]
@ -2371,7 +2371,7 @@ 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<uint>>(), 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::<Vec<uint>>();
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<int> = 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<int>>(), 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<int>>(), vec![13i, 12, 11]);
for _ in range(10i, 0).rev() {
fail!("unreachable");
}
assert_eq!(range(11u, 14).rev().collect::<~[uint]>(), box [13u, 12, 11]);
assert_eq!(range(11u, 14).rev().collect::<Vec<uint>>(), vec![13u, 12, 11]);
for _ in range(10u, 0).rev() {
fail!("unreachable");
}
@ -2997,13 +2997,14 @@ 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<int>>(), vec![0i, 1, 2, 3, 4]);
assert_eq!(range(-10i, -1).collect::<Vec<int>>(),
vec![-10, -9, -8, -7, -6, -5, -4, -3, -2]);
assert_eq!(range(0i, 5).rev().collect::<Vec<int>>(), vec![4, 3, 2, 1, 0]);
assert_eq!(range(200, -5).collect::<Vec<int>>(), vec![]);
assert_eq!(range(200, -5).rev().collect::<Vec<int>>(), vec![]);
assert_eq!(range(200, 200).collect::<Vec<int>>(), vec![]);
assert_eq!(range(200, 200).rev().collect::<Vec<int>>(), vec![]);
assert_eq!(range(0i, 100).size_hint(), (100, Some(100)));
// this test is only meaningful when sizeof uint < sizeof u64
@ -3014,32 +3015,32 @@ 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<int>>(), vec![0i, 1, 2, 3, 4, 5]);
assert_eq!(range_inclusive(0i, 5).rev().collect::<Vec<int>>(), vec![5i, 4, 3, 2, 1, 0]);
assert_eq!(range_inclusive(200, -5).collect::<Vec<int>>(), vec![]);
assert_eq!(range_inclusive(200, -5).rev().collect::<Vec<int>>(), vec![]);
assert_eq!(range_inclusive(200, 200).collect::<Vec<int>>(), vec![200]);
assert_eq!(range_inclusive(200, 200).rev().collect::<Vec<int>>(), vec![200]);
}
#[test]
fn test_range_step() {
assert_eq!(range_step(0i, 20, 5).collect::<~[int]>(), box [0, 5, 10, 15]);
assert_eq!(range_step(20i, 0, -5).collect::<~[int]>(), box [20, 15, 10, 5]);
assert_eq!(range_step(20i, 0, -6).collect::<~[int]>(), box [20, 14, 8, 2]);
assert_eq!(range_step(200u8, 255, 50).collect::<~[u8]>(), box [200u8, 250]);
assert_eq!(range_step(200, -5, 1).collect::<~[int]>(), box []);
assert_eq!(range_step(200, 200, 1).collect::<~[int]>(), box []);
assert_eq!(range_step(0i, 20, 5).collect::<Vec<int>>(), vec![0, 5, 10, 15]);
assert_eq!(range_step(20i, 0, -5).collect::<Vec<int>>(), vec![20, 15, 10, 5]);
assert_eq!(range_step(20i, 0, -6).collect::<Vec<int>>(), vec![20, 14, 8, 2]);
assert_eq!(range_step(200u8, 255, 50).collect::<Vec<u8>>(), vec![200u8, 250]);
assert_eq!(range_step(200, -5, 1).collect::<Vec<int>>(), vec![]);
assert_eq!(range_step(200, 200, 1).collect::<Vec<int>>(), vec![]);
}
#[test]
fn test_range_step_inclusive() {
assert_eq!(range_step_inclusive(0i, 20, 5).collect::<~[int]>(), box [0, 5, 10, 15, 20]);
assert_eq!(range_step_inclusive(20i, 0, -5).collect::<~[int]>(), box [20, 15, 10, 5, 0]);
assert_eq!(range_step_inclusive(20i, 0, -6).collect::<~[int]>(), box [20, 14, 8, 2]);
assert_eq!(range_step_inclusive(200u8, 255, 50).collect::<~[u8]>(), box [200u8, 250]);
assert_eq!(range_step_inclusive(200, -5, 1).collect::<~[int]>(), box []);
assert_eq!(range_step_inclusive(200, 200, 1).collect::<~[int]>(), box [200]);
assert_eq!(range_step_inclusive(0i, 20, 5).collect::<Vec<int>>(), vec![0, 5, 10, 15, 20]);
assert_eq!(range_step_inclusive(20i, 0, -5).collect::<Vec<int>>(), vec![20, 15, 10, 5, 0]);
assert_eq!(range_step_inclusive(20i, 0, -6).collect::<Vec<int>>(), vec![20, 14, 8, 2]);
assert_eq!(range_step_inclusive(200u8, 255, 50).collect::<Vec<u8>>(), vec![200u8, 250]);
assert_eq!(range_step_inclusive(200, -5, 1).collect::<Vec<int>>(), vec![]);
assert_eq!(range_step_inclusive(200, 200, 1).collect::<Vec<int>>(), vec![200]);
}
#[test]

View File

@ -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![]
}

View File

@ -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<Vec<int>> = collect(range(0, 0)
.map(|_| Some(0)));
assert_eq!(v, Some(vec![]));
let v: Option<~[int]> = collect(range(0, 3)
.map(|x| Some(x)));
assert_eq!(v, Some(box [0, 1, 2]));
let v: Option<Vec<int>> = collect(range(0, 3)
.map(|x| Some(x)));
assert_eq!(v, Some(vec![0, 1, 2]));
let v: Option<~[int]> = collect(range(0, 3)
.map(|x| if x > 1 { None } else { Some(x) }));
let v: Option<Vec<int>> = collect(range(0, 3)
.map(|x| if x > 1 { None } else { Some(x) }));
assert_eq!(v, None);
// test that it does not take more elements than it needs
let mut functions = [|| Some(()), || None, || fail!()];
let v: Option<~[()]> = collect(functions.mut_iter().map(|f| (*f)()));
let v: Option<Vec<()>> = collect(functions.mut_iter().map(|f| (*f)()));
assert_eq!(v, None);
}

View File

@ -653,20 +653,20 @@ mod tests {
#[test]
fn test_collect() {
let v: Result<~[int], ()> = collect(range(0, 0).map(|_| Ok::<int, ()>(0)));
assert_eq!(v, Ok(box []));
let v: Result<Vec<int>, ()> = collect(range(0, 0).map(|_| Ok::<int, ()>(0)));
assert_eq!(v, Ok(vec![]));
let v: Result<~[int], ()> = collect(range(0, 3).map(|x| Ok::<int, ()>(x)));
assert_eq!(v, Ok(box [0, 1, 2]));
let v: Result<Vec<int>, ()> = collect(range(0, 3).map(|x| Ok::<int, ()>(x)));
assert_eq!(v, Ok(vec![0, 1, 2]));
let v: Result<~[int], int> = collect(range(0, 3)
.map(|x| if x > 1 { Err(x) } else { Ok(x) }));
let v: Result<Vec<int>, int> = collect(range(0, 3)
.map(|x| if x > 1 { Err(x) } else { Ok(x) }));
assert_eq!(v, Err(2));
// test that it does not take more elements than it needs
let mut functions = [|| Ok(()), || Err(1), || fail!()];
let v: Result<~[()], int> = collect(functions.mut_iter().map(|f| (*f)()));
let v: Result<Vec<()>, int> = collect(functions.mut_iter().map(|f| (*f)()));
assert_eq!(v, Err(1));
}

View File

@ -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<A: Clone> Clone for ~[A] {
#[inline]
fn clone(&self) -> ~[A] {
self.iter().map(|a| a.clone()).collect()
}
}
impl<A> FromIterator<A> for ~[A] {
fn from_iter<T: Iterator<A>>(mut iterator: T) -> ~[A] {
let (lower, _) = iterator.size_hint();
let cap = if lower == 0 {16} else {lower};
let mut cap = cap.checked_mul(&mem::size_of::<A>()).unwrap();
let mut len = 0;
let len = self.len();
let data_size = len.checked_mul(&mem::size_of::<A>()).unwrap();
let size = mem::size_of::<Vec<()>>().checked_add(&data_size).unwrap();
unsafe {
let mut ptr = alloc(cap) as *mut Vec<A>;
let mut ret = cast::transmute(ptr);
for elt in iterator {
if len * mem::size_of::<A>() >= cap {
cap = cap.checked_mul(&2).unwrap();
let ptr2 = alloc(cap) as *mut Vec<A>;
ptr::copy_nonoverlapping_memory(&mut (*ptr2).data,
&(*ptr).data,
len);
free(ptr as *u8);
cast::forget(ret);
ret = cast::transmute(ptr2);
ptr = ptr2;
}
let ret = alloc(size) as *mut Vec<A>;
let base = &mut (*ptr).data as *mut A;
intrinsics::move_val_init(&mut *base.offset(len as int), elt);
len += 1;
(*ptr).fill = len * mem::nonzero_size_of::<A>();
}
ret
(*ret).fill = len * mem::nonzero_size_of::<A>();
(*ret).alloc = len * mem::nonzero_size_of::<A>();
let mut i = 0;
let p = &mut (*ret).data as *mut _ as *mut A;
try_finally(
&mut i, (),
|i, ()| while *i < len {
mem::move_val_init(
&mut(*p.offset(*i as int)),
self.unsafe_ref(*i).clone());
*i += 1;
},
|i| if *i < len {
// we must be failing, clean up after ourselves
for j in range(0, *i as int) {
ptr::read(&*p.offset(j));
}
free(ret as *u8);
});
cast::transmute(ret)
}
}
}
#[cfg(not(test))]
impl<'a,T:Clone, V: Vector<T>> Add<V, ~[T]> for &'a [T] {
#[inline]
fn add(&self, rhs: &V) -> ~[T] {
let first = self.iter().map(|t| t.clone());
first.chain(rhs.as_slice().iter().map(|t| t.clone())).collect()
}
}
#[cfg(not(test))]
impl<T:Clone, V: Vector<T>> Add<V, ~[T]> for ~[T] {
#[inline]
fn add(&self, rhs: &V) -> ~[T] {
self.as_slice() + rhs.as_slice()
}
}

View File

@ -621,12 +621,12 @@ impl<'a> Iterator<UTF16Item> 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<_>>(),
/// vec![ScalarValue('𝄞'),
/// ScalarValue('m'), ScalarValue('u'), ScalarValue('s'),
/// LoneSurrogate(0xDD1E),
/// ScalarValue('i'), ScalarValue('c'),
/// LoneSurrogate(0xD834)]);
/// ```
pub fn utf16_items<'a>(v: &'a [u16]) -> UTF16Items<'a> {
UTF16Items { iter : v.iter() }
@ -896,8 +896,8 @@ pub trait StrSlice<'a> {
/// # Example
///
/// ```rust
/// let v: ~[char] = "abc åäö".chars().collect();
/// assert_eq!(v, ~['a', 'b', 'c', ' ', 'å', 'ä', 'ö']);
/// let v: Vec<char> = "abc åäö".chars().collect();
/// assert_eq!(v, vec!['a', 'b', 'c', ' ', 'å', 'ä', 'ö']);
/// ```
fn chars(&self) -> Chars<'a>;
@ -925,14 +925,14 @@ pub trait StrSlice<'a> {
/// # Example
///
/// ```rust
/// let v: ~[&str] = "Mary had a little lamb".split(' ').collect();
/// assert_eq!(v, ~["Mary", "had", "a", "little", "lamb"]);
/// let v: Vec<&str> = "Mary had a little lamb".split(' ').collect();
/// assert_eq!(v, vec!["Mary", "had", "a", "little", "lamb"]);
///
/// let v: ~[&str] = "abc1def2ghi".split(|c: char| c.is_digit()).collect();
/// assert_eq!(v, ~["abc", "def", "ghi"]);
/// let v: Vec<&str> = "abc1def2ghi".split(|c: char| c.is_digit()).collect();
/// assert_eq!(v, vec!["abc", "def", "ghi"]);
///
/// let v: ~[&str] = "lionXXtigerXleopard".split('X').collect();
/// assert_eq!(v, ~["lion", "", "tiger", "leopard"]);
/// let v: Vec<&str> = "lionXXtigerXleopard".split('X').collect();
/// assert_eq!(v, vec!["lion", "", "tiger", "leopard"]);
/// ```
fn split<Sep: CharEq>(&self, sep: Sep) -> CharSplits<'a, Sep>;
@ -943,14 +943,14 @@ pub trait StrSlice<'a> {
/// # Example
///
/// ```rust
/// let v: ~[&str] = "Mary had a little lambda".splitn(' ', 2).collect();
/// assert_eq!(v, ~["Mary", "had", "a little lambda"]);
/// let v: Vec<&str> = "Mary had a little lambda".splitn(' ', 2).collect();
/// assert_eq!(v, vec!["Mary", "had", "a little lambda"]);
///
/// let v: ~[&str] = "abc1def2ghi".splitn(|c: char| c.is_digit(), 1).collect();
/// assert_eq!(v, ~["abc", "def2ghi"]);
/// let v: Vec<&str> = "abc1def2ghi".splitn(|c: char| c.is_digit(), 1).collect();
/// assert_eq!(v, vec!["abc", "def2ghi"]);
///
/// let v: ~[&str] = "lionXXtigerXleopard".splitn('X', 2).collect();
/// assert_eq!(v, ~["lion", "", "tigerXleopard"]);
/// let v: Vec<&str> = "lionXXtigerXleopard".splitn('X', 2).collect();
/// assert_eq!(v, vec!["lion", "", "tigerXleopard"]);
/// ```
fn splitn<Sep: CharEq>(&self, sep: Sep, count: uint) -> CharSplitsN<'a, Sep>;
@ -963,20 +963,20 @@ pub trait StrSlice<'a> {
/// # Example
///
/// ```rust
/// let v: ~[&str] = "A.B.".split_terminator('.').collect();
/// assert_eq!(v, ~["A", "B"]);
/// let v: Vec<&str> = "A.B.".split_terminator('.').collect();
/// assert_eq!(v, vec!["A", "B"]);
///
/// let v: ~[&str] = "A..B..".split_terminator('.').collect();
/// assert_eq!(v, ~["A", "", "B", ""]);
/// let v: Vec<&str> = "A..B..".split_terminator('.').collect();
/// assert_eq!(v, vec!["A", "", "B", ""]);
///
/// let v: ~[&str] = "Mary had a little lamb".split(' ').rev().collect();
/// assert_eq!(v, ~["lamb", "little", "a", "had", "Mary"]);
/// let v: Vec<&str> = "Mary had a little lamb".split(' ').rev().collect();
/// assert_eq!(v, vec!["lamb", "little", "a", "had", "Mary"]);
///
/// let v: ~[&str] = "abc1def2ghi".split(|c: char| c.is_digit()).rev().collect();
/// assert_eq!(v, ~["ghi", "def", "abc"]);
/// let v: Vec<&str> = "abc1def2ghi".split(|c: char| c.is_digit()).rev().collect();
/// assert_eq!(v, vec!["ghi", "def", "abc"]);
///
/// let v: ~[&str] = "lionXXtigerXleopard".split('X').rev().collect();
/// assert_eq!(v, ~["leopard", "tiger", "", "lion"]);
/// let v: Vec<&str> = "lionXXtigerXleopard".split('X').rev().collect();
/// assert_eq!(v, vec!["leopard", "tiger", "", "lion"]);
/// ```
fn split_terminator<Sep: CharEq>(&self, sep: Sep) -> CharSplits<'a, Sep>;
@ -991,14 +991,14 @@ pub trait StrSlice<'a> {
/// # Example
///
/// ```rust
/// let v: ~[&str] = "Mary had a little lamb".rsplitn(' ', 2).collect();
/// assert_eq!(v, ~["lamb", "little", "Mary had a"]);
/// let v: Vec<&str> = "Mary had a little lamb".rsplitn(' ', 2).collect();
/// assert_eq!(v, vec!["lamb", "little", "Mary had a"]);
///
/// let v: ~[&str] = "abc1def2ghi".rsplitn(|c: char| c.is_digit(), 1).collect();
/// assert_eq!(v, ~["ghi", "abc1def"]);
/// let v: Vec<&str> = "abc1def2ghi".rsplitn(|c: char| c.is_digit(), 1).collect();
/// assert_eq!(v, vec!["ghi", "abc1def"]);
///
/// let v: ~[&str] = "lionXXtigerXleopard".rsplitn('X', 2).collect();
/// assert_eq!(v, ~["leopard", "tiger", "lionX"]);
/// let v: Vec<&str> = "lionXXtigerXleopard".rsplitn('X', 2).collect();
/// assert_eq!(v, vec!["leopard", "tiger", "lionX"]);
/// ```
fn rsplitn<Sep: CharEq>(&self, sep: Sep, count: uint) -> CharSplitsN<'a, Sep>;
@ -1013,14 +1013,14 @@ pub trait StrSlice<'a> {
/// # Example
///
/// ```rust
/// let v: ~[(uint, uint)] = "abcXXXabcYYYabc".match_indices("abc").collect();
/// assert_eq!(v, ~[(0,3), (6,9), (12,15)]);
/// let v: Vec<(uint, uint)> = "abcXXXabcYYYabc".match_indices("abc").collect();
/// assert_eq!(v, vec![(0,3), (6,9), (12,15)]);
///
/// let v: ~[(uint, uint)] = "1abcabc2".match_indices("abc").collect();
/// assert_eq!(v, ~[(1,4), (4,7)]);
/// let v: Vec<(uint, uint)> = "1abcabc2".match_indices("abc").collect();
/// assert_eq!(v, vec![(1,4), (4,7)]);
///
/// let v: ~[(uint, uint)] = "ababa".match_indices("aba").collect();
/// assert_eq!(v, ~[(0, 3)]); // only the first `aba`
/// let v: Vec<(uint, uint)> = "ababa".match_indices("aba").collect();
/// assert_eq!(v, vec![(0, 3)]); // only the first `aba`
/// ```
fn match_indices(&self, sep: &'a str) -> MatchIndices<'a>;
@ -1029,11 +1029,11 @@ pub trait StrSlice<'a> {
/// # Example
///
/// ```rust
/// let v: ~[&str] = "abcXXXabcYYYabc".split_str("abc").collect();
/// assert_eq!(v, ~["", "XXX", "YYY", ""]);
/// let v: Vec<&str> = "abcXXXabcYYYabc".split_str("abc").collect();
/// assert_eq!(v, vec!["", "XXX", "YYY", ""]);
///
/// let v: ~[&str] = "1abcabc2".split_str("abc").collect();
/// assert_eq!(v, ~["1", "", "2"]);
/// let v: Vec<&str> = "1abcabc2".split_str("abc").collect();
/// assert_eq!(v, vec!["1", "", "2"]);
/// ```
fn split_str(&self, &'a str) -> StrSplits<'a>;
@ -1045,8 +1045,8 @@ pub trait StrSlice<'a> {
///
/// ```rust
/// let four_lines = "foo\nbar\n\nbaz\n";
/// let v: ~[&str] = four_lines.lines().collect();
/// assert_eq!(v, ~["foo", "bar", "", "baz"]);
/// let v: Vec<&str> = four_lines.lines().collect();
/// assert_eq!(v, vec!["foo", "bar", "", "baz"]);
/// ```
fn lines(&self) -> CharSplits<'a, char>;
@ -1058,8 +1058,8 @@ pub trait StrSlice<'a> {
///
/// ```rust
/// let four_lines = "foo\r\nbar\n\r\nbaz\n";
/// let v: ~[&str] = four_lines.lines_any().collect();
/// assert_eq!(v, ~["foo", "bar", "", "baz"]);
/// let v: Vec<&str> = four_lines.lines_any().collect();
/// assert_eq!(v, vec!["foo", "bar", "", "baz"]);
/// ```
fn lines_any(&self) -> AnyLines<'a>;
@ -1071,8 +1071,8 @@ pub trait StrSlice<'a> {
///
/// ```rust
/// let some_words = " Mary had\ta little \n\t lamb";
/// let v: ~[&str] = some_words.words().collect();
/// assert_eq!(v, ~["Mary", "had", "a", "little", "lamb"]);
/// let v: Vec<&str> = some_words.words().collect();
/// assert_eq!(v, vec!["Mary", "had", "a", "little", "lamb"]);
/// ```
fn words(&self) -> Words<'a>;
@ -1469,7 +1469,8 @@ pub trait StrSlice<'a> {
///
/// ```rust
/// let string = "a\nb\nc";
/// let lines: ~[&str] = string.lines().collect();
/// let lines: Vec<&str> = string.lines().collect();
/// let lines = lines.as_slice();
///
/// assert!(string.subslice_offset(lines[0]) == 0); // &"a"
/// assert!(string.subslice_offset(lines[1]) == 2); // &"b"

View File

@ -51,7 +51,7 @@
//! fn main() {
//! let args = os::args();
//!
//! let program = args[0].clone();
//! let program = args.get(0).clone();
//!
//! let opts = [
//! optopt("o", "", "set output file name", "NAME"),

View File

@ -22,7 +22,7 @@ pub struct GetAddrInfoRequest;
impl GetAddrInfoRequest {
pub fn run(host: Option<&str>, servname: Option<&str>,
hint: Option<ai::Hint>) -> Result<~[ai::Info], IoError> {
hint: Option<ai::Hint>) -> Result<Vec<ai::Info>, IoError> {
assert!(host.is_some() || servname.is_some());
let c_host = host.map_or(unsafe { CString::new(null(), true) }, |x| x.to_c_str());
@ -80,7 +80,7 @@ impl GetAddrInfoRequest {
unsafe { freeaddrinfo(res); }
Ok(addrs.move_iter().collect())
Ok(addrs)
}
}

View File

@ -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<Vec<Path>> {
if fp_buf as uint == 0 {
fail!("os::list_dir() failure: got null ptr from wfd");
} else {
let fp_vec = slice::from_buf(fp_buf, libc::wcslen(fp_buf) as uint);
let fp_trimmed = str::truncate_utf16_at_nul(fp_vec);
let fp_vec = vec::raw::from_buf(fp_buf, libc::wcslen(fp_buf) as uint);
let fp_trimmed = str::truncate_utf16_at_nul(fp_vec.as_slice());
let fp_str = str::from_utf16(fp_trimmed)
.expect("rust_list_dir_wfd_fp_buf returned invalid UTF-16");
paths.push(Path::new(fp_str));

View File

@ -194,7 +194,7 @@ impl rtio::IoFactory for IoFactory {
})
}
fn get_host_addresses(&mut self, host: Option<&str>, servname: Option<&str>,
hint: Option<ai::Hint>) -> IoResult<~[ai::Info]> {
hint: Option<ai::Hint>) -> IoResult<Vec<ai::Info>> {
addrinfo::GetAddrInfoRequest::run(host, servname, hint)
}
@ -260,7 +260,7 @@ impl rtio::IoFactory for IoFactory {
}
fn spawn(&mut self, config: ProcessConfig)
-> IoResult<(Box<RtioProcess:Send>,
~[Option<Box<RtioPipe:Send>>])> {
Vec<Option<Box<RtioPipe:Send>>>)> {
process::Process::spawn(config).map(|(p, io)| {
(box p as Box<RtioProcess:Send>,
io.move_iter().map(|p| p.map(|p| {

View File

@ -67,7 +67,7 @@ impl Process {
/// os pipe instead. This process takes ownership of these file
/// descriptors, closing them upon destruction of the process.
pub fn spawn(config: p::ProcessConfig)
-> Result<(Process, ~[Option<file::FileDesc>]), io::IoError>
-> Result<(Process, Vec<Option<file::FileDesc>>), io::IoError>
{
// right now we only handle stdin/stdout/stderr.
if config.extra_io.len() > 0 {
@ -117,7 +117,7 @@ impl Process {
exit_code: None,
exit_signal: None,
},
ret_io.move_iter().collect()))
ret_io))
}
Err(e) => Err(e)
}

View File

@ -45,9 +45,9 @@ pub fn get_rpath_flags(sess: &Session, out_filename: &Path) -> Vec<~str> {
let libs = sess.cstore.get_used_crates(cstore::RequireDynamic);
let libs = libs.move_iter().filter_map(|(_, l)| {
l.map(|p| p.clone())
}).collect::<~[_]>();
}).collect::<Vec<_>>();
let rpaths = get_rpaths(os, sysroot, output, libs,
let rpaths = get_rpaths(os, sysroot, output, libs.as_slice(),
sess.opts.target_triple);
flags.push_all(rpaths_to_flags(rpaths.as_slice()).as_slice());
flags

View File

@ -282,7 +282,7 @@ mod __test {
#![!resolve_unexported]
extern crate test (name = "test", vers = "...");
fn main() {
test::test_main_static(::os::args(), tests)
test::test_main_static(::os::args().as_slice(), tests)
}
static tests : &'static [test::TestDescAndFn] = &[
@ -326,8 +326,8 @@ fn mk_test_module(cx: &TestCtxt) -> @ast::Item {
let mainfn = (quote_item!(&cx.ext_cx,
pub fn main() {
#![main]
#![allow(deprecated_owned_vector)]
test::test_main_static(::std::os::args(), TESTS);
use std::slice::Vector;
test::test_main_static(::std::os::args().as_slice(), TESTS);
}
)).unwrap();

View File

@ -434,7 +434,7 @@ pub fn monitor(f: proc():Send) {
}
pub fn main() {
std::os::set_exit_status(main_args(std::os::args()));
std::os::set_exit_status(main_args(std::os::args().as_slice()));
}
pub fn main_args(args: &[~str]) -> int {

View File

@ -226,7 +226,8 @@ fn get_extern_rust_fn(ccx: &CrateContext, inputs: &[ty::t], output: ty::t,
let f = decl_rust_fn(ccx, false, inputs, output, name);
csearch::get_item_attrs(&ccx.sess().cstore, did, |meta_items| {
set_llvm_fn_attrs(meta_items.iter().map(|&x| attr::mk_attr(x)).collect::<~[_]>(), f)
set_llvm_fn_attrs(meta_items.iter().map(|&x| attr::mk_attr(x))
.collect::<Vec<_>>().as_slice(), f)
});
ccx.externs.borrow_mut().insert(name.to_owned(), f);
@ -2109,12 +2110,12 @@ pub fn write_metadata(cx: &CrateContext, krate: &ast::Crate) -> Vec<u8> {
let encode_parms = crate_ctxt_to_encode_parms(cx, encode_inlined_item);
let metadata = encoder::encode_metadata(encode_parms, krate);
let compressed = encoder::metadata_encoding_version +
match flate::deflate_bytes(metadata.as_slice()) {
Some(compressed) => compressed,
None => cx.sess().fatal(format!("failed to compress metadata", ))
}.as_slice();
let llmeta = C_bytes(cx, compressed);
let compressed = Vec::from_slice(encoder::metadata_encoding_version)
.append(match flate::deflate_bytes(metadata.as_slice()) {
Some(compressed) => compressed,
None => cx.sess().fatal(format!("failed to compress metadata"))
}.as_slice());
let llmeta = C_bytes(cx, compressed.as_slice());
let llconst = C_struct(cx, [llmeta], false);
let name = format!("rust_metadata_{}_{}_{}", cx.link_meta.crateid.name,
cx.link_meta.crateid.version_or_default(), cx.link_meta.crate_hash);

View File

@ -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))
})
}

View File

@ -157,12 +157,13 @@ pub fn monomorphic_fn(ccx: &CrateContext,
// This is a bit unfortunate.
let idx = real_substs.tps.len() - num_method_ty_params;
let substs = real_substs.tps.slice(0, idx) +
&[real_substs.self_ty.unwrap()] + real_substs.tps.tailn(idx);
let substs = Vec::from_slice(real_substs.tps.slice(0, idx))
.append([real_substs.self_ty.unwrap()])
.append(real_substs.tps.tailn(idx));
debug!("static default: changed substitution to {}",
substs.repr(ccx.tcx()));
ty::subst_tps(ccx.tcx(), substs, None, llitem_ty)
ty::subst_tps(ccx.tcx(), substs.as_slice(), None, llitem_ty)
}
};

View File

@ -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::<Vec<~str>>().connect(" + ")
},
arrow = match decl.decl.output { clean::Unit => "no", _ => "yes" },
ret = decl.decl.output)

View File

@ -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());

View File

@ -85,7 +85,7 @@ local_data_key!(pub analysiskey: core::CrateAnalysis)
type Output = (clean::Crate, Vec<plugins::PluginJson> );
pub fn main() {
std::os::set_exit_status(main_args(std::os::args()));
std::os::set_exit_status(main_args(std::os::args().as_slice()));
}
pub fn opts() -> Vec<getopts::OptGroup> {

View File

@ -33,7 +33,7 @@ pub struct GetAddrInfoRequest;
impl GetAddrInfoRequest {
pub fn run(loop_: &Loop, node: Option<&str>, service: Option<&str>,
hints: Option<ai::Hint>) -> Result<~[ai::Info], UvError> {
hints: Option<ai::Hint>) -> Result<Vec<ai::Info>, UvError> {
assert!(node.is_some() || service.is_some());
let (_c_node, c_node_ptr) = match node {
Some(n) => {
@ -134,7 +134,7 @@ fn each_ai_flag(_f: |c_int, ai::Flag|) {
}
// Traverse the addrinfo linked list, producing a vector of Rust socket addresses
pub fn accum_addrinfo(addr: &Addrinfo) -> ~[ai::Info] {
pub fn accum_addrinfo(addr: &Addrinfo) -> Vec<ai::Info> {
unsafe {
let mut addr = addr.handle;
@ -180,6 +180,6 @@ pub fn accum_addrinfo(addr: &Addrinfo) -> ~[ai::Info] {
}
}
return addrs.move_iter().collect();
addrs
}
}

View File

@ -40,7 +40,8 @@ impl Process {
/// Returns either the corresponding process object or an error which
/// occurred.
pub fn spawn(io_loop: &mut UvIoFactory, config: process::ProcessConfig)
-> Result<(Box<Process>, ~[Option<PipeWatcher>]), UvError> {
-> Result<(Box<Process>, Vec<Option<PipeWatcher>>), UvError>
{
let cwd = config.cwd.map(|s| s.to_c_str());
let mut io = vec![config.stdin, config.stdout, config.stderr];
for slot in config.extra_io.iter() {
@ -102,7 +103,7 @@ impl Process {
});
match ret {
Ok(p) => Ok((p, ret_io.move_iter().collect())),
Ok(p) => Ok((p, ret_io)),
Err(e) => Err(e),
}
}

View File

@ -178,7 +178,7 @@ impl IoFactory for UvIoFactory {
}
fn get_host_addresses(&mut self, host: Option<&str>, servname: Option<&str>,
hint: Option<ai::Hint>) -> Result<~[ai::Info], IoError> {
hint: Option<ai::Hint>) -> Result<Vec<ai::Info>, IoError> {
let r = GetAddrInfoRequest::run(&self.loop_, host, servname, hint);
r.map_err(uv_error_to_io_error)
}
@ -272,7 +272,7 @@ impl IoFactory for UvIoFactory {
fn spawn(&mut self, config: ProcessConfig)
-> Result<(Box<rtio::RtioProcess:Send>,
~[Option<Box<rtio::RtioPipe:Send>>]),
Vec<Option<Box<rtio::RtioPipe:Send>>>),
IoError>
{
match Process::spawn(self, config) {

View File

@ -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<Vec<u8>, FromBase64Error>;
}
/// Errors that can occur when decoding a base64 encoded string
@ -192,14 +192,13 @@ impl<'a> FromBase64 for &'a str {
* ```rust
* extern crate serialize;
* use serialize::base64::{ToBase64, FromBase64, STANDARD};
* use std::str;
*
* fn main () {
* let hello_str = bytes!("Hello, World").to_base64(STANDARD);
* println!("base64 output: {}", hello_str);
* let res = hello_str.from_base64();
* if res.is_ok() {
* let opt_bytes = str::from_utf8_owned(res.unwrap());
* let opt_bytes = StrBuf::from_utf8(res.unwrap());
* if opt_bytes.is_some() {
* println!("decoded from base64: {}", opt_bytes.unwrap());
* }
@ -207,7 +206,7 @@ impl<'a> FromBase64 for &'a str {
* }
* ```
*/
fn from_base64(&self) -> Result<~[u8], FromBase64Error> {
fn from_base64(&self) -> Result<Vec<u8>, FromBase64Error> {
let mut r = Vec::new();
let mut buf: u32 = 0;
let mut modulus = 0;
@ -256,7 +255,7 @@ 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::<u8>());
assert_eq!(v.as_slice().to_base64(STANDARD).from_base64().unwrap(),
v.as_slice().to_owned());
assert_eq!(v.as_slice().to_base64(STANDARD).from_base64().unwrap().as_slice(),
v.as_slice());
}
}

View File

@ -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<Vec<u8>, FromHexError>;
}
/// Errors that can occur when decoding a hex encoded string
@ -91,19 +91,18 @@ impl<'a> FromHex for &'a str {
* ```rust
* extern crate serialize;
* use serialize::hex::{FromHex, ToHex};
* use std::str;
*
* fn main () {
* let hello_str = "Hello, World".as_bytes().to_hex();
* println!("{}", hello_str);
* let bytes = hello_str.from_hex().unwrap();
* println!("{:?}", bytes);
* let result_str = str::from_utf8_owned(bytes).unwrap();
* let result_str = StrBuf::from_utf8(bytes).unwrap();
* println!("{}", result_str);
* }
* ```
*/
fn from_hex(&self) -> Result<~[u8], FromHexError> {
fn from_hex(&self) -> Result<Vec<u8>, FromHexError> {
// This may be an overestimate if there is any whitespace
let mut b = Vec::with_capacity(self.len() / 2);
let mut modulus = 0;
@ -150,10 +149,10 @@ 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]);
}
}

View File

@ -166,14 +166,14 @@ use serialize::{json, Encodable, Decodable};
pub struct TestStruct1 {
data_int: u8,
data_str: ~str,
data_vector: ~[u8],
data_vector: Vec<u8>,
}
// To serialize use the `json::str_encode` to encode an object in a string.
// It calls the generated `Encodable` impl.
fn main() {
let to_encode_object = TestStruct1
{data_int: 1, data_str:"toto".to_owned(), data_vector:~[2,3,4,5]};
{data_int: 1, data_str:"toto".to_owned(), data_vector:vec![2,3,4,5]};
let encoded_str: ~str = json::Encoder::str_encode(&to_encode_object);
// To deserialize use the `json::from_str` and `json::Decoder`
@ -201,7 +201,7 @@ use collections::TreeMap;
pub struct TestStruct1 {
data_int: u8,
data_str: ~str,
data_vector: ~[u8],
data_vector: Vec<u8>,
}
impl ToJson for TestStruct1 {
@ -218,7 +218,7 @@ fn main() {
// Serialization using our impl of to_json
let test2: TestStruct1 = TestStruct1 {data_int: 1, data_str:"toto".to_owned(),
data_vector:~[2,3,4,5]};
data_vector:vec![2,3,4,5]};
let tjson: json::Json = test2.to_json();
let json_str: ~str = tjson.to_str();
@ -258,7 +258,7 @@ pub enum Json {
Null,
}
pub type List = ~[Json];
pub type List = Vec<Json>;
pub type Object = TreeMap<~str, Json>;
/// The errors that can arise while parsing a JSON stream.
@ -2211,7 +2211,7 @@ impl<A:ToJson,B:ToJson> ToJson for (A, B) {
fn to_json(&self) -> Json {
match *self {
(ref a, ref b) => {
List(box [a.to_json(), b.to_json()])
List(vec![a.to_json(), b.to_json()])
}
}
}
@ -2221,7 +2221,7 @@ impl<A:ToJson,B:ToJson,C:ToJson> ToJson for (A, B, C) {
fn to_json(&self) -> Json {
match *self {
(ref a, ref b, ref c) => {
List(box [a.to_json(), b.to_json(), c.to_json()])
List(vec![a.to_json(), b.to_json(), c.to_json()])
}
}
}
@ -2298,12 +2298,12 @@ mod tests {
struct Inner {
a: (),
b: uint,
c: ~[~str],
c: Vec<~str>,
}
#[deriving(Eq, Encodable, Decodable, Show)]
struct Outer {
inner: ~[Inner],
inner: Vec<Inner>,
}
fn mk_object(items: &[(~str, Json)]) -> Json {
@ -2360,22 +2360,22 @@ 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<bool> = Decodable::decode(&mut decoder).unwrap();
assert_eq!(v, vec![true]);
let mut decoder = Decoder::new(from_str("[true]").unwrap());
let v: ~[bool] = Decodable::decode(&mut decoder).unwrap();
assert_eq!(v, ~[true]);
let v: Vec<bool> = Decodable::decode(&mut decoder).unwrap();
assert_eq!(v, vec![true]);
let mut decoder = Decoder::new(from_str("[3, 1]").unwrap());
let v: ~[int] = Decodable::decode(&mut decoder).unwrap();
assert_eq!(v, ~[3, 1]);
let v: Vec<int> = Decodable::decode(&mut decoder).unwrap();
assert_eq!(v, vec![3, 1]);
let mut decoder = Decoder::new(from_str("[[3], [1, 2]]").unwrap());
let v: ~[~[uint]] = Decodable::decode(&mut decoder).unwrap();
assert_eq!(v, ~[~[3], ~[1, 2]]);
let v: Vec<Vec<uint>> = Decodable::decode(&mut decoder).unwrap();
assert_eq!(v, vec![vec![3], vec![1, 2]]);
}
#[test]
@ -2750,7 +2750,7 @@ 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<DecodeStruct>
}
#[deriving(Decodable)]
enum DecodeEnum {

View File

@ -453,12 +453,14 @@ impl<E, S:Encoder<E>,T:Encodable<S, E>> Encodable<S, E> for ~[T] {
impl<E, D:Decoder<E>,T:Decodable<D, E>> Decodable<D, E> for ~[T] {
fn decode(d: &mut D) -> Result<~[T], E> {
use std::vec::FromVec;
d.read_seq(|d, len| {
let mut v: Vec<T> = Vec::with_capacity(len);
for i in range(0, len) {
v.push(try!(d.read_seq_elt(i, |d| Decodable::decode(d))));
}
let k = v.move_iter().collect::<~[T]>();
let k: ~[T] = FromVec::from_vec(v);
Ok(k)
})
}
@ -557,7 +559,7 @@ impl<E, S: Encoder<E>> Encodable<S, E> for path::posix::Path {
impl<E, D: Decoder<E>> Decodable<D, E> for path::posix::Path {
fn decode(d: &mut D) -> Result<path::posix::Path, E> {
let bytes: ~[u8] = try!(Decodable::decode(d));
let bytes: Vec<u8> = try!(Decodable::decode(d));
Ok(path::posix::Path::new(bytes))
}
}
@ -570,7 +572,7 @@ impl<E, S: Encoder<E>> Encodable<S, E> for path::windows::Path {
impl<E, D: Decoder<E>> Decodable<D, E> for path::windows::Path {
fn decode(d: &mut D) -> Result<path::windows::Path, E> {
let bytes: ~[u8] = try!(Decodable::decode(d));
let bytes: Vec<u8> = try!(Decodable::decode(d));
Ok(path::windows::Path::new(bytes))
}
}
@ -600,17 +602,17 @@ impl<E, S:Encoder<E>> EncoderHelpers<E> for S {
}
pub trait DecoderHelpers<E> {
fn read_to_vec<T>(&mut self, f: |&mut Self| -> Result<T, E>) -> Result<~[T], E>;
fn read_to_vec<T>(&mut self, f: |&mut Self| -> Result<T, E>) -> Result<Vec<T>, E>;
}
impl<E, D:Decoder<E>> DecoderHelpers<E> for D {
fn read_to_vec<T>(&mut self, f: |&mut D| -> Result<T, E>) -> Result<~[T], E> {
fn read_to_vec<T>(&mut self, f: |&mut D| -> Result<T, E>) -> Result<Vec<T>, E> {
self.read_seq(|this, len| {
let mut v = Vec::with_capacity(len);
for i in range(0, len) {
v.push(try!(this.read_seq_elt(i, |this| f(this))));
}
Ok(v.move_iter().collect())
Ok(v)
})
}
}

View File

@ -13,7 +13,7 @@
use to_str::{IntoStr};
use str;
use str::Str;
use str::StrSlice;
use str::{StrAllocating, StrSlice};
use str::OwnedStr;
use container::Container;
use cast;
@ -217,14 +217,14 @@ pub trait OwnedAsciiCast {
/// Take ownership and cast to an ascii vector. Fail on non-ASCII input.
#[inline]
fn into_ascii(self) -> ~[Ascii] {
fn into_ascii(self) -> Vec<Ascii> {
assert!(self.is_ascii());
unsafe {self.into_ascii_nocheck()}
}
/// Take ownership and cast to an ascii vector. Return None on non-ASCII input.
#[inline]
fn into_ascii_opt(self) -> Option<~[Ascii]> {
fn into_ascii_opt(self) -> Option<Vec<Ascii>> {
if self.is_ascii() {
Some(unsafe { self.into_ascii_nocheck() })
} else {
@ -234,7 +234,7 @@ 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<Ascii>;
}
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<Ascii> {
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<Ascii> {
let v: ~[u8] = cast::transmute(self);
v.into_ascii_nocheck()
}
}
impl OwnedAsciiCast for Vec<u8> {
#[inline]
fn is_ascii(&self) -> bool {
self.as_slice().is_ascii()
}
#[inline]
unsafe fn into_ascii_nocheck(self) -> Vec<Ascii> {
cast::transmute(self)
}
}
@ -268,10 +281,10 @@ pub trait AsciiStr {
fn as_str_ascii<'a>(&'a self) -> &'a str;
/// Convert to vector representing a lower cased ascii string.
fn to_lower(&self) -> ~[Ascii];
fn to_lower(&self) -> Vec<Ascii>;
/// Convert to vector representing a upper cased ascii string.
fn to_upper(&self) -> ~[Ascii];
fn to_upper(&self) -> Vec<Ascii>;
/// Compares two Ascii strings ignoring case.
fn eq_ignore_case(self, other: &[Ascii]) -> bool;
@ -284,12 +297,12 @@ impl<'a> AsciiStr for &'a [Ascii] {
}
#[inline]
fn to_lower(&self) -> ~[Ascii] {
fn to_lower(&self) -> Vec<Ascii> {
self.iter().map(|a| a.to_lower()).collect()
}
#[inline]
fn to_upper(&self) -> ~[Ascii] {
fn to_upper(&self) -> Vec<Ascii> {
self.iter().map(|a| a.to_upper()).collect()
}
@ -309,19 +322,21 @@ impl IntoStr for ~[Ascii] {
impl IntoStr for Vec<Ascii> {
#[inline]
fn into_str(self) -> ~str {
let v: ~[Ascii] = self.move_iter().collect();
unsafe { cast::transmute(v) }
unsafe {
let s: &str = cast::transmute(self.as_slice());
s.to_owned()
}
}
}
/// Trait to convert to an owned byte array by consuming self
/// Trait to convert to an owned byte vector by consuming self
pub trait IntoBytes {
/// Converts to an owned byte array by consuming self
fn into_bytes(self) -> ~[u8];
/// Converts to an owned byte vector by consuming self
fn into_bytes(self) -> Vec<u8>;
}
impl IntoBytes for ~[Ascii] {
fn into_bytes(self) -> ~[u8] {
impl IntoBytes for Vec<Ascii> {
fn into_bytes(self) -> Vec<u8> {
unsafe { cast::transmute(self) }
}
}
@ -404,9 +419,11 @@ unsafe fn str_map_bytes(string: ~str, map: &'static [u8]) -> ~str {
#[inline]
unsafe fn str_copy_map_bytes(string: &str, map: &'static [u8]) -> ~str {
let bytes = string.bytes().map(|b| map[b as uint]).collect::<~[_]>();
str::raw::from_utf8_owned(bytes)
let mut s = string.to_owned();
for b in str::raw::as_owned_vec(&mut s).mut_iter() {
*b = map[*b as uint];
}
s
}
static ASCII_LOWER_MAP: &'static [u8] = &[
@ -492,7 +509,6 @@ mod tests {
macro_rules! v2ascii (
( [$($e:expr),*]) => (&[$(Ascii{chr:$e}),*]);
(&[$($e:expr),*]) => (&[$(Ascii{chr:$e}),*]);
(~[$($e:expr),*]) => (box [$(Ascii{chr:$e}),*]);
)
macro_rules! vec2ascii (
@ -556,20 +572,17 @@ 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);
}

View File

@ -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

View File

@ -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<Vec<IpAddr>> {
lookup(Some(host), None, None).map(|a| a.move_iter().map(|i| i.address.ip).collect())
}
@ -90,7 +90,7 @@ pub fn get_host_addresses(host: &str) -> IoResult<~[IpAddr]> {
/// FIXME: this is not public because the `Hint` structure is not ready for public
/// consumption just yet.
fn lookup(hostname: Option<&str>, servname: Option<&str>, hint: Option<Hint>)
-> IoResult<~[Info]> {
-> IoResult<Vec<Info>> {
LocalIo::maybe_raise(|io| io.get_host_addresses(hostname, servname, hint))
}

View File

@ -69,7 +69,7 @@ pub struct Process {
/// Extra I/O handles as configured by the original `ProcessConfig` when
/// this process was created. This is by default empty.
pub extra_io: ~[Option<io::PipeStream>],
pub extra_io: Vec<Option<io::PipeStream>>,
}
/// This configuration describes how a new process should be spawned. A blank
@ -418,7 +418,7 @@ 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();
}

View File

@ -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;
}

View File

@ -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};

View File

@ -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};

View File

@ -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};

View File

@ -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};

View File

@ -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};

View File

@ -77,13 +77,16 @@ impl ToStrRadix for $T {
/// Convert to a string in a given base.
#[inline]
fn to_str_radix(&self, radix: uint) -> ~str {
use slice::Vector;
use str::StrAllocating;
let mut buf = ::vec::Vec::new();
strconv::int_to_str_bytes_common(*self, radix, strconv::SignNeg, |i| {
buf.push(i);
});
// We know we generated valid utf-8, so we don't need to go through that
// check.
unsafe { str::raw::from_utf8_owned(buf.move_iter().collect()) }
unsafe { str::raw::from_utf8(buf.as_slice()).to_owned() }
}
}

View File

@ -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<T:NumCast+Zero+One+Eq+Ord+Float+
Div<T,T>+Neg<T>+Rem<T,T>+Mul<T,T>>(
num: T, radix: uint, negative_zero: bool,
sign: SignFormat, digits: SignificantDigits, exp_format: ExponentFormat, exp_upper: bool
) -> (~[u8], bool) {
) -> (Vec<u8>, bool) {
assert!(2 <= radix && radix <= 36);
match exp_format {
ExpDec if radix >= DIGIT_E_RADIX // decimal exponent 'e'
@ -278,17 +277,17 @@ pub fn float_to_str_bytes_common<T:NumCast+Zero+One+Eq+Ord+Float+
let _1: T = One::one();
match num.classify() {
FPNaN => { return ("NaN".as_bytes().to_owned(), true); }
FPNaN => { return (Vec::from_slice("NaN".as_bytes()), true); }
FPInfinite if num > _0 => {
return match sign {
SignAll => ("+inf".as_bytes().to_owned(), true),
_ => ("inf".as_bytes().to_owned(), true)
SignAll => (Vec::from_slice("+inf".as_bytes()), true),
_ => (Vec::from_slice("inf".as_bytes()), true)
};
}
FPInfinite if num < _0 => {
return match sign {
SignNone => ("inf".as_bytes().to_owned(), true),
_ => ("-inf".as_bytes().to_owned(), true),
SignNone => (Vec::from_slice("inf".as_bytes()), true),
_ => (Vec::from_slice("-inf".as_bytes()), true),
};
}
_ => {}
@ -483,7 +482,7 @@ pub fn float_to_str_bytes_common<T:NumCast+Zero+One+Eq+Ord+Float+
}
}
(buf.move_iter().collect(), false)
(buf, false)
}
/**
@ -498,7 +497,7 @@ pub fn float_to_str_common<T:NumCast+Zero+One+Eq+Ord+NumStrConv+Float+
) -> (~str, bool) {
let (bytes, special) = float_to_str_bytes_common(num, radix,
negative_zero, sign, digits, exp_format, exp_capital);
(str::from_utf8_owned(bytes).unwrap(), special)
(StrBuf::from_utf8(bytes).unwrap().into_owned(), special)
}
// Some constants for from_str_bytes_common's input validation,

View File

@ -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};

View File

@ -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};

View File

@ -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};

View File

@ -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};

View File

@ -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};

View File

@ -78,13 +78,16 @@ impl ToStrRadix for $T {
/// Convert to a string in a given base.
#[inline]
fn to_str_radix(&self, radix: uint) -> ~str {
use slice::Vector;
use str::StrAllocating;
let mut buf = ::vec::Vec::new();
strconv::int_to_str_bytes_common(*self, radix, strconv::SignNone, |i| {
buf.push(i);
});
// We know we generated valid utf-8, so we don't need to go through that
// check.
unsafe { str::raw::from_utf8_owned(buf.move_iter().collect()) }
unsafe { str::raw::from_utf8(buf.as_slice()).to_owned() }
}
}

View File

@ -169,7 +169,7 @@ fn with_env_lock<T>(f: || -> T) -> T {
///
/// Invalid UTF-8 bytes are replaced with \uFFFD. See `str::from_utf8_lossy()`
/// for details.
pub fn env() -> ~[(~str,~str)] {
pub fn env() -> Vec<(~str,~str)> {
env_as_bytes().move_iter().map(|(k,v)| {
let k = str::from_utf8_lossy(k).into_owned();
let v = str::from_utf8_lossy(v).into_owned();
@ -179,7 +179,7 @@ pub fn env() -> ~[(~str,~str)] {
/// Returns a vector of (variable, value) byte-vector pairs for all the
/// environment variables of the current process.
pub fn env_as_bytes() -> ~[(~[u8],~[u8])] {
pub fn env_as_bytes() -> Vec<(~[u8],~[u8])> {
unsafe {
#[cfg(windows)]
unsafe fn get_env_pairs() -> Vec<~[u8]> {
@ -224,16 +224,16 @@ 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<Path> {
#[cfg(target_os = "freebsd")]
fn load_self() -> Option<~[u8]> {
fn load_self() -> Option<Vec<u8>> {
unsafe {
use libc::funcs::bsd44::*;
use libc::consts::os::extra::*;
@ -436,23 +436,23 @@ pub fn self_exe_name() -> Option<Path> {
if err != 0 { return None; }
if sz == 0 { return None; }
v.set_len(sz as uint - 1); // chop off trailing NUL
Some(v.move_iter().collect())
Some(v)
}
}
#[cfg(target_os = "linux")]
#[cfg(target_os = "android")]
fn load_self() -> Option<~[u8]> {
fn load_self() -> Option<Vec<u8>> {
use std::io;
match io::fs::readlink(&Path::new("/proc/self/exe")) {
Ok(path) => Some(path.as_vec().to_owned()),
Ok(path) => Some(path.into_vec()),
Err(..) => None
}
}
#[cfg(target_os = "macos")]
fn load_self() -> Option<~[u8]> {
fn load_self() -> Option<Vec<u8>> {
unsafe {
use libc::funcs::extra::_NSGetExecutablePath;
let mut sz: u32 = 0;
@ -462,19 +462,19 @@ pub fn self_exe_name() -> Option<Path> {
let err = _NSGetExecutablePath(v.as_mut_ptr() as *mut i8, &mut sz);
if err != 0 { return None; }
v.set_len(sz as uint - 1); // chop off trailing NUL
Some(v.move_iter().collect())
Some(v)
}
}
#[cfg(windows)]
fn load_self() -> Option<~[u8]> {
fn load_self() -> Option<Vec<u8>> {
use str::OwnedStr;
unsafe {
use os::win32::fill_utf16_buf_and_decode;
fill_utf16_buf_and_decode(|buf, sz| {
libc::GetModuleFileNameW(0u as libc::DWORD, buf, sz)
}).map(|s| s.into_bytes())
}).map(|s| s.into_strbuf().into_bytes())
}
}
@ -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()
}

View File

@ -21,6 +21,7 @@
//! FIXME #7756: This has a lot of C glue for lack of globals.
use option::Option;
use vec::Vec;
#[cfg(test)] use option::{Some, None};
#[cfg(test)] use realstd;
#[cfg(test)] use realargs = realstd::rt::args;
@ -36,10 +37,10 @@ pub unsafe fn init(argc: int, argv: **u8) { realargs::init(argc, argv) }
#[cfg(test)] pub unsafe fn cleanup() { realargs::cleanup() }
/// Take the global arguments from global storage.
#[cfg(not(test))] pub fn take() -> Option<~[~[u8]]> { imp::take() }
#[cfg(test)] pub fn take() -> Option<~[~[u8]]> {
#[cfg(not(test))] pub fn take() -> Option<Vec<~[u8]>> { imp::take() }
#[cfg(test)] pub fn take() -> Option<Vec<~[u8]>> {
match realargs::take() {
realstd::option::Some(a) => Some(a),
realstd::option::Some(v) => Some(unsafe{ ::cast::transmute(v) }),
realstd::option::None => None,
}
}
@ -47,14 +48,14 @@ pub unsafe fn init(argc: int, argv: **u8) { realargs::init(argc, argv) }
/// Give the global arguments to global storage.
///
/// It is an error if the arguments already exist.
#[cfg(not(test))] pub fn put(args: ~[~[u8]]) { imp::put(args) }
#[cfg(test)] pub fn put(args: ~[~[u8]]) { realargs::put(args) }
#[cfg(not(test))] pub fn put(args: Vec<~[u8]>) { imp::put(args) }
#[cfg(test)] pub fn put(args: Vec<~[u8]>) { realargs::put(unsafe { ::cast::transmute(args) }) }
/// Make a clone of the global arguments.
#[cfg(not(test))] pub fn clone() -> Option<~[~[u8]]> { imp::clone() }
#[cfg(test)] pub fn clone() -> Option<~[~[u8]]> {
#[cfg(not(test))] pub fn clone() -> Option<Vec<~[u8]>> { imp::clone() }
#[cfg(test)] pub fn clone() -> Option<Vec<~[u8]>> {
match realargs::clone() {
realstd::option::Some(a) => Some(a),
realstd::option::Some(v) => Some(unsafe { ::cast::transmute(v) }),
realstd::option::None => None,
}
}
@ -70,6 +71,7 @@ mod imp {
use owned::Box;
use unstable::mutex::{StaticNativeMutex, NATIVE_MUTEX_INIT};
use mem;
use vec::Vec;
#[cfg(not(test))] use ptr::RawPtr;
static mut global_args_ptr: uint = 0;
@ -87,15 +89,15 @@ mod imp {
lock.destroy();
}
pub fn take() -> Option<~[~[u8]]> {
pub fn take() -> Option<Vec<~[u8]>> {
with_lock(|| unsafe {
let ptr = get_global_ptr();
let val = mem::replace(&mut *ptr, None);
val.as_ref().map(|s: &Box<~[~[u8]]>| (**s).clone())
val.as_ref().map(|s: &Box<Vec<~[u8]>>| (**s).clone())
})
}
pub fn put(args: ~[~[u8]]) {
pub fn put(args: Vec<~[u8]>) {
with_lock(|| unsafe {
let ptr = get_global_ptr();
rtassert!((*ptr).is_none());
@ -103,10 +105,10 @@ mod imp {
})
}
pub fn clone() -> Option<~[~[u8]]> {
pub fn clone() -> Option<Vec<~[u8]>> {
with_lock(|| unsafe {
let ptr = get_global_ptr();
(*ptr).as_ref().map(|s: &Box<~[~[u8]]>| (**s).clone())
(*ptr).as_ref().map(|s: &Box<Vec<~[u8]>>| (**s).clone())
})
}
@ -117,13 +119,13 @@ mod imp {
}
}
fn get_global_ptr() -> *mut Option<Box<~[~[u8]]>> {
fn get_global_ptr() -> *mut Option<Box<Vec<~[u8]>>> {
unsafe { cast::transmute(&global_args_ptr) }
}
// Copied from `os`.
#[cfg(not(test))]
unsafe fn load_argc_and_argv(argc: int, argv: **u8) -> ~[~[u8]] {
unsafe fn load_argc_and_argv(argc: int, argv: **u8) -> Vec<~[u8]> {
use c_str::CString;
use ptr::RawPtr;
use libc;
@ -133,7 +135,7 @@ 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<Vec<~[u8]>> {
fail!()
}
pub fn put(_args: ~[~[u8]]) {
pub fn put(_args: Vec<~[u8]>) {
fail!()
}
pub fn clone() -> Option<~[~[u8]]> {
pub fn clone() -> Option<Vec<~[u8]>> {
fail!()
}
}

View File

@ -161,7 +161,7 @@ pub trait IoFactory {
fn unix_connect(&mut self, path: &CString,
timeout: Option<u64>) -> IoResult<Box<RtioPipe:Send>>;
fn get_host_addresses(&mut self, host: Option<&str>, servname: Option<&str>,
hint: Option<ai::Hint>) -> IoResult<~[ai::Info]>;
hint: Option<ai::Hint>) -> IoResult<Vec<ai::Info>>;
// filesystem operations
fn fs_from_raw_fd(&mut self, fd: c_int, close: CloseBehavior)
@ -191,7 +191,7 @@ pub trait IoFactory {
fn timer_init(&mut self) -> IoResult<Box<RtioTimer:Send>>;
fn spawn(&mut self, config: ProcessConfig)
-> IoResult<(Box<RtioProcess:Send>,
~[Option<Box<RtioPipe:Send>>])>;
Vec<Option<Box<RtioPipe:Send>>>)>;
fn kill(&mut self, pid: libc::pid_t, signal: int) -> IoResult<()>;
fn pipe_open(&mut self, fd: c_int) -> IoResult<Box<RtioPipe:Send>>;
fn tty_open(&mut self, fd: c_int, readable: bool)

View File

@ -127,23 +127,23 @@ pub trait VectorVector<T> {
// FIXME #5898: calling these .concat and .connect conflicts with
// StrVector::con{cat,nect}, since they have generic contents.
/// Flattens a vector of vectors of T into a single vector of T.
fn concat_vec(&self) -> ~[T];
fn concat_vec(&self) -> Vec<T>;
/// Concatenate a vector of vectors, placing a given separator between each.
fn connect_vec(&self, sep: &T) -> ~[T];
fn connect_vec(&self, sep: &T) -> Vec<T>;
}
impl<'a, T: Clone, V: Vector<T>> VectorVector<T> for &'a [V] {
fn concat_vec(&self) -> ~[T] {
fn concat_vec(&self) -> Vec<T> {
let size = self.iter().fold(0u, |acc, v| acc + v.as_slice().len());
let mut result = Vec::with_capacity(size);
for v in self.iter() {
result.push_all(v.as_slice())
}
result.move_iter().collect()
result
}
fn connect_vec(&self, sep: &T) -> ~[T] {
fn connect_vec(&self, sep: &T) -> Vec<T> {
let size = self.iter().fold(0u, |acc, v| acc + v.as_slice().len());
let mut result = Vec::with_capacity(size + self.len());
let mut first = true;
@ -151,29 +151,10 @@ impl<'a, T: Clone, V: Vector<T>> VectorVector<T> 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<T, U, V: Iterator<(T, U)>>(mut iter: V) -> (~[T], ~[U]) {
let (lo, _) = iter.size_hint();
let mut ts = Vec::with_capacity(lo);
let mut us = Vec::with_capacity(lo);
for (t, u) in iter {
ts.push(t);
us.push(u);
}
(ts.move_iter().collect(), us.move_iter().collect())
}
/// An Iterator that yields the element swaps needed to produce
/// a sequence of all possible permutations for an indexed sequence of
/// elements. Each permutation is only a single swap apart.
@ -185,7 +166,7 @@ pub fn unzip<T, U, V: Iterator<(T, U)>>(mut iter: V) -> (~[T], ~[U]) {
/// The last generated swap is always (0, 1), and it returns the
/// sequence to its initial order.
pub struct ElementSwaps {
sdir: ~[SizeDirection],
sdir: Vec<SizeDirection>,
/// If true, emit the last swap that returns the sequence to initial state
emit_reset: bool,
swaps_made : uint,
@ -199,9 +180,7 @@ 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<T> for &'a [T] {
/// Returns a copy of `v`.
#[inline]
fn to_owned(&self) -> ~[T] {
use RawVec = core::raw::Vec;
use rt::global_heap::{malloc_raw, exchange_free};
use num::{CheckedAdd, CheckedMul};
use option::Expect;
let len = self.len();
let mut result = Vec::with_capacity(len);
// Unsafe code so this can be optimised to a memcpy (or something
// similarly fast) when T is Copy. LLVM is easily confused, so any
// extra operations during the loop can prevent this optimisation
let data_size = len.checked_mul(&mem::size_of::<T>());
let data_size = data_size.expect("overflow in to_owned()");
let size = mem::size_of::<RawVec<()>>().checked_add(&data_size);
let size = size.expect("overflow in to_owned()");
unsafe {
let ret = malloc_raw(size) as *mut RawVec<()>;
(*ret).fill = len * mem::nonzero_size_of::<T>();
(*ret).alloc = len * mem::nonzero_size_of::<T>();
// Be careful with the following loop. We want it to be optimized
// to a memcpy (or something similarly fast) when T is Copy. LLVM
// is easily confused, so any extra operations during the loop can
// prevent this optimization.
let mut i = 0;
let p = result.as_mut_ptr();
// Use try_finally here otherwise the write to length
// inside the loop stops LLVM from optimising this.
let p = &mut (*ret).data as *mut _ as *mut T;
try_finally(
&mut i, (),
|i, ()| while *i < len {
@ -332,9 +324,15 @@ impl<'a, T: Clone> CloneableVector<T> 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<T: Clone> CloneableVector<T> for ~[T] {
pub trait ImmutableCloneableVector<T> {
/// Partitions the vector into two vectors `(A,B)`, where all
/// elements of `A` satisfy `f` and all elements of `B` do not.
fn partitioned(&self, f: |&T| -> bool) -> (~[T], ~[T]);
fn partitioned(&self, f: |&T| -> bool) -> (Vec<T>, Vec<T>);
/// Create an iterator that yields every possible permutation of the
/// vector in succession.
@ -363,7 +361,7 @@ pub trait ImmutableCloneableVector<T> {
impl<'a,T:Clone> ImmutableCloneableVector<T> for &'a [T] {
#[inline]
fn partitioned(&self, f: |&T| -> bool) -> (~[T], ~[T]) {
fn partitioned(&self, f: |&T| -> bool) -> (Vec<T>, Vec<T>) {
let mut lefts = Vec::new();
let mut rights = Vec::new();
@ -375,7 +373,7 @@ impl<'a,T:Clone> ImmutableCloneableVector<T> for &'a [T] {
}
}
(lefts.move_iter().collect(), rights.move_iter().collect())
(lefts, rights)
}
fn permutations(self) -> Permutations<T> {
@ -412,7 +410,7 @@ pub trait OwnedVector<T> {
* Partitions the vector into two vectors `(A,B)`, where all
* elements of `A` satisfy `f` and all elements of `B` do not.
*/
fn partition(self, f: |&T| -> bool) -> (~[T], ~[T]);
fn partition(self, f: |&T| -> bool) -> (Vec<T>, Vec<T>);
}
impl<T> OwnedVector<T> for ~[T] {
@ -432,7 +430,7 @@ impl<T> OwnedVector<T> for ~[T] {
}
#[inline]
fn partition(self, f: |&T| -> bool) -> (~[T], ~[T]) {
fn partition(self, f: |&T| -> bool) -> (Vec<T>, Vec<T>) {
let mut lefts = Vec::new();
let mut rights = Vec::new();
@ -444,7 +442,7 @@ impl<T> OwnedVector<T> for ~[T] {
}
}
(lefts.move_iter().collect(), rights.move_iter().collect())
(lefts, rights)
}
}
@ -729,45 +727,10 @@ impl<'a, T: TotalOrd> MutableTotalOrdVector<T> 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<T>(ptr: *T, elts: uint) -> ~[T] {
raw::from_buf_raw(ptr, elts)
}
/// Unsafe operations
pub mod raw {
use iter::Iterator;
use ptr;
use slice::{MutableVector, OwnedVector};
use vec::Vec;
pub use core::slice::raw::{buf_as_slice, mut_buf_as_slice};
pub use core::slice::raw::{shift_ptr, pop_ptr};
/**
* Constructs a vector from an unsafe pointer to a buffer
*
* # Arguments
*
* * ptr - An unsafe pointer to a buffer of `T`
* * elts - The number of elements in the buffer
*/
// Was in raw, but needs to be called by net_tcp::on_tcp_read_cb
#[inline]
pub unsafe fn from_buf_raw<T>(ptr: *T, elts: uint) -> ~[T] {
let mut dst = Vec::with_capacity(elts);
dst.set_len(elts);
ptr::copy_memory(dst.as_mut_ptr(), ptr, elts);
dst.move_iter().collect()
}
}
/// An iterator that moves out of a vector.
@ -827,31 +790,6 @@ 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::<uint>() % 10;
counts[n] += 1;
(n, counts[n])
}).collect::<~[(uint, int)]>();
}).collect::<Vec<(uint, int)>>();
// only sort on the first element, so an unstable sort
// may mix up the counts.
@ -1436,46 +1363,45 @@ 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::<Vec<&[int]>>().as_slice(),
&[&[1], &[3], &[5]]);
assert_eq!(xs.split(|x| *x == 1).collect::<Vec<&[int]>>().as_slice(),
&[&[], &[2,3,4,5]]);
assert_eq!(xs.split(|x| *x == 5).collect::<Vec<&[int]>>().as_slice(),
&[&[1,2,3,4], &[]]);
assert_eq!(xs.split(|x| *x == 10).collect::<Vec<&[int]>>().as_slice(),
&[&[1,2,3,4,5]]);
assert_eq!(xs.split(|_| true).collect::<Vec<&[int]>>().as_slice(),
&[&[], &[], &[], &[], &[], &[]]);
let xs: &[int] = &[];
assert_eq!(xs.split(|x| *x == 5).collect::<~[&[int]]>(), box [&[]]);
assert_eq!(xs.split(|x| *x == 5).collect::<Vec<&[int]>>().as_slice(), &[&[]]);
}
#[test]
fn test_splitnator() {
let xs = &[1i,2,3,4,5];
assert_eq!(xs.splitn(0, |x| *x % 2 == 0).collect::<~[&[int]]>(),
box [&[1,2,3,4,5]]);
assert_eq!(xs.splitn(1, |x| *x % 2 == 0).collect::<~[&[int]]>(),
box [&[1], &[3,4,5]]);
assert_eq!(xs.splitn(3, |_| true).collect::<~[&[int]]>(),
box [&[], &[], &[], &[4,5]]);
assert_eq!(xs.splitn(0, |x| *x % 2 == 0).collect::<Vec<&[int]>>().as_slice(),
&[&[1,2,3,4,5]]);
assert_eq!(xs.splitn(1, |x| *x % 2 == 0).collect::<Vec<&[int]>>().as_slice(),
&[&[1], &[3,4,5]]);
assert_eq!(xs.splitn(3, |_| true).collect::<Vec<&[int]>>().as_slice(),
&[&[], &[], &[], &[4,5]]);
let xs: &[int] = &[];
assert_eq!(xs.splitn(1, |x| *x == 5).collect::<~[&[int]]>(), box [&[]]);
assert_eq!(xs.splitn(1, |x| *x == 5).collect::<Vec<&[int]>>().as_slice(), &[&[]]);
}
#[test]
fn test_rsplitator() {
let xs = &[1i,2,3,4,5];
assert_eq!(xs.split(|x| *x % 2 == 0).rev().collect::<~[&[int]]>(),
box [&[5], &[3], &[1]]);
assert_eq!(xs.split(|x| *x == 1).rev().collect::<~[&[int]]>(),
box [&[2,3,4,5], &[]]);
assert_eq!(xs.split(|x| *x == 5).rev().collect::<~[&[int]]>(),
box [&[], &[1,2,3,4]]);
assert_eq!(xs.split(|x| *x == 10).rev().collect::<~[&[int]]>(),
box [&[1,2,3,4,5]]);
assert_eq!(xs.split(|x| *x % 2 == 0).rev().collect::<Vec<&[int]>>().as_slice(),
&[&[5], &[3], &[1]]);
assert_eq!(xs.split(|x| *x == 1).rev().collect::<Vec<&[int]>>().as_slice(),
&[&[2,3,4,5], &[]]);
assert_eq!(xs.split(|x| *x == 5).rev().collect::<Vec<&[int]>>().as_slice(),
&[&[], &[1,2,3,4]]);
assert_eq!(xs.split(|x| *x == 10).rev().collect::<Vec<&[int]>>().as_slice(),
&[&[1,2,3,4,5]]);
let xs: &[int] = &[];
assert_eq!(xs.split(|x| *x == 5).rev().collect::<~[&[int]]>(), box [&[]]);
assert_eq!(xs.split(|x| *x == 5).rev().collect::<Vec<&[int]>>().as_slice(), &[&[]]);
}
#[test]
fn test_rsplitnator() {
let xs = &[1,2,3,4,5];
assert_eq!(xs.rsplitn(0, |x| *x % 2 == 0).collect::<~[&[int]]>(),
box [&[1,2,3,4,5]]);
assert_eq!(xs.rsplitn(1, |x| *x % 2 == 0).collect::<~[&[int]]>(),
box [&[5], &[1,2,3]]);
assert_eq!(xs.rsplitn(3, |_| true).collect::<~[&[int]]>(),
box [&[], &[], &[], &[1,2]]);
assert_eq!(xs.rsplitn(0, |x| *x % 2 == 0).collect::<Vec<&[int]>>().as_slice(),
&[&[1,2,3,4,5]]);
assert_eq!(xs.rsplitn(1, |x| *x % 2 == 0).collect::<Vec<&[int]>>().as_slice(),
&[&[5], &[1,2,3]]);
assert_eq!(xs.rsplitn(3, |_| true).collect::<Vec<&[int]>>().as_slice(),
&[&[], &[], &[], &[1,2]]);
let xs: &[int] = &[];
assert_eq!(xs.rsplitn(1, |x| *x == 5).collect::<~[&[int]]>(), box [&[]]);
assert_eq!(xs.rsplitn(1, |x| *x == 5).collect::<Vec<&[int]>>().as_slice(), &[&[]]);
}
#[test]
fn test_windowsator() {
let v = &[1i,2,3,4];
assert_eq!(v.windows(2).collect::<~[&[int]]>(), box [&[1,2], &[2,3], &[3,4]]);
assert_eq!(v.windows(3).collect::<~[&[int]]>(), box [&[1i,2,3], &[2,3,4]]);
assert_eq!(v.windows(2).collect::<Vec<&[int]>>().as_slice(), &[&[1,2], &[2,3], &[3,4]]);
assert_eq!(v.windows(3).collect::<Vec<&[int]>>().as_slice(), &[&[1i,2,3], &[2,3,4]]);
assert!(v.windows(6).next().is_none());
}
@ -1855,11 +1781,11 @@ 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::<Vec<&[int]>>().as_slice(), &[&[1i,2], &[3,4], &[5]]);
assert_eq!(v.chunks(3).collect::<Vec<&[int]>>().as_slice(), &[&[1i,2,3], &[4,5]]);
assert_eq!(v.chunks(6).collect::<Vec<&[int]>>().as_slice(), &[&[1i,2,3,4,5]]);
assert_eq!(v.chunks(2).rev().collect::<~[&[int]]>(), box [&[5i], &[3,4], &[1,2]]);
assert_eq!(v.chunks(2).rev().collect::<Vec<&[int]>>().as_slice(), &[&[5i], &[3,4], &[1,2]]);
let mut it = v.chunks(2);
assert_eq!(it.indexable(), 3);
assert_eq!(it.idx(0).unwrap(), &[1,2]);
@ -2237,15 +2163,6 @@ 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<uint>> = Vec::from_fn(100, |i| range(0, i).collect());

View File

@ -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<u16> {
let me = self.as_slice();
let mut u = Vec::new();;
let mut u = Vec::new();
for ch in me.chars() {
let mut buf = [0u16, ..2];
let n = ch.encode_utf16(buf /* as mut slice! */);
u.push_all(buf.slice_to(n));
}
u.move_iter().collect()
u
}
/// Given a string, make a new string with repeated copies of it.
@ -1554,7 +1546,8 @@ 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]

View File

@ -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())
}
}

View File

@ -69,14 +69,14 @@ impl<T: Send> UnsafeArc<T> {
/// As new(), but returns a vector of as many pre-cloned handles as
/// requested.
pub fn newN(data: T, num_handles: uint) -> ~[UnsafeArc<T>] {
pub fn newN(data: T, num_handles: uint) -> Vec<UnsafeArc<T>> {
unsafe {
if num_handles == 0 {
box [] // need to free data here
vec![] // need to free data here
} else {
let ptr = new_inner(data, num_handles);
let v = Vec::from_fn(num_handles, |_| UnsafeArc { data: ptr });
v.move_iter().collect()
v
}
}
}

View File

@ -407,7 +407,7 @@ mod tests {
use rand::Rng;
use sync::atomics::{AtomicBool, INIT_ATOMIC_BOOL, SeqCst,
AtomicUint, INIT_ATOMIC_UINT};
use slice;
use vec;
#[test]
fn smoke() {
@ -603,7 +603,7 @@ 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 {

View File

@ -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::<Vec<_>>();
newenv.push_all(&[sep]);
newenv.push_all(path.as_vec());
os::setenv(envvar, str::from_utf8(newenv.as_slice()).unwrap());
}
/// Access the value at the symbol of the dynamic library

View File

@ -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<T> Vector<T> for Vec<T> {
}
}
impl<T: Clone, V: Vector<T>> Add<V, Vec<T>> for Vec<T> {
#[inline]
fn add(&self, rhs: &V) -> Vec<T> {
let mut res = Vec::with_capacity(self.len() + rhs.as_slice().len());
res.push_all(self.as_slice());
res.push_all(rhs.as_slice());
res
}
}
#[unsafe_destructor]
impl<T> Drop for Vec<T> {
fn drop(&mut self) {
@ -1436,10 +1447,94 @@ impl<T> Drop for MoveItems<T> {
}
}
/**
* Convert an iterator of pairs into a pair of vectors.
*
* Returns a tuple containing two vectors where the i-th element of the first
* vector contains the first element of the i-th tuple of the input iterator,
* and the i-th element of the second vector contains the second element
* of the i-th tuple of the input iterator.
*/
pub fn unzip<T, U, V: Iterator<(T, U)>>(mut iter: V) -> (Vec<T>, Vec<U>) {
let (lo, _) = iter.size_hint();
let mut ts = Vec::with_capacity(lo);
let mut us = Vec::with_capacity(lo);
for (t, u) in iter {
ts.push(t);
us.push(u);
}
(ts, us)
}
/// Mechanism to convert from a `Vec<T>` to a `[T]`.
///
/// In a post-DST world this will be used to convert to any `Ptr<[T]>`.
///
/// This could be implemented on more types than just pointers to vectors, but
/// the recommended approach for those types is to implement `FromIterator`.
// FIXME(#12938): Update doc comment when DST lands
pub trait FromVec<T> {
/// Convert a `Vec<T>` into the receiver type.
fn from_vec(v: Vec<T>) -> Self;
}
impl<T> FromVec<T> for ~[T] {
fn from_vec(mut v: Vec<T>) -> ~[T] {
let len = v.len();
let data_size = len.checked_mul(&mem::size_of::<T>());
let data_size = data_size.expect("overflow in from_vec()");
let size = mem::size_of::<RawVec<()>>().checked_add(&data_size);
let size = size.expect("overflow in from_vec()");
// In a post-DST world, we can attempt to reuse the Vec allocation by calling
// shrink_to_fit() on it. That may involve a reallocation+memcpy, but that's no
// diffrent than what we're doing manually here.
let vp = v.as_mut_ptr();
unsafe {
let ret = malloc_raw(size) as *mut RawVec<()>;
(*ret).fill = len * mem::nonzero_size_of::<T>();
(*ret).alloc = len * mem::nonzero_size_of::<T>();
ptr::copy_nonoverlapping_memory(&mut (*ret).data as *mut _ as *mut u8,
vp as *u8, data_size);
// we've transferred ownership of the contents from v, but we can't drop it
// as it still needs to free its own allocation.
v.set_len(0);
transmute(ret)
}
}
}
/// Unsafe operations
pub mod raw {
use super::Vec;
use ptr;
/// Constructs a vector from an unsafe pointer to a buffer.
///
/// The elements of the buffer are copied into the vector without cloning,
/// as if `ptr::read()` were called on them.
#[inline]
pub unsafe fn from_buf<T>(ptr: *T, elts: uint) -> Vec<T> {
let mut dst = Vec::with_capacity(elts);
dst.set_len(elts);
ptr::copy_nonoverlapping_memory(dst.as_mut_ptr(), ptr, elts);
dst
}
}
#[cfg(test)]
mod tests {
use prelude::*;
use mem::size_of;
use kinds::marker;
use super::{unzip, raw, FromVec};
#[test]
fn test_small_vec_struct() {
@ -1649,4 +1744,75 @@ 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);
}
}

View File

@ -90,6 +90,7 @@ fn vector<M: MutableMap<uint, uint>>(map: &mut M, n_keys: uint, dist: &[uint]) {
fn main() {
let args = os::args();
let args = args.as_slice();
let n_keys = {
if args.len() == 2 {
from_str::<uint>(args[1]).unwrap()

View File

@ -155,6 +155,7 @@ fn empty_results() -> Results {
fn main() {
let args = os::args();
let args = args.as_slice();
let num_keys = {
if args.len() == 2 {
from_str::<uint>(args[1]).unwrap()

View File

@ -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() {

View File

@ -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::<uint>(args[1]).unwrap()
} else {

View File

@ -31,6 +31,7 @@ fn parfib(n: uint) -> uint {
fn main() {
let args = os::args();
let args = args.as_slice();
let n = if args.len() == 2 {
from_str::<uint>(args[1]).unwrap()
} else {

View File

@ -28,6 +28,7 @@ fn start(argc: int, argv: **u8) -> int {
fn main() {
let args = os::args();
let args = args.as_slice();
let n = if args.len() == 2 {
from_str::<uint>(args[1]).unwrap()
} else {

View File

@ -40,6 +40,7 @@ fn bottom_up_tree<'r>(arena: &'r TypedArena<Tree<'r>>, item: int, depth: int)
fn main() {
let args = std::os::args();
let args = args.as_slice();
let n = if std::os::getenv("RUST_BENCH").is_some() {
17
} else if args.len() <= 1u {

View File

@ -194,7 +194,7 @@ fn main() {
let nn = if std::os::getenv("RUST_BENCH").is_some() {
200000
} else {
std::os::args().get(1).and_then(|arg| from_str(*arg)).unwrap_or(600)
std::os::args().as_slice().get(1).and_then(|arg| from_str(*arg)).unwrap_or(600)
};
print_complements();

View File

@ -53,7 +53,7 @@ fn fannkuch(n: uint, i: uint) -> (int, int) {
}
fn main() {
let n = std::os::args().get(1).and_then(|arg| from_str(*arg)).unwrap_or(2u);
let n = std::os::args().as_slice().get(1).and_then(|arg| from_str(*arg)).unwrap_or(2u);
let (tx, rx) = channel();
for i in range(0, n) {

View File

@ -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::<uint>(args[1]).unwrap()
} else {

View File

@ -74,6 +74,7 @@ fn make_fasta<W: Writer, I: Iterator<u8>>(
fn run<W: Writer>(writer: &mut W) {
let args = os::args();
let args = args.as_slice();
let n = if os::getenv("RUST_BENCH").is_some() {
25000000
} else if args.len() <= 1u {

View File

@ -72,7 +72,7 @@ fn sort_and_fmt(mm: &HashMap<Vec<u8> , uint>, total: uint) -> ~str {
// given a map, search for the frequency of a pattern
fn find(mm: &HashMap<Vec<u8> , uint>, key: ~str) -> uint {
let key = key.into_ascii().to_lower().into_str();
let key = key.into_ascii().as_slice().to_lower().into_str();
match mm.find_equiv(&key.as_bytes()) {
option::None => { return 0u; }
option::Some(&num) => { return num; }

View File

@ -65,6 +65,7 @@ fn mandelbrot<W: io::Writer>(w: uint, mut out: W) -> io::IoResult<()> {
fn main() {
let args = std::os::args();
let args = args.as_slice();
let res = if args.len() < 2 {
println!("Test mode: do not dump the image because it's not utf8, \
which interferes with the test runner.");

View File

@ -190,7 +190,7 @@ fn to_utf8(raw_sol: &List<u64>) -> ~str {
}
}
}
std::str::from_utf8_owned(sol.move_iter().collect()).unwrap()
std::str::from_utf8(sol.as_slice()).unwrap().to_owned()
}
// Prints a solution in ~str form.
@ -270,6 +270,7 @@ fn search(
fn main () {
let args = std::os::args();
let args = args.as_slice();
let stop_after = if args.len() <= 1 {
2098
} else {

View File

@ -88,6 +88,7 @@ fn pidigits(n: int) {
fn main() {
let args = std::os::args();
let args = args.as_slice();
let n = if args.len() < 2 {
512
} else {

View File

@ -94,6 +94,7 @@ fn mult_AtAv(v: Arc<RWLock<Vec<f64>>>, out: Arc<RWLock<Vec<f64>>>,
fn main() {
let args = os::args();
let args = args.as_slice();
let n = if os::getenv("RUST_BENCH").is_some() {
5500
} else if args.len() < 2 {

View File

@ -35,6 +35,7 @@ fn roundtrip(id: int, tx: Sender<int>, rx: Receiver<int>) {
fn main() {
let args = std::os::args();
let args = args.as_slice();
let token = if std::os::getenv("RUST_BENCH").is_some() {
2000000
} else {

View File

@ -36,8 +36,8 @@ fn random_char() -> char {
fn main() {
let args = os::args();
let rustc = args[1].as_slice();
let tmpdir = Path::new(args[2].as_slice());
let rustc = args.get(1).as_slice();
let tmpdir = Path::new(args.get(2).as_slice());
let main_file = tmpdir.join("unicode_input_multiple_files_main.rs");
let main_file_str = main_file.as_str().unwrap();

View File

@ -35,8 +35,8 @@ fn random_char() -> char {
fn main() {
let args = os::args();
let rustc = args[1].as_slice();
let tmpdir = Path::new(args[2].as_slice());
let rustc = args.get(1).as_slice();
let tmpdir = Path::new(args.get(2).as_slice());
let main_file = tmpdir.join("span_main.rs");
let main_file_str = main_file.as_str().unwrap();

View File

@ -100,6 +100,7 @@ fn runtest(me: &str) {
fn main() {
let args = os::args();
let args = args.as_slice();
if args.len() >= 2 && args[1].as_slice() == "fail" {
foo();
} else if args.len() >= 2 && args[1].as_slice() == "double-fail" {

View File

@ -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

View File

@ -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?");

View File

@ -25,6 +25,7 @@ fn start(argc: int, argv: **u8) -> int {
fn main() {
let args = os::args();
let args = args.as_slice();
if args.len() > 1 && args[1].as_slice() == "child" {
if args[2].as_slice() == "green" {
child();
@ -48,6 +49,7 @@ fn main() {
fn parent(flavor: ~str) {
let args = os::args();
let args = args.as_slice();
let mut p = io::Process::new(args[0].as_slice(), ["child".to_owned(), flavor]).unwrap();
p.stdin.get_mut_ref().write_str("test1\ntest2\ntest3").unwrap();
let out = p.wait_with_output();

View File

@ -10,6 +10,7 @@
fn parse_args() -> ~str {
let args = ::std::os::args();
let args = args.as_slice();
let mut n = 0;
while n < args.len() {

View File

@ -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");

View File

@ -34,6 +34,7 @@ fn loud_recurse() {
fn main() {
let args = os::args();
let args = args.as_slice();
if args.len() > 1 && args[1].as_slice() == "silent" {
silent_recurse();
} else if args.len() > 1 && args[1].as_slice() == "loud" {

View File

@ -62,7 +62,7 @@ pub fn main() {
assert!(map.pop(&Slice("foo")).is_some());
assert_eq!(map.move_iter().map(|(k, v)| k.to_str() + v.to_str())
.collect::<~[~str]>()
.collect::<Vec<~str>>()
.concat(),
"abc50bcd51cde52def53".to_owned());
}

View File

@ -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; }

View File

@ -25,6 +25,7 @@ fn test() {
fn main() {
let args = os::args();
let args = args.as_slice();
if args.len() > 1 && args[1].as_slice() == "test" {
return test();
}

View File

@ -20,7 +20,7 @@ impl to_str for int {
impl<T:to_str> to_str for Vec<T> {
fn to_string(&self) -> ~str {
format!("[{}]", self.iter().map(|e| e.to_string()).collect::<~[~str]>().connect(", "))
format!("[{}]", self.iter().map(|e| e.to_string()).collect::<Vec<~str>>().connect(", "))
}
}