`/data/local/tmp` seems to be more common.
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 => ()
}
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 => ()
}
(*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()))
}
}
~~~
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
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
}
}
~~~
## Attributes
~~~~ {.notrust .ebnf .gram}
-attribute : '#' '!' ? '[' attr_list ']' ;
-attr_list : attr [ ',' attr_list ]* ;
-attr : ident [ '=' literal
- | '(' attr_list ')' ] ? ;
+attribute : '#' '!' ? '[' meta_item ']' ;
+meta_item : ident [ '=' literal
+ | '(' meta_seq ')' ] ? ;
+meta_seq : meta_item [ ',' meta_seq ]* ;
~~~~
Static entities in Rust — crates, modules and items — may have _attributes_
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
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.
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,
}
~~~~
-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];
~~~~
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
use intrinsics;
use ptr::copy_nonoverlapping_memory;
-/// Casts the value at `src` to U. The two types must have the same length.
-#[inline]
-pub unsafe fn transmute_copy<T, U>(src: &T) -> U {
- let mut dest: U = mem::uninit();
- let dest_ptr: *mut u8 = transmute(&mut dest);
- let src_ptr: *u8 = transmute(src);
- copy_nonoverlapping_memory(dest_ptr, src_ptr, mem::size_of::<U>());
- dest
-}
-
-/**
- * Move a thing into the void
- *
- * The forget function will take ownership of the provided value but neglect
- * to run any required cleanup or memory-management operations on it.
- */
-#[inline]
-pub unsafe fn forget<T>(thing: T) { intrinsics::forget(thing); }
-
-/**
- * Force-increment the reference count on a shared box. If used
- * carelessly, this can leak the box.
- */
-#[inline]
-pub unsafe fn bump_box_refcount<T>(t: @T) { forget(t); }
-
/**
* Transform a value of one type into a value of another type.
* Both types must have the same size and alignment.
* ```
*/
#[inline]
-pub unsafe fn transmute<L, G>(thing: L) -> G {
+pub unsafe fn transmute<T, U>(thing: T) -> U {
intrinsics::transmute(thing)
}
+/**
+ * Move a thing into the void
+ *
+ * The forget function will take ownership of the provided value but neglect
+ * to run any required cleanup or memory-management operations on it.
+ */
+#[inline]
+pub unsafe fn forget<T>(thing: T) { intrinsics::forget(thing); }
+
+/// Casts the value at `src` to U. The two types must have the same length.
+#[inline]
+pub unsafe fn transmute_copy<T, U>(src: &T) -> U {
+ let mut dest: U = mem::uninit();
+ let dest_ptr: *mut u8 = transmute(&mut dest);
+ let src_ptr: *u8 = transmute(src);
+ copy_nonoverlapping_memory(dest_ptr, src_ptr, mem::size_of::<U>());
+ dest
+}
+
/// Coerce an immutable reference to be mutable.
#[inline]
#[deprecated="casting &T to &mut T is undefined behaviour: use Cell<T>, RefCell<T> or Unsafe<T>"]
#[cfg(test)]
mod tests {
- use cast::{bump_box_refcount, transmute};
+ use cast::transmute;
use raw;
use realstd::str::StrAllocating;
assert_eq!(1u, unsafe { ::cast::transmute_copy(&1) });
}
- #[test]
- fn test_bump_managed_refcount() {
- unsafe {
- let managed = @"box box box".to_owned(); // refcount 1
- bump_box_refcount(managed); // refcount 2
- let ptr: *int = transmute(managed); // refcount 2
- let _box1: @~str = ::cast::transmute_copy(&ptr);
- let _box2: @~str = ::cast::transmute_copy(&ptr);
- assert!(*_box1 == "box box box".to_owned());
- assert!(*_box2 == "box box box".to_owned());
- // Will destroy _box1 and _box2. Without the bump, this would
- // use-after-free. With too many bumps, it would leak.
- }
- }
-
#[test]
fn test_transmute() {
unsafe {
// option. This file may not be copied, modified, or distributed
// except according to those terms.
-//! Types dealing with dynamic mutability
+//! Types that provide interior mutability.
use clone::Clone;
use cmp::Eq;
///
/// ```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 {
#[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]
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]
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());
#[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);
}
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]
#[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");
}
}
}
- 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
#[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]
mod std {
pub use clone;
pub use cmp;
+ pub use kinds;
#[cfg(test)] pub use realstd::fmt; // needed for fail!()
#[cfg(test)] pub use realstd::rt; // needed for fail!()
#[cfg(test)] pub use realstd::option; // needed for assert!()
#[cfg(test)] pub use realstd::os; // needed for tests
+ #[cfg(test)] pub use realstd::slice; // needed for tests
+ #[cfg(test)] pub use realstd::vec; // needed for vec![]
}
#[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);
}
// option. This file may not be copied, modified, or distributed
// except according to those terms.
+// FIXME: talk about offset, copy_memory, copy_nonoverlapping_memory
+
//! Conveniences for working with unsafe pointers, the `*T`, and `*mut T` types.
//!
//! Working with unsafe pointers in Rust is fairly uncommon,
#[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));
}
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};
use str::StrSlice;
#[cfg(not(test))] use ops::Add;
-#[cfg(not(test))] use slice::Vector;
#[allow(ctypes)]
extern {
impl<A: Clone> Clone for ~[A] {
#[inline]
fn clone(&self) -> ~[A] {
- self.iter().map(|a| a.clone()).collect()
- }
-}
-
-impl<A> FromIterator<A> for ~[A] {
- fn from_iter<T: Iterator<A>>(mut iterator: T) -> ~[A] {
- let (lower, _) = iterator.size_hint();
- let cap = if lower == 0 {16} else {lower};
- let mut cap = cap.checked_mul(&mem::size_of::<A>()).unwrap();
- let mut len = 0;
+ let len = self.len();
+ let data_size = len.checked_mul(&mem::size_of::<A>()).unwrap();
+ let size = mem::size_of::<Vec<()>>().checked_add(&data_size).unwrap();
unsafe {
- let mut ptr = alloc(cap) as *mut Vec<A>;
- let mut ret = cast::transmute(ptr);
- for elt in iterator {
- if len * mem::size_of::<A>() >= cap {
- cap = cap.checked_mul(&2).unwrap();
- let ptr2 = alloc(cap) as *mut Vec<A>;
- ptr::copy_nonoverlapping_memory(&mut (*ptr2).data,
- &(*ptr).data,
- len);
- free(ptr as *u8);
- cast::forget(ret);
- ret = cast::transmute(ptr2);
- ptr = ptr2;
- }
-
- let base = &mut (*ptr).data as *mut A;
- intrinsics::move_val_init(&mut *base.offset(len as int), elt);
- len += 1;
- (*ptr).fill = len * mem::nonzero_size_of::<A>();
- }
- ret
+ let ret = alloc(size) as *mut Vec<A>;
+
+ (*ret).fill = len * mem::nonzero_size_of::<A>();
+ (*ret).alloc = len * mem::nonzero_size_of::<A>();
+
+ let mut i = 0;
+ let p = &mut (*ret).data as *mut _ as *mut A;
+ try_finally(
+ &mut i, (),
+ |i, ()| while *i < len {
+ mem::move_val_init(
+ &mut(*p.offset(*i as int)),
+ self.unsafe_ref(*i).clone());
+ *i += 1;
+ },
+ |i| if *i < len {
+ // we must be failing, clean up after ourselves
+ for j in range(0, *i as int) {
+ ptr::read(&*p.offset(j));
+ }
+ free(ret as *u8);
+ });
+ cast::transmute(ret)
}
}
}
-
-#[cfg(not(test))]
-impl<'a,T:Clone, V: Vector<T>> Add<V, ~[T]> for &'a [T] {
- #[inline]
- fn add(&self, rhs: &V) -> ~[T] {
- let first = self.iter().map(|t| t.clone());
- first.chain(rhs.as_slice().iter().map(|t| t.clone())).collect()
- }
-}
-
-#[cfg(not(test))]
-impl<T:Clone, V: Vector<T>> Add<V, ~[T]> for ~[T] {
- #[inline]
- fn add(&self, rhs: &V) -> ~[T] {
- self.as_slice() + rhs.as_slice()
- }
-}
/// 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() }
/// # 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>;
/// # 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>;
/// # 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>;
/// # 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>;
/// # 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>;
/// # 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>;
/// # 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>;
///
/// ```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>;
///
/// ```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>;
///
/// ```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>;
///
/// ```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"
//! 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"),
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());
unsafe { freeaddrinfo(res); }
- Ok(addrs.move_iter().collect())
+ Ok(addrs)
}
}
use std::rt::rtio;
use std::str;
use std::sync::arc::UnsafeArc;
-use std::slice;
+use std::vec;
use io::IoResult;
if fp_buf as uint == 0 {
fail!("os::list_dir() failure: got null ptr from wfd");
} else {
- let fp_vec = slice::from_buf(fp_buf, libc::wcslen(fp_buf) as uint);
- let fp_trimmed = str::truncate_utf16_at_nul(fp_vec);
+ let fp_vec = vec::raw::from_buf(fp_buf, libc::wcslen(fp_buf) as uint);
+ let fp_trimmed = str::truncate_utf16_at_nul(fp_vec.as_slice());
let fp_str = str::from_utf16(fp_trimmed)
.expect("rust_list_dir_wfd_fp_buf returned invalid UTF-16");
paths.push(Path::new(fp_str));
})
}
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)
}
}
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| {
/// 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 {
exit_code: None,
exit_signal: None,
},
- ret_io.move_iter().collect()))
+ ret_io))
}
Err(e) => Err(e)
}
/**
A big unsigned integer type.
-A `BigUint`-typed value `BigUint { data: ~[a, b, c] }` represents a number
+A `BigUint`-typed value `BigUint { data: vec!(a, b, c) }` represents a number
`(a + b * BigDigit::base + c * BigDigit::base^2)`.
*/
#[deriving(Clone)]
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
#![!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] = &[
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();
}
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 {
}
}
-fn check_unused_mut_pat(cx: &Context, p: &ast::Pat) {
- match p.node {
- ast::PatIdent(ast::BindByValue(ast::MutMutable),
- ref path, _) if pat_util::pat_is_binding(&cx.tcx.def_map, p) => {
- // `let mut _a = 1;` doesn't need a warning.
- let initial_underscore = if path.segments.len() == 1 {
- token::get_ident(path.segments
- .get(0)
- .identifier).get().starts_with("_")
- } else {
- cx.tcx.sess.span_bug(p.span,
- "mutable binding that doesn't consist \
- of exactly one segment")
- };
-
- if !initial_underscore &&
- !cx.tcx.used_mut_nodes.borrow().contains(&p.id) {
- cx.span_lint(UnusedMut, p.span,
- "variable does not need to be mutable");
+fn check_unused_mut_pat(cx: &Context, pats: &[@ast::Pat]) {
+ // collect all mutable pattern and group their NodeIDs by their Identifier to
+ // avoid false warnings in match arms with multiple patterns
+ let mut mutables = HashMap::new();
+ for &p in pats.iter() {
+ pat_util::pat_bindings(&cx.tcx.def_map, p, |mode, id, _, path| {
+ match mode {
+ ast::BindByValue(ast::MutMutable) => {
+ if path.segments.len() != 1 {
+ cx.tcx.sess.span_bug(p.span,
+ "mutable binding that doesn't consist \
+ of exactly one segment");
+ }
+ let ident = path.segments.get(0).identifier;
+ if !token::get_ident(ident).get().starts_with("_") {
+ mutables.insert_or_update_with(ident.name as uint, vec!(id), |_, old| {
+ old.push(id);
+ });
+ }
+ }
+ _ => {
+ }
}
+ });
+ }
+
+ let used_mutables = cx.tcx.used_mut_nodes.borrow();
+ for (_, v) in mutables.iter() {
+ if !v.iter().any(|e| used_mutables.contains(e)) {
+ cx.span_lint(UnusedMut, cx.tcx.map.span(*v.get(0)),
+ "variable does not need to be mutable");
}
- _ => ()
}
}
fn visit_pat(&mut self, p: &ast::Pat, _: ()) {
check_pat_non_uppercase_statics(self, p);
check_pat_uppercase_variable(self, p);
- check_unused_mut_pat(self, p);
visit::walk_pat(self, p, ());
}
ast::ExprParen(expr) => if self.negated_expr_id == e.id {
self.negated_expr_id = expr.id
},
+ ast::ExprMatch(_, ref arms) => {
+ for a in arms.iter() {
+ check_unused_mut_pat(self, a.pats.as_slice());
+ }
+ },
_ => ()
};
check_unused_result(self, s);
check_unnecessary_parens_stmt(self, s);
+ match s.node {
+ ast::StmtDecl(d, _) => {
+ match d.node {
+ ast::DeclLocal(l) => {
+ check_unused_mut_pat(self, &[l.pat]);
+ },
+ _ => {}
+ }
+ },
+ _ => {}
+ }
+
visit::walk_stmt(self, s, ());
}
visit::walk_fn(this, fk, decl, body, span, id, ());
};
+ for a in decl.inputs.iter(){
+ check_unused_mut_pat(self, &[a.pat]);
+ }
+
match *fk {
visit::FkMethod(_, _, m) => {
self.with_lint_attrs(m.attrs.as_slice(), |cx| {
match def {
DefMod(_) | DefForeignMod(_) => {}
- DefVariant(_, variant_id, is_struct) => {
+ DefVariant(enum_did, variant_id, is_struct) => {
debug!("(building reduced graph for external crate) building \
variant {}",
final_ident);
- // We assume the parent is visible, or else we wouldn't have seen
- // it. Also variants are public-by-default if the parent was also
- // public.
+ // If this variant is public, then it was publicly reexported,
+ // otherwise we need to inherit the visibility of the enum
+ // definition.
+ let is_exported = is_public ||
+ self.external_exports.contains(&enum_did);
if is_struct {
- child_name_bindings.define_type(def, DUMMY_SP, true);
+ child_name_bindings.define_type(def, DUMMY_SP, is_exported);
self.structs.insert(variant_id);
} else {
- child_name_bindings.define_value(def, DUMMY_SP, true);
+ child_name_bindings.define_value(def, DUMMY_SP, is_exported);
}
}
DefFn(..) | DefStaticMethod(..) | DefStatic(..) => {
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);
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);
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};
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))
}
};
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),
}
}
}));
- (adt::trans_const(cx, &*repr, discr, cs),
+ (adt::trans_const(cx, &*repr, discr, cs.as_slice()),
inlineable.iter().fold(true, |a, &b| a && b))
})
}
// 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)
}
};
"".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)
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());
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> {
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) => {
}
// 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;
}
}
- return addrs.move_iter().collect();
+ addrs
}
}
/// 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() {
});
match ret {
- Ok(p) => Ok((p, ret_io.move_iter().collect())),
+ Ok(p) => Ok((p, ret_io)),
Err(e) => Err(e),
}
}
}
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)
}
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) {
}
unsafe {
- str::raw::from_utf8_owned(v.move_iter().collect())
+ str::raw::from_utf8(v.as_slice()).to_owned()
}
}
}
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
* ```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());
* }
* }
* ```
*/
- 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;
_ => return Err(InvalidBase64Length),
}
- Ok(r.move_iter().collect())
+ Ok(r)
}
}
#[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]
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());
}
}
}
unsafe {
- str::raw::from_utf8_owned(v.move_iter().collect())
+ str::raw::from_utf8(v.as_slice()).to_owned()
}
}
}
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
* ```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;
#[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]
#[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]
#[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]);
}
}
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`
pub struct TestStruct1 {
data_int: u8,
data_str: ~str,
- data_vector: ~[u8],
+ data_vector: Vec<u8>,
}
impl ToJson for TestStruct1 {
// 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();
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.
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()])
}
}
}
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()])
}
}
}
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 {
#[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());
);
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()))])
]))
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()))])
]))
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]
"{\"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() +
"}").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([
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()] }
]
}
);
x: f64,
y: bool,
z: ~str,
- w: ~[DecodeStruct]
+ w: Vec<DecodeStruct>
}
#[deriving(Decodable)]
enum DecodeEnum {
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)
})
}
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))
}
}
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))
}
}
}
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)
})
}
}
use to_str::{IntoStr};
use str;
use str::Str;
-use str::StrSlice;
+use str::{StrAllocating, StrSlice};
use str::OwnedStr;
use container::Container;
use cast;
/// 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 {
/// 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] {
}
#[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()))
}
}
}
#[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)
}
}
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;
}
#[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()
}
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) }
}
}
#[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] = &[
macro_rules! v2ascii (
( [$($e:expr),*]) => (&[$(Ascii{chr:$e}),*]);
(&[$($e:expr),*]) => (&[$(Ascii{chr:$e}),*]);
- (~[$($e:expr),*]) => (box [$(Ascii{chr:$e}),*]);
)
macro_rules! vec2ascii (
#[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]
#[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]
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);
}
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
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 {
/// 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())
}
/// 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))
}
///
/// For clarification on the semantics of interrupting a read and a write,
/// take a look at `set_read_timeout` and `set_write_timeout`.
+ #[experimental = "the timeout argument may change in type and value"]
pub fn set_timeout(&mut self, timeout_ms: Option<u64>) {
self.obj.set_timeout(timeout_ms)
}
/// action is taken. Otherwise, the read operation will be scheduled to
/// promptly return. If a timeout error is returned, then no data was read
/// during the timeout period.
+ #[experimental = "the timeout argument may change in type and value"]
pub fn set_read_timeout(&mut self, timeout_ms: Option<u64>) {
self.obj.set_read_timeout(timeout_ms)
}
/// does not know how many bytes were written as part of the timeout
/// operation. It may be the case that bytes continue to be written in an
/// asynchronous fashion after the call to write returns.
+ #[experimental = "the timeout argument may change in type and value"]
pub fn set_write_timeout(&mut self, timeout_ms: Option<u64>) {
self.obj.set_write_timeout(timeout_ms)
}
// Also make sure that even though the timeout is expired that we will
// continue to receive any pending connections.
- let (tx, rx) = channel();
- spawn(proc() {
- tx.send(TcpStream::connect(addr).unwrap());
- });
- let l = rx.recv();
- for i in range(0, 1001) {
- match a.accept() {
- Ok(..) => break,
- Err(ref e) if e.kind == TimedOut => {}
- Err(e) => fail!("error: {}", e),
+ //
+ // FIXME: freebsd apparently never sees the pending connection, but
+ // testing manually always works. Need to investigate this
+ // flakiness.
+ if !cfg!(target_os = "freebsd") {
+ let (tx, rx) = channel();
+ spawn(proc() {
+ tx.send(TcpStream::connect(addr).unwrap());
+ });
+ let l = rx.recv();
+ for i in range(0, 1001) {
+ match a.accept() {
+ Ok(..) => break,
+ Err(ref e) if e.kind == TimedOut => {}
+ Err(e) => fail!("error: {}", e),
+ }
+ ::task::deschedule();
+ if i == 1000 { fail!("should have a pending connection") }
}
- ::task::deschedule();
- if i == 1000 { fail!("should have a pending connection") }
}
- drop(l);
// Unset the timeout and make sure that this always blocks.
a.set_timeout(None);
/// Sets the read/write timeout for this socket.
///
/// For more information, see `TcpStream::set_timeout`
+ #[experimental = "the timeout argument may change in type and value"]
pub fn set_timeout(&mut self, timeout_ms: Option<u64>) {
self.obj.set_timeout(timeout_ms)
}
/// Sets the read timeout for this socket.
///
/// For more information, see `TcpStream::set_timeout`
+ #[experimental = "the timeout argument may change in type and value"]
pub fn set_read_timeout(&mut self, timeout_ms: Option<u64>) {
self.obj.set_read_timeout(timeout_ms)
}
/// Sets the write timeout for this socket.
///
/// For more information, see `TcpStream::set_timeout`
+ #[experimental = "the timeout argument may change in type and value"]
pub fn set_write_timeout(&mut self, timeout_ms: Option<u64>) {
self.obj.set_write_timeout(timeout_ms)
}
/// Sets the read/write timeout for this socket.
///
/// For more information, see `TcpStream::set_timeout`
+ #[experimental = "the timeout argument may change in type and value"]
pub fn set_timeout(&mut self, timeout_ms: Option<u64>) {
self.obj.set_timeout(timeout_ms)
}
/// Sets the read timeout for this socket.
///
/// For more information, see `TcpStream::set_timeout`
+ #[experimental = "the timeout argument may change in type and value"]
pub fn set_read_timeout(&mut self, timeout_ms: Option<u64>) {
self.obj.set_read_timeout(timeout_ms)
}
/// Sets the write timeout for this socket.
///
/// For more information, see `TcpStream::set_timeout`
+ #[experimental = "the timeout argument may change in type and value"]
pub fn set_write_timeout(&mut self, timeout_ms: Option<u64>) {
self.obj.set_write_timeout(timeout_ms)
}
/// 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
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();
}
//! memory types, including [`atomics`](sync/atomics/index.html).
//!
//! Common types of I/O, including files, TCP, UPD, pipes, Unix domain sockets,
-//! timers, and process spawning, are defined in the [`io`](io/index.html).
+//! timers, and process spawning, are defined in the [`io`](io/index.html) module.
//!
//! Rust's I/O and concurrency depends on a small runtime interface
//! that lives, along with its support code, in mod [`rt`](rt/index.html).
//!
//! ## The Rust prelude and macros
//!
-//! Finally, the [`prelude`](prelude/index.html) defines a set of
+//! Finally, the [`prelude`](prelude/index.html) defines a
//! common set of traits, types, and functions that are made available
//! to all code by default. [`macros`](macros/index.html) contains
-//! all the standard macros, such as `assert!`, `fail!`, `println!`.
+//! all the standard macros, such as `assert!`, `fail!`, `println!`,
+//! and `format!`, also available to all Rust code.
#![crate_id = "std#0.11-pre"]
#![comment = "The Rust standard library"]
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;
}
//! 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};
//! 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};
//! 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};
//! 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};
//! 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};
/// 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() }
}
}
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.
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'
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),
};
}
_ => {}
}
}
- (buf.move_iter().collect(), false)
+ (buf, false)
}
/**
) -> (~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,
//! 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};
//! 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};
//! 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};
//! 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};
//! 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};
/// 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() }
}
}
///
/// 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();
/// 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]> {
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)
})
}
}
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::*;
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;
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())
}
}
}
#[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()
+ })
}
/**
* 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);
#[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() {
}
#[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;
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()
}
///
/// 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()
}
//! 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;
#[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,
}
}
/// 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,
}
}
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;
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());
})
}
- 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())
})
}
}
}
- 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;
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)]
// 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()));
#[cfg(target_os = "win32", not(test))]
mod imp {
use option::Option;
+ use vec::Vec;
pub unsafe fn init(_argc: int, _argv: **u8) {
}
pub fn cleanup() {
}
- pub fn take() -> Option<~[~[u8]]> {
+ pub fn take() -> Option<Vec<~[u8]>> {
fail!()
}
- pub fn put(_args: ~[~[u8]]) {
+ pub fn put(_args: Vec<~[u8]>) {
fail!()
}
- pub fn clone() -> Option<~[~[u8]]> {
+ pub fn clone() -> Option<Vec<~[u8]>> {
fail!()
}
}
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)
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)
// 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;
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.
/// 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,
// 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
}
}
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() {
/// 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 {
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)]
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.
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();
}
}
- (lefts.move_iter().collect(), rights.move_iter().collect())
+ (lefts, rights)
}
fn permutations(self) -> Permutations<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] {
}
#[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();
}
}
- (lefts.move_iter().collect(), rights.move_iter().collect())
+ (lefts, rights)
}
}
}
}
-/**
-* 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.
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.
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];
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.
// 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]
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());
}
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]);
})
}
- #[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());
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;
/// 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"]
/// 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.
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);
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,
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,
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,
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);
}
}
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]
#[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]
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;
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())
}
}
/// 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
}
}
}
use rand::Rng;
use sync::atomics::{AtomicBool, INIT_ATOMIC_BOOL, SeqCst,
AtomicUint, INIT_ATOMIC_UINT};
- use slice;
+ use vec;
#[test]
fn smoke() {
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 {
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}
("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
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};
}
}
+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) {
}
}
+/**
+ * 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() {
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);
+ }
}
--- /dev/null
+// Copyright 2014 The Rust Project Developers. See the COPYRIGHT
+// file at the top-level directory of this distribution and at
+// http://rust-lang.org/COPYRIGHT.
+//
+// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
+// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
+// <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your
+// option. This file may not be copied, modified, or distributed
+// except according to those terms.
+
+enum Foo {
+ Bar(int)
+}
+
+pub mod test {
+ enum Foo {
+ Bar(int)
+ }
+}
fn main() {
let args = os::args();
+ let args = args.as_slice();
let n_keys = {
if args.len() == 2 {
from_str::<uint>(args[1]).unwrap()
fn main() {
let args = os::args();
+ let args = args.as_slice();
let num_keys = {
if args.len() == 2 {
from_str::<uint>(args[1]).unwrap()
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() {
fn main() {
let args = os::args();
+ let args = args.as_slice();
let n = if args.len() == 3 {
from_str::<uint>(args[1]).unwrap()
} else {
fn main() {
let args = os::args();
+ let args = args.as_slice();
let n = if args.len() == 2 {
from_str::<uint>(args[1]).unwrap()
} else {
fn main() {
let args = os::args();
+ let args = args.as_slice();
let n = if args.len() == 2 {
from_str::<uint>(args[1]).unwrap()
} else {
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 {
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();
}
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) {
fn main() {
let args = os::args();
+ let args = args.as_slice();
let n = if args.len() > 1 {
from_str::<uint>(args[1]).unwrap()
} else {
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 {
// 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; }
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.");
}
}
}
- 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.
fn main () {
let args = std::os::args();
+ let args = args.as_slice();
let stop_after = if args.len() <= 1 {
2098
} else {
fn main() {
let args = std::os::args();
+ let args = args.as_slice();
let n = if args.len() < 2 {
512
} else {
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 {
fn main() {
let args = std::os::args();
+ let args = args.as_slice();
let token = if std::os::getenv("RUST_BENCH").is_some() {
2000000
} else {
--- /dev/null
+// Copyright 2014 The Rust Project Developers. See the COPYRIGHT
+// file at the top-level directory of this distribution and at
+// http://rust-lang.org/COPYRIGHT.
+//
+// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
+// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
+// <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your
+// option. This file may not be copied, modified, or distributed
+// except according to those terms.
+
+// This file must never have a trailing newline
+
+fn main() {
+ let x = Some(3);
+ let y = x.as_ref().unwrap_or(&5); //~ ERROR: borrowed value does not live long enough
+}
\ No newline at end of file
--- /dev/null
+// Copyright 2014 The Rust Project Developers. See the COPYRIGHT
+// file at the top-level directory of this distribution and at
+// http://rust-lang.org/COPYRIGHT.
+//
+// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
+// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
+// <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your
+// option. This file may not be copied, modified, or distributed
+// except according to those terms.
+
+// aux-build:issue-11680.rs
+
+extern crate other = "issue-11680";
+
+fn main() {
+ let _b = other::Bar(1);
+ //~^ ERROR: variant `Bar` is private
+
+ let _b = other::test::Bar(1);
+ //~^ ERROR: variant `Bar` is private
+}
match 30 {
mut x => {} //~ ERROR: variable does not need to be mutable
}
+ match (30, 2) {
+ (mut x, 1) | //~ ERROR: variable does not need to be mutable
+ (mut x, 2) |
+ (mut x, 3) => {
+ }
+ _ => {}
+ }
let x = |mut y: int| 10; //~ ERROR: variable does not need to be mutable
fn what(mut foo: int) {} //~ ERROR: variable does not need to be mutable
}
}
+ match (30, 2) {
+ (mut x, 1) |
+ (mut x, 2) |
+ (mut x, 3) => {
+ x = 21
+ }
+ _ => {}
+ }
+
let x = |mut y: int| y = 32;
fn nothing(mut foo: int) { foo = 37; }
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();
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();
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" {
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
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?");
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();
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();
fn parse_args() -> ~str {
let args = ::std::os::args();
+ let args = args.as_slice();
let mut n = 0;
while n < args.len() {
fn main() {
let args = os::args();
+ let args = args.as_slice();
if args.len() > 1 && args[1].as_slice() == "child" {
debug!("foo");
debug!("bar");
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" {
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());
}
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; }
fn main() {
let args = os::args();
+ let args = args.as_slice();
if args.len() > 1 && args[1].as_slice() == "test" {
return test();
}
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(", "))
}
}