auto merge of #13588 : alexcrichton/rust/no-more-growing, r=thestinger

This is all in preparation for DST. This removes all the growable/shrinkable methods from `~[T]`.
This commit is contained in:
bors 2014-04-18 11:41:23 -07:00
commit d1d8497e53
62 changed files with 484 additions and 1167 deletions

View File

@ -33,7 +33,6 @@ use std::os;
use std::str; use std::str;
use std::strbuf::StrBuf; use std::strbuf::StrBuf;
use std::task; use std::task;
use std::slice;
use test::MetricMap; use test::MetricMap;
pub fn run(config: config, testfile: ~str) { pub fn run(config: config, testfile: ~str) {
@ -509,7 +508,7 @@ fn check_expected_errors(expected_errors: Vec<errors::ExpectedError> ,
proc_res: &ProcRes) { proc_res: &ProcRes) {
// true if we found the error in question // true if we found the error in question
let mut found_flags = slice::from_elem( let mut found_flags = Vec::from_elem(
expected_errors.len(), false); expected_errors.len(), false);
if proc_res.status.success() { if proc_res.status.success() {
@ -554,13 +553,13 @@ fn check_expected_errors(expected_errors: Vec<errors::ExpectedError> ,
for line in proc_res.stderr.lines() { for line in proc_res.stderr.lines() {
let mut was_expected = false; let mut was_expected = false;
for (i, ee) in expected_errors.iter().enumerate() { for (i, ee) in expected_errors.iter().enumerate() {
if !found_flags[i] { if !*found_flags.get(i) {
debug!("prefix={} ee.kind={} ee.msg={} line={}", debug!("prefix={} ee.kind={} ee.msg={} line={}",
*prefixes.get(i), ee.kind, ee.msg, line); *prefixes.get(i), ee.kind, ee.msg, line);
if prefix_matches(line, *prefixes.get(i)) && if prefix_matches(line, *prefixes.get(i)) &&
line.contains(ee.kind) && line.contains(ee.kind) &&
line.contains(ee.msg) { line.contains(ee.msg) {
found_flags[i] = true; *found_flags.get_mut(i) = true;
was_expected = true; was_expected = true;
break; break;
} }

View File

@ -255,10 +255,9 @@ might look like the example below.
~~~ ~~~
# use std::task::spawn; # use std::task::spawn;
# use std::slice;
// Create a vector of ports, one for each child task // Create a vector of ports, one for each child task
let rxs = slice::from_fn(3, |init_val| { let rxs = Vec::from_fn(3, |init_val| {
let (tx, rx) = channel(); let (tx, rx) = channel();
spawn(proc() { spawn(proc() {
tx.send(some_expensive_computation(init_val)); tx.send(some_expensive_computation(init_val));
@ -304,7 +303,6 @@ be distributed on the available cores.
~~~ ~~~
# extern crate sync; # extern crate sync;
# use std::slice;
fn partial_sum(start: uint) -> f64 { fn partial_sum(start: uint) -> f64 {
let mut local_sum = 0f64; let mut local_sum = 0f64;
for num in range(start*100000, (start+1)*100000) { for num in range(start*100000, (start+1)*100000) {
@ -314,7 +312,7 @@ fn partial_sum(start: uint) -> f64 {
} }
fn main() { fn main() {
let mut futures = slice::from_fn(1000, |ind| sync::Future::spawn( proc() { partial_sum(ind) })); let mut futures = Vec::from_fn(1000, |ind| sync::Future::spawn( proc() { partial_sum(ind) }));
let mut final_res = 0f64; let mut final_res = 0f64;
for ft in futures.mut_iter() { for ft in futures.mut_iter() {
@ -342,15 +340,14 @@ a single large vector of floats. Each task needs the full vector to perform its
extern crate rand; extern crate rand;
extern crate sync; extern crate sync;
use std::slice;
use sync::Arc; use sync::Arc;
fn pnorm(nums: &~[f64], p: uint) -> f64 { fn pnorm(nums: &[f64], p: uint) -> f64 {
nums.iter().fold(0.0, |a,b| a+(*b).powf(&(p as f64)) ).powf(&(1.0 / (p as f64))) nums.iter().fold(0.0, |a,b| a+(*b).powf(&(p as f64)) ).powf(&(1.0 / (p as f64)))
} }
fn main() { fn main() {
let numbers = slice::from_fn(1000000, |_| rand::random::<f64>()); let numbers = Vec::from_fn(1000000, |_| rand::random::<f64>());
let numbers_arc = Arc::new(numbers); let numbers_arc = Arc::new(numbers);
for num in range(1u, 10) { for num in range(1u, 10) {
@ -358,9 +355,9 @@ fn main() {
tx.send(numbers_arc.clone()); tx.send(numbers_arc.clone());
spawn(proc() { spawn(proc() {
let local_arc : Arc<~[f64]> = rx.recv(); let local_arc : Arc<Vec<f64>> = rx.recv();
let task_numbers = &*local_arc; let task_numbers = &*local_arc;
println!("{}-norm = {}", num, pnorm(task_numbers, num)); println!("{}-norm = {}", num, pnorm(task_numbers.as_slice(), num));
}); });
} }
} }
@ -374,9 +371,8 @@ created by the line
# extern crate sync; # extern crate sync;
# extern crate rand; # extern crate rand;
# use sync::Arc; # use sync::Arc;
# use std::slice;
# fn main() { # fn main() {
# let numbers = slice::from_fn(1000000, |_| rand::random::<f64>()); # let numbers = Vec::from_fn(1000000, |_| rand::random::<f64>());
let numbers_arc=Arc::new(numbers); let numbers_arc=Arc::new(numbers);
# } # }
~~~ ~~~
@ -387,9 +383,8 @@ and a clone of it is sent to each task
# extern crate sync; # extern crate sync;
# extern crate rand; # extern crate rand;
# use sync::Arc; # use sync::Arc;
# use std::slice;
# fn main() { # fn main() {
# let numbers=slice::from_fn(1000000, |_| rand::random::<f64>()); # let numbers=Vec::from_fn(1000000, |_| rand::random::<f64>());
# let numbers_arc = Arc::new(numbers); # let numbers_arc = Arc::new(numbers);
# let (tx, rx) = channel(); # let (tx, rx) = channel();
tx.send(numbers_arc.clone()); tx.send(numbers_arc.clone());
@ -404,13 +399,12 @@ Each task recovers the underlying data by
# extern crate sync; # extern crate sync;
# extern crate rand; # extern crate rand;
# use sync::Arc; # use sync::Arc;
# use std::slice;
# fn main() { # fn main() {
# let numbers=slice::from_fn(1000000, |_| rand::random::<f64>()); # let numbers=Vec::from_fn(1000000, |_| rand::random::<f64>());
# let numbers_arc=Arc::new(numbers); # let numbers_arc=Arc::new(numbers);
# let (tx, rx) = channel(); # let (tx, rx) = channel();
# tx.send(numbers_arc.clone()); # tx.send(numbers_arc.clone());
# let local_arc : Arc<~[f64]> = rx.recv(); # let local_arc : Arc<Vec<f64>> = rx.recv();
let task_numbers = &*local_arc; let task_numbers = &*local_arc;
# } # }
~~~ ~~~

View File

@ -1582,12 +1582,12 @@ the elements are mutable if the vector is mutable.
use std::strbuf::StrBuf; use std::strbuf::StrBuf;
// A dynamically sized vector (unique vector) // A dynamically sized vector (unique vector)
let mut numbers = ~[1, 2, 3]; let mut numbers = vec![1, 2, 3];
numbers.push(4); numbers.push(4);
numbers.push(5); numbers.push(5);
// The type of a unique vector is written as `~[int]` // The type of a unique vector is written as `~[int]`
let more_numbers: ~[int] = numbers; let more_numbers: ~[int] = numbers.move_iter().collect();
// The original `numbers` value can no longer be used, due to move semantics. // The original `numbers` value can no longer be used, due to move semantics.
@ -1955,8 +1955,8 @@ vector consisting of the result of applying `function` to each element
of `vector`: of `vector`:
~~~~ ~~~~
fn map<T, U>(vector: &[T], function: |v: &T| -> U) -> ~[U] { fn map<T, U>(vector: &[T], function: |v: &T| -> U) -> Vec<U> {
let mut accumulator = ~[]; let mut accumulator = Vec::new();
for element in vector.iter() { for element in vector.iter() {
accumulator.push(function(element)); accumulator.push(function(element));
} }

View File

@ -57,7 +57,7 @@ impl GetAddrInfoRequest {
} }
// Collect all the results we found // Collect all the results we found
let mut addrs = ~[]; let mut addrs = Vec::new();
let mut rp = res; let mut rp = res;
while rp.is_not_null() { while rp.is_not_null() {
unsafe { unsafe {
@ -80,7 +80,7 @@ impl GetAddrInfoRequest {
unsafe { freeaddrinfo(res); } unsafe { freeaddrinfo(res); }
Ok(addrs) Ok(addrs.move_iter().collect())
} }
} }

View File

@ -18,7 +18,6 @@ use libc::{c_int, c_void};
use libc; use libc;
use std::mem; use std::mem;
use std::rt::rtio; use std::rt::rtio;
use std::slice;
use io::{IoResult, retry, keep_going}; use io::{IoResult, retry, keep_going};
@ -416,7 +415,7 @@ pub fn readlink(p: &CString) -> IoResult<Path> {
if len == -1 { if len == -1 {
len = 1024; // FIXME: read PATH_MAX from C ffi? len = 1024; // FIXME: read PATH_MAX from C ffi?
} }
let mut buf = slice::with_capacity::<u8>(len as uint); let mut buf: Vec<u8> = Vec::with_capacity(len as uint);
match retry(|| unsafe { match retry(|| unsafe {
libc::readlink(p, buf.as_ptr() as *mut libc::c_char, libc::readlink(p, buf.as_ptr() as *mut libc::c_char,
len as libc::size_t) as libc::c_int len as libc::size_t) as libc::c_int

View File

@ -74,7 +74,7 @@ impl Process {
return Err(super::unimpl()); return Err(super::unimpl());
} }
fn get_io(io: p::StdioContainer, ret: &mut ~[Option<file::FileDesc>]) fn get_io(io: p::StdioContainer, ret: &mut Vec<Option<file::FileDesc>>)
-> (Option<os::Pipe>, c_int) -> (Option<os::Pipe>, c_int)
{ {
match io { match io {
@ -93,7 +93,7 @@ impl Process {
} }
} }
let mut ret_io = ~[]; let mut ret_io = Vec::new();
let (in_pipe, in_fd) = get_io(config.stdin, &mut ret_io); let (in_pipe, in_fd) = get_io(config.stdin, &mut ret_io);
let (out_pipe, out_fd) = get_io(config.stdout, &mut ret_io); let (out_pipe, out_fd) = get_io(config.stdout, &mut ret_io);
let (err_pipe, err_fd) = get_io(config.stderr, &mut ret_io); let (err_pipe, err_fd) = get_io(config.stderr, &mut ret_io);
@ -117,7 +117,7 @@ impl Process {
exit_code: None, exit_code: None,
exit_signal: None, exit_signal: None,
}, },
ret_io)) ret_io.move_iter().collect()))
} }
Err(e) => Err(e) Err(e) => Err(e)
} }
@ -641,12 +641,10 @@ fn spawn_process_os(config: p::ProcessConfig,
#[cfg(unix)] #[cfg(unix)]
fn with_argv<T>(prog: &str, args: &[~str], cb: proc(**libc::c_char) -> T) -> T { fn with_argv<T>(prog: &str, args: &[~str], cb: proc(**libc::c_char) -> T) -> T {
use std::slice;
// We can't directly convert `str`s into `*char`s, as someone needs to hold // We can't directly convert `str`s into `*char`s, as someone needs to hold
// a reference to the intermediary byte buffers. So first build an array to // a reference to the intermediary byte buffers. So first build an array to
// hold all the ~[u8] byte strings. // hold all the ~[u8] byte strings.
let mut tmps = slice::with_capacity(args.len() + 1); let mut tmps = Vec::with_capacity(args.len() + 1);
tmps.push(prog.to_c_str()); tmps.push(prog.to_c_str());
@ -667,14 +665,12 @@ fn with_argv<T>(prog: &str, args: &[~str], cb: proc(**libc::c_char) -> T) -> T {
#[cfg(unix)] #[cfg(unix)]
fn with_envp<T>(env: Option<~[(~str, ~str)]>, cb: proc(*c_void) -> T) -> T { fn with_envp<T>(env: Option<~[(~str, ~str)]>, cb: proc(*c_void) -> T) -> T {
use std::slice;
// On posixy systems we can pass a char** for envp, which is a // On posixy systems we can pass a char** for envp, which is a
// null-terminated array of "k=v\n" strings. Like `with_argv`, we have to // null-terminated array of "k=v\n" strings. Like `with_argv`, we have to
// have a temporary buffer to hold the intermediary `~[u8]` byte strings. // have a temporary buffer to hold the intermediary `~[u8]` byte strings.
match env { match env {
Some(env) => { Some(env) => {
let mut tmps = slice::with_capacity(env.len()); let mut tmps = Vec::with_capacity(env.len());
for pair in env.iter() { for pair in env.iter() {
let kv = format!("{}={}", *pair.ref0(), *pair.ref1()); let kv = format!("{}={}", *pair.ref0(), *pair.ref1());
@ -700,7 +696,7 @@ fn with_envp<T>(env: Option<~[(~str, ~str)]>, cb: |*mut c_void| -> T) -> T {
// \0 to terminate. // \0 to terminate.
match env { match env {
Some(env) => { Some(env) => {
let mut blk = ~[]; let mut blk = Vec::new();
for pair in env.iter() { for pair in env.iter() {
let kv = format!("{}={}", *pair.ref0(), *pair.ref1()); let kv = format!("{}={}", *pair.ref0(), *pair.ref1());

View File

@ -156,8 +156,6 @@ pub fn minimize_rpaths(rpaths: &[~str]) -> Vec<~str> {
#[cfg(unix, test)] #[cfg(unix, test)]
mod test { mod test {
use std::os;
use back::rpath::get_install_prefix_rpath; use back::rpath::get_install_prefix_rpath;
use back::rpath::{minimize_rpaths, rpaths_to_flags, get_rpath_relative_to_output}; use back::rpath::{minimize_rpaths, rpaths_to_flags, get_rpath_relative_to_output};
use syntax::abi; use syntax::abi;

View File

@ -223,13 +223,13 @@ pub fn describe_codegen_flags() {
} }
pub fn run_compiler(args: &[~str]) { pub fn run_compiler(args: &[~str]) {
let mut args = args.to_owned(); let mut args = Vec::from_slice(args);
let binary = args.shift().unwrap(); let binary = args.shift().unwrap();
if args.is_empty() { usage(binary); return; } if args.is_empty() { usage(binary); return; }
let matches = let matches =
&match getopts::getopts(args, d::optgroups().as_slice()) { &match getopts::getopts(args.as_slice(), d::optgroups().as_slice()) {
Ok(m) => m, Ok(m) => m,
Err(f) => { Err(f) => {
d::early_error(f.to_err_msg()); d::early_error(f.to_err_msg());

View File

@ -18,7 +18,6 @@
use std::io; use std::io;
use std::slice;
use std::strbuf::StrBuf; use std::strbuf::StrBuf;
use std::uint; use std::uint;
use syntax::ast; use syntax::ast;
@ -308,13 +307,13 @@ impl<'a, O:DataFlowOperator+Clone+'static> DataFlowContext<'a, O> {
changed: true changed: true
}; };
let mut temp = slice::from_elem(self.words_per_id, 0u); let mut temp = Vec::from_elem(self.words_per_id, 0u);
let mut loop_scopes = Vec::new(); let mut loop_scopes = Vec::new();
while propcx.changed { while propcx.changed {
propcx.changed = false; propcx.changed = false;
propcx.reset(temp); propcx.reset(temp.as_mut_slice());
propcx.walk_block(blk, temp, &mut loop_scopes); propcx.walk_block(blk, temp.as_mut_slice(), &mut loop_scopes);
} }
} }

View File

@ -16,8 +16,6 @@
* closure. * closure.
*/ */
use std::slice;
use back::abi; use back::abi;
use driver::session; use driver::session;
use lib::llvm::{ValueRef, NoAliasAttribute, StructRetAttribute, NoCaptureAttribute}; use lib::llvm::{ValueRef, NoAliasAttribute, StructRetAttribute, NoCaptureAttribute};
@ -221,11 +219,12 @@ fn resolve_default_method_vtables(bcx: &Block,
Some(vtables) => { Some(vtables) => {
let num_impl_type_parameters = let num_impl_type_parameters =
vtables.len() - num_method_vtables; vtables.len() - num_method_vtables;
vtables.tailn(num_impl_type_parameters).to_owned() Vec::from_slice(vtables.tailn(num_impl_type_parameters))
}, },
None => slice::from_elem(num_method_vtables, @Vec::new()) None => Vec::from_elem(num_method_vtables, @Vec::new())
}; };
let method_vtables = method_vtables.as_slice();
let param_vtables = @((*trait_vtables_fixed).clone().append(method_vtables)); let param_vtables = @((*trait_vtables_fixed).clone().append(method_vtables));
let self_vtables = resolve_param_vtables_under_param_substs( let self_vtables = resolve_param_vtables_under_param_substs(

View File

@ -593,11 +593,11 @@ fn const_expr_unadjusted(cx: &CrateContext, e: &ast::Expr,
const_eval::const_uint(i) => i as uint, const_eval::const_uint(i) => i as uint,
_ => cx.sess().span_bug(count.span, "count must be integral const expression.") _ => cx.sess().span_bug(count.span, "count must be integral const expression.")
}; };
let vs = slice::from_elem(n, const_expr(cx, elem, is_local).val0()); let vs = Vec::from_elem(n, const_expr(cx, elem, is_local).val0());
let v = if vs.iter().any(|vi| val_ty(*vi) != llunitty) { let v = if vs.iter().any(|vi| val_ty(*vi) != llunitty) {
C_struct(cx, vs, false) C_struct(cx, vs.as_slice(), false)
} else { } else {
C_array(llunitty, vs) C_array(llunitty, vs.as_slice())
}; };
(v, true) (v, true)
} }

View File

@ -148,7 +148,6 @@ use collections::HashMap;
use collections::HashSet; use collections::HashSet;
use libc::{c_uint, c_ulonglong, c_longlong}; use libc::{c_uint, c_ulonglong, c_longlong};
use std::ptr; use std::ptr;
use std::slice;
use std::strbuf::StrBuf; use std::strbuf::StrBuf;
use std::sync::atomics; use std::sync::atomics;
use syntax::codemap::{Span, Pos}; use syntax::codemap::{Span, Pos};
@ -776,7 +775,7 @@ pub fn create_function_debug_context(cx: &CrateContext,
return create_DIArray(DIB(cx), []); return create_DIArray(DIB(cx), []);
} }
let mut signature = slice::with_capacity(fn_decl.inputs.len() + 1); let mut signature = Vec::with_capacity(fn_decl.inputs.len() + 1);
// Return type -- llvm::DIBuilder wants this at index 0 // Return type -- llvm::DIBuilder wants this at index 0
match fn_decl.output.node { match fn_decl.output.node {
@ -818,7 +817,7 @@ pub fn create_function_debug_context(cx: &CrateContext,
signature.push(type_metadata(cx, arg_type, codemap::DUMMY_SP)); signature.push(type_metadata(cx, arg_type, codemap::DUMMY_SP));
} }
return create_DIArray(DIB(cx), signature); return create_DIArray(DIB(cx), signature.as_slice());
} }
fn get_template_parameters(cx: &CrateContext, fn get_template_parameters(cx: &CrateContext,
@ -961,7 +960,7 @@ fn compile_unit_metadata(cx: &CrateContext) {
// prepend "./" if necessary // prepend "./" if necessary
let dotdot = bytes!(".."); let dotdot = bytes!("..");
let prefix = &[dotdot[0], ::std::path::SEP_BYTE]; let prefix = &[dotdot[0], ::std::path::SEP_BYTE];
let mut path_bytes = p.as_vec().to_owned(); let mut path_bytes = Vec::from_slice(p.as_vec());
if path_bytes.slice_to(2) != prefix && if path_bytes.slice_to(2) != prefix &&
path_bytes.slice_to(2) != dotdot { path_bytes.slice_to(2) != dotdot {
@ -969,7 +968,7 @@ fn compile_unit_metadata(cx: &CrateContext) {
path_bytes.insert(1, prefix[1]); path_bytes.insert(1, prefix[1]);
} }
path_bytes.to_c_str() path_bytes.as_slice().to_c_str()
} }
_ => fallback_path(cx) _ => fallback_path(cx)
} }

View File

@ -71,7 +71,6 @@ use util::nodemap::NodeMap;
use middle::trans::machine::{llsize_of, llsize_of_alloc}; use middle::trans::machine::{llsize_of, llsize_of_alloc};
use middle::trans::type_::Type; use middle::trans::type_::Type;
use std::slice;
use syntax::ast; use syntax::ast;
use syntax::codemap; use syntax::codemap;
use syntax::print::pprust::{expr_to_str}; use syntax::print::pprust::{expr_to_str};
@ -969,7 +968,7 @@ fn trans_rec_or_struct<'a>(
let ty = node_id_type(bcx, id); let ty = node_id_type(bcx, id);
let tcx = bcx.tcx(); let tcx = bcx.tcx();
with_field_tys(tcx, ty, Some(id), |discr, field_tys| { with_field_tys(tcx, ty, Some(id), |discr, field_tys| {
let mut need_base = slice::from_elem(field_tys.len(), true); let mut need_base = Vec::from_elem(field_tys.len(), true);
let numbered_fields = fields.iter().map(|field| { let numbered_fields = fields.iter().map(|field| {
let opt_pos = let opt_pos =
@ -977,7 +976,7 @@ fn trans_rec_or_struct<'a>(
field_ty.ident.name == field.ident.node.name); field_ty.ident.name == field.ident.node.name);
match opt_pos { match opt_pos {
Some(i) => { Some(i) => {
need_base[i] = false; *need_base.get_mut(i) = false;
(i, field.expr) (i, field.expr)
} }
None => { None => {

View File

@ -118,7 +118,6 @@ use std::cell::{Cell, RefCell};
use collections::HashMap; use collections::HashMap;
use std::mem::replace; use std::mem::replace;
use std::result; use std::result;
use std::slice;
use std::vec::Vec; use std::vec::Vec;
use syntax::abi; use syntax::abi;
use syntax::ast::{Provided, Required}; use syntax::ast::{Provided, Required};
@ -3906,13 +3905,13 @@ pub fn check_bounds_are_used(ccx: &CrateCtxt,
// make a vector of booleans initially false, set to true when used // make a vector of booleans initially false, set to true when used
if tps.len() == 0u { return; } if tps.len() == 0u { return; }
let mut tps_used = slice::from_elem(tps.len(), false); let mut tps_used = Vec::from_elem(tps.len(), false);
ty::walk_ty(ty, |t| { ty::walk_ty(ty, |t| {
match ty::get(t).sty { match ty::get(t).sty {
ty::ty_param(param_ty {idx, ..}) => { ty::ty_param(param_ty {idx, ..}) => {
debug!("Found use of ty param \\#{}", idx); debug!("Found use of ty param \\#{}", idx);
tps_used[idx] = true; *tps_used.get_mut(idx) = true;
} }
_ => () _ => ()
} }

View File

@ -26,7 +26,6 @@ use util::ppaux::{Repr};
use std::cell::{Cell, RefCell}; use std::cell::{Cell, RefCell};
use std::uint; use std::uint;
use std::slice;
use collections::{HashMap, HashSet}; use collections::{HashMap, HashSet};
use syntax::ast; use syntax::ast;
@ -1004,7 +1003,7 @@ impl<'a> RegionVarBindings<'a> {
// idea is to report errors that derive from independent // idea is to report errors that derive from independent
// regions of the graph, but not those that derive from // regions of the graph, but not those that derive from
// overlapping locations. // overlapping locations.
let mut dup_vec = slice::from_elem(self.num_vars(), uint::MAX); let mut dup_vec = Vec::from_elem(self.num_vars(), uint::MAX);
let mut opt_graph = None; let mut opt_graph = None;
@ -1052,11 +1051,13 @@ impl<'a> RegionVarBindings<'a> {
match var_data[idx].classification { match var_data[idx].classification {
Expanding => { Expanding => {
self.collect_error_for_expanding_node( self.collect_error_for_expanding_node(
graph, var_data, dup_vec, node_vid, errors); graph, var_data, dup_vec.as_mut_slice(),
node_vid, errors);
} }
Contracting => { Contracting => {
self.collect_error_for_contracting_node( self.collect_error_for_contracting_node(
graph, var_data, dup_vec, node_vid, errors); graph, var_data, dup_vec.as_mut_slice(),
node_vid, errors);
} }
} }
} }

View File

@ -525,7 +525,6 @@ mod tests {
use super::{Digest, Sha256, FixedBuffer}; use super::{Digest, Sha256, FixedBuffer};
use std::num::Bounded; use std::num::Bounded;
use std::slice;
use self::rand::isaac::IsaacRng; use self::rand::isaac::IsaacRng;
use self::rand::Rng; use self::rand::Rng;
use serialize::hex::FromHex; use serialize::hex::FromHex;
@ -600,7 +599,7 @@ mod tests {
/// correct. /// correct.
fn test_digest_1million_random<D: Digest>(digest: &mut D, blocksize: uint, expected: &str) { fn test_digest_1million_random<D: Digest>(digest: &mut D, blocksize: uint, expected: &str) {
let total_size = 1000000; let total_size = 1000000;
let buffer = slice::from_elem(blocksize * 2, 'a' as u8); let buffer = Vec::from_elem(blocksize * 2, 'a' as u8);
let mut rng = IsaacRng::new_unseeded(); let mut rng = IsaacRng::new_unseeded();
let mut count = 0; let mut count = 0;

View File

@ -38,7 +38,6 @@ use std::fmt;
use std::io::{fs, File, BufferedWriter, MemWriter, BufferedReader}; use std::io::{fs, File, BufferedWriter, MemWriter, BufferedReader};
use std::io; use std::io;
use std::local_data; use std::local_data;
use std::slice;
use std::str; use std::str;
use std::strbuf::StrBuf; use std::strbuf::StrBuf;
@ -1047,7 +1046,7 @@ fn item_module(w: &mut Writer, cx: &Context,
item: &clean::Item, items: &[clean::Item]) -> fmt::Result { item: &clean::Item, items: &[clean::Item]) -> fmt::Result {
try!(document(w, item)); try!(document(w, item));
debug!("{:?}", items); debug!("{:?}", items);
let mut indices = slice::from_fn(items.len(), |i| i); let mut indices = Vec::from_fn(items.len(), |i| i);
fn cmp(i1: &clean::Item, i2: &clean::Item, idx1: uint, idx2: uint) -> Ordering { fn cmp(i1: &clean::Item, i2: &clean::Item, idx1: uint, idx2: uint) -> Ordering {
if shortty(i1) == shortty(i2) { if shortty(i1) == shortty(i2) {

View File

@ -169,8 +169,8 @@ fn runtest(test: &str, cratename: &str, libs: HashSet<Path>, should_fail: bool,
fn maketest(s: &str, cratename: &str, loose_feature_gating: bool) -> ~str { fn maketest(s: &str, cratename: &str, loose_feature_gating: bool) -> ~str {
let mut prog = StrBuf::from_str(r" let mut prog = StrBuf::from_str(r"
#![deny(warnings)]; #![deny(warnings)]
#![allow(unused_variable, dead_assignment, unused_mut, attribute_usage, dead_code)]; #![allow(unused_variable, dead_assignment, unused_mut, attribute_usage, dead_code)]
"); ");
if loose_feature_gating { if loose_feature_gating {

View File

@ -138,7 +138,7 @@ pub fn accum_addrinfo(addr: &Addrinfo) -> ~[ai::Info] {
unsafe { unsafe {
let mut addr = addr.handle; let mut addr = addr.handle;
let mut addrs = ~[]; let mut addrs = Vec::new();
loop { loop {
let rustaddr = net::sockaddr_to_addr(cast::transmute((*addr).ai_addr), let rustaddr = net::sockaddr_to_addr(cast::transmute((*addr).ai_addr),
(*addr).ai_addrlen as uint); (*addr).ai_addrlen as uint);
@ -180,6 +180,6 @@ pub fn accum_addrinfo(addr: &Addrinfo) -> ~[ai::Info] {
} }
} }
return addrs; return addrs.move_iter().collect();
} }
} }

View File

@ -469,7 +469,6 @@ mod test {
use libc::{O_CREAT, O_RDWR, O_RDONLY, S_IWUSR, S_IRUSR}; use libc::{O_CREAT, O_RDWR, O_RDONLY, S_IWUSR, S_IRUSR};
use std::io; use std::io;
use std::str; use std::str;
use std::slice;
use super::FsRequest; use super::FsRequest;
use super::super::Loop; use super::super::Loop;
use super::super::local_loop; use super::super::local_loop;
@ -505,8 +504,8 @@ mod test {
let fd = result.fd; let fd = result.fd;
// read // read
let mut read_mem = slice::from_elem(1000, 0u8); let mut read_mem = Vec::from_elem(1000, 0u8);
let result = FsRequest::read(l(), fd, read_mem, 0); let result = FsRequest::read(l(), fd, read_mem.as_mut_slice(), 0);
assert!(result.is_ok()); assert!(result.is_ok());
let nread = result.unwrap(); let nread = result.unwrap();

View File

@ -15,7 +15,6 @@ use libc;
use std::ptr; use std::ptr;
use std::rt::rtio::RtioProcess; use std::rt::rtio::RtioProcess;
use std::rt::task::BlockedTask; use std::rt::task::BlockedTask;
use std::slice;
use homing::{HomingIO, HomeHandle}; use homing::{HomingIO, HomeHandle};
use pipe::PipeWatcher; use pipe::PipeWatcher;
@ -44,12 +43,12 @@ impl Process {
-> Result<(~Process, ~[Option<PipeWatcher>]), UvError> -> Result<(~Process, ~[Option<PipeWatcher>]), UvError>
{ {
let cwd = config.cwd.map(|s| s.to_c_str()); let cwd = config.cwd.map(|s| s.to_c_str());
let mut io = ~[config.stdin, config.stdout, config.stderr]; let mut io = vec![config.stdin, config.stdout, config.stderr];
for slot in config.extra_io.iter() { for slot in config.extra_io.iter() {
io.push(*slot); io.push(*slot);
} }
let mut stdio = slice::with_capacity::<uvll::uv_stdio_container_t>(io.len()); let mut stdio = Vec::<uvll::uv_stdio_container_t>::with_capacity(io.len());
let mut ret_io = slice::with_capacity(io.len()); let mut ret_io = Vec::with_capacity(io.len());
unsafe { unsafe {
stdio.set_len(io.len()); stdio.set_len(io.len());
for (slot, other) in stdio.iter().zip(io.iter()) { for (slot, other) in stdio.iter().zip(io.iter()) {
@ -104,7 +103,7 @@ impl Process {
}); });
match ret { match ret {
Ok(p) => Ok((p, ret_io)), Ok(p) => Ok((p, ret_io.move_iter().collect())),
Err(e) => Err(e), Err(e) => Err(e),
} }
} }
@ -167,14 +166,14 @@ unsafe fn set_stdio(dst: *uvll::uv_stdio_container_t,
fn with_argv<T>(prog: &str, args: &[~str], f: |**libc::c_char| -> T) -> T { fn with_argv<T>(prog: &str, args: &[~str], f: |**libc::c_char| -> T) -> T {
// First, allocation space to put all the C-strings (we need to have // First, allocation space to put all the C-strings (we need to have
// ownership of them somewhere // ownership of them somewhere
let mut c_strs = slice::with_capacity(args.len() + 1); let mut c_strs = Vec::with_capacity(args.len() + 1);
c_strs.push(prog.to_c_str()); c_strs.push(prog.to_c_str());
for arg in args.iter() { for arg in args.iter() {
c_strs.push(arg.to_c_str()); c_strs.push(arg.to_c_str());
} }
// Next, create the char** array // Next, create the char** array
let mut c_args = slice::with_capacity(c_strs.len() + 1); let mut c_args = Vec::with_capacity(c_strs.len() + 1);
for s in c_strs.iter() { for s in c_strs.iter() {
c_args.push(s.with_ref(|p| p)); c_args.push(s.with_ref(|p| p));
} }
@ -189,11 +188,11 @@ fn with_env<T>(env: Option<&[(~str, ~str)]>, f: |**libc::c_char| -> T) -> T {
None => { return f(ptr::null()); } None => { return f(ptr::null()); }
}; };
// As with argv, create some temporary storage and then the actual array // As with argv, create some temporary storage and then the actual array
let mut envp = slice::with_capacity(env.len()); let mut envp = Vec::with_capacity(env.len());
for &(ref key, ref value) in env.iter() { for &(ref key, ref value) in env.iter() {
envp.push(format!("{}={}", *key, *value).to_c_str()); envp.push(format!("{}={}", *key, *value).to_c_str());
} }
let mut c_envp = slice::with_capacity(envp.len() + 1); let mut c_envp = Vec::with_capacity(envp.len() + 1);
for s in envp.iter() { for s in envp.iter() {
c_envp.push(s.with_ref(|p| p)); c_envp.push(s.with_ref(|p| p));
} }

View File

@ -79,7 +79,7 @@ impl<'a> ToBase64 for &'a [u8] {
UrlSafe => URLSAFE_CHARS UrlSafe => URLSAFE_CHARS
}; };
let mut v: ~[u8] = ~[]; let mut v = Vec::new();
let mut i = 0; let mut i = 0;
let mut cur_length = 0; let mut cur_length = 0;
let len = self.len(); let len = self.len();
@ -146,7 +146,7 @@ impl<'a> ToBase64 for &'a [u8] {
} }
unsafe { unsafe {
str::raw::from_utf8_owned(v) str::raw::from_utf8_owned(v.move_iter().collect())
} }
} }
} }
@ -208,7 +208,7 @@ impl<'a> FromBase64 for &'a str {
* ``` * ```
*/ */
fn from_base64(&self) -> Result<~[u8], FromBase64Error> { fn from_base64(&self) -> Result<~[u8], FromBase64Error> {
let mut r = ~[]; let mut r = Vec::new();
let mut buf: u32 = 0; let mut buf: u32 = 0;
let mut modulus = 0; let mut modulus = 0;
@ -256,7 +256,7 @@ impl<'a> FromBase64 for &'a str {
_ => return Err(InvalidBase64Length), _ => return Err(InvalidBase64Length),
} }
Ok(r) Ok(r.move_iter().collect())
} }
} }
@ -337,12 +337,12 @@ mod tests {
#[test] #[test]
fn test_base64_random() { fn test_base64_random() {
use self::rand::{task_rng, random, Rng}; use self::rand::{task_rng, random, Rng};
use std::slice;
for _ in range(0, 1000) { for _ in range(0, 1000) {
let times = task_rng().gen_range(1u, 100); let times = task_rng().gen_range(1u, 100);
let v = slice::from_fn(times, |_| random::<u8>()); let v = Vec::from_fn(times, |_| random::<u8>());
assert_eq!(v.to_base64(STANDARD).from_base64().unwrap(), v); assert_eq!(v.as_slice().to_base64(STANDARD).from_base64().unwrap(),
v.as_slice().to_owned());
} }
} }

View File

@ -1099,8 +1099,7 @@ mod bench {
#[bench] #[bench]
pub fn vuint_at_A_aligned(b: &mut Bencher) { pub fn vuint_at_A_aligned(b: &mut Bencher) {
use std::slice; let data = Vec::from_fn(4*100, |i| {
let data = slice::from_fn(4*100, |i| {
match i % 2 { match i % 2 {
0 => 0x80u8, 0 => 0x80u8,
_ => i as u8, _ => i as u8,
@ -1110,7 +1109,7 @@ mod bench {
b.iter(|| { b.iter(|| {
let mut i = 0; let mut i = 0;
while i < data.len() { while i < data.len() {
sum += reader::vuint_at(data, i).unwrap().val; sum += reader::vuint_at(data.as_slice(), i).unwrap().val;
i += 4; i += 4;
} }
}); });
@ -1118,8 +1117,7 @@ mod bench {
#[bench] #[bench]
pub fn vuint_at_A_unaligned(b: &mut Bencher) { pub fn vuint_at_A_unaligned(b: &mut Bencher) {
use std::slice; let data = Vec::from_fn(4*100+1, |i| {
let data = slice::from_fn(4*100+1, |i| {
match i % 2 { match i % 2 {
1 => 0x80u8, 1 => 0x80u8,
_ => i as u8 _ => i as u8
@ -1129,7 +1127,7 @@ mod bench {
b.iter(|| { b.iter(|| {
let mut i = 1; let mut i = 1;
while i < data.len() { while i < data.len() {
sum += reader::vuint_at(data, i).unwrap().val; sum += reader::vuint_at(data.as_slice(), i).unwrap().val;
i += 4; i += 4;
} }
}); });
@ -1137,8 +1135,7 @@ mod bench {
#[bench] #[bench]
pub fn vuint_at_D_aligned(b: &mut Bencher) { pub fn vuint_at_D_aligned(b: &mut Bencher) {
use std::slice; let data = Vec::from_fn(4*100, |i| {
let data = slice::from_fn(4*100, |i| {
match i % 4 { match i % 4 {
0 => 0x10u8, 0 => 0x10u8,
3 => i as u8, 3 => i as u8,
@ -1149,7 +1146,7 @@ mod bench {
b.iter(|| { b.iter(|| {
let mut i = 0; let mut i = 0;
while i < data.len() { while i < data.len() {
sum += reader::vuint_at(data, i).unwrap().val; sum += reader::vuint_at(data.as_slice(), i).unwrap().val;
i += 4; i += 4;
} }
}); });
@ -1157,8 +1154,7 @@ mod bench {
#[bench] #[bench]
pub fn vuint_at_D_unaligned(b: &mut Bencher) { pub fn vuint_at_D_unaligned(b: &mut Bencher) {
use std::slice; let data = Vec::from_fn(4*100+1, |i| {
let data = slice::from_fn(4*100+1, |i| {
match i % 4 { match i % 4 {
1 => 0x10u8, 1 => 0x10u8,
0 => i as u8, 0 => i as u8,
@ -1169,7 +1165,7 @@ mod bench {
b.iter(|| { b.iter(|| {
let mut i = 1; let mut i = 1;
while i < data.len() { while i < data.len() {
sum += reader::vuint_at(data, i).unwrap().val; sum += reader::vuint_at(data.as_slice(), i).unwrap().val;
i += 4; i += 4;
} }
}); });

View File

@ -10,7 +10,6 @@
//! Hex binary-to-text encoding //! Hex binary-to-text encoding
use std::str; use std::str;
use std::slice;
use std::fmt; use std::fmt;
/// A trait for converting a value to hexadecimal encoding /// A trait for converting a value to hexadecimal encoding
@ -39,14 +38,14 @@ impl<'a> ToHex for &'a [u8] {
* ``` * ```
*/ */
fn to_hex(&self) -> ~str { fn to_hex(&self) -> ~str {
let mut v = slice::with_capacity(self.len() * 2); let mut v = Vec::with_capacity(self.len() * 2);
for &byte in self.iter() { for &byte in self.iter() {
v.push(CHARS[(byte >> 4) as uint]); v.push(CHARS[(byte >> 4) as uint]);
v.push(CHARS[(byte & 0xf) as uint]); v.push(CHARS[(byte & 0xf) as uint]);
} }
unsafe { unsafe {
str::raw::from_utf8_owned(v) str::raw::from_utf8_owned(v.move_iter().collect())
} }
} }
} }
@ -106,7 +105,7 @@ impl<'a> FromHex for &'a str {
*/ */
fn from_hex(&self) -> Result<~[u8], FromHexError> { fn from_hex(&self) -> Result<~[u8], FromHexError> {
// This may be an overestimate if there is any whitespace // This may be an overestimate if there is any whitespace
let mut b = slice::with_capacity(self.len() / 2); let mut b = Vec::with_capacity(self.len() / 2);
let mut modulus = 0; let mut modulus = 0;
let mut buf = 0u8; let mut buf = 0u8;
@ -132,7 +131,7 @@ impl<'a> FromHex for &'a str {
} }
match modulus { match modulus {
0 => Ok(b), 0 => Ok(b.move_iter().collect()),
_ => Err(InvalidHexLength), _ => Err(InvalidHexLength),
} }
} }

View File

@ -1230,11 +1230,11 @@ impl<T : Iterator<char>> Parser<T> {
self.bump(); self.bump();
self.parse_whitespace(); self.parse_whitespace();
let mut values = ~[]; let mut values = Vec::new();
if self.ch_is(']') { if self.ch_is(']') {
self.bump(); self.bump();
return Ok(List(values)); return Ok(List(values.move_iter().collect()));
} }
loop { loop {
@ -1252,7 +1252,7 @@ impl<T : Iterator<char>> Parser<T> {
self.bump(); self.bump();
} else if self.ch_is(']') { } else if self.ch_is(']') {
self.bump(); self.bump();
return Ok(List(values)); return Ok(List(values.move_iter().collect()));
} else { } else {
return self.error(~"expected `,` or `]`") return self.error(~"expected `,` or `]`")
} }
@ -1332,14 +1332,14 @@ pub fn from_str(s: &str) -> DecodeResult<Json> {
/// A structure to decode JSON to values in rust. /// A structure to decode JSON to values in rust.
pub struct Decoder { pub struct Decoder {
stack: ~[Json], stack: Vec<Json>,
} }
impl Decoder { impl Decoder {
/// Creates a new decoder instance for decoding the specified JSON value. /// Creates a new decoder instance for decoding the specified JSON value.
pub fn new(json: Json) -> Decoder { pub fn new(json: Json) -> Decoder {
Decoder { Decoder {
stack: ~[json] stack: vec!(json),
} }
} }
} }

View File

@ -16,7 +16,6 @@ Core encoding and decoding interfaces.
use std::path; use std::path;
use std::rc::Rc; use std::rc::Rc;
use std::slice;
pub trait Encoder<E> { pub trait Encoder<E> {
// Primitive types: // Primitive types:
@ -443,11 +442,15 @@ impl<E, S:Encoder<E>,T:Encodable<S, E>> Encodable<S, E> for ~[T] {
impl<E, D:Decoder<E>,T:Decodable<D, E>> Decodable<D, E> for ~[T] { impl<E, D:Decoder<E>,T:Decodable<D, E>> Decodable<D, E> for ~[T] {
fn decode(d: &mut D) -> Result<~[T], E> { fn decode(d: &mut D) -> Result<~[T], E> {
d.read_seq(|d, len| { d.read_seq(|d, len| {
let mut v: ~[T] = slice::with_capacity(len); let mut v: Vec<T> = Vec::with_capacity(len);
for i in range(0, len) { for i in range(0, len) {
v.push(try!(d.read_seq_elt(i, |d| Decodable::decode(d)))); v.push(try!(d.read_seq_elt(i, |d| Decodable::decode(d))));
} }
Ok(v) println!("-------");
println!("{}", v.len());
let k = v.move_iter().collect::<~[T]>();
println!("{}", k.len());
Ok(k)
}) })
} }
} }
@ -594,11 +597,11 @@ pub trait DecoderHelpers<E> {
impl<E, D:Decoder<E>> DecoderHelpers<E> for D { 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<~[T], E> {
self.read_seq(|this, len| { self.read_seq(|this, len| {
let mut v = slice::with_capacity(len); let mut v = Vec::with_capacity(len);
for i in range(0, len) { for i in range(0, len) {
v.push(try!(this.read_seq_elt(i, |this| f(this)))); v.push(try!(this.read_seq_elt(i, |this| f(this))));
} }
Ok(v) Ok(v.move_iter().collect())
}) })
} }
} }

View File

@ -30,7 +30,6 @@ use rt::task::{Task, BlockedTask};
use rt::thread::Thread; use rt::thread::Thread;
use sync::atomics; use sync::atomics;
use unstable::mutex::NativeMutex; use unstable::mutex::NativeMutex;
use slice::OwnedVector;
use mpsc = sync::mpsc_queue; use mpsc = sync::mpsc_queue;

View File

@ -30,7 +30,6 @@ use rt::task::{Task, BlockedTask};
use rt::thread::Thread; use rt::thread::Thread;
use spsc = sync::spsc_queue; use spsc = sync::spsc_queue;
use sync::atomics; use sync::atomics;
use slice::OwnedVector;
static DISCONNECTED: int = int::MIN; static DISCONNECTED: int = int::MIN;
#[cfg(test)] #[cfg(test)]

View File

@ -359,13 +359,8 @@ pub fn hash_with_keys<T: Hash<SipState>>(k0: u64, k1: u64, value: &T) -> u64 {
#[cfg(test)] #[cfg(test)]
mod tests { mod tests {
extern crate test; extern crate test;
use io::Writer; use prelude::*;
use iter::Iterator;
use num::ToStrRadix; use num::ToStrRadix;
use option::{Some, None};
use str::Str;
use strbuf::StrBuf;
use slice::{Vector, ImmutableVector, OwnedVector};
use self::test::Bencher; use self::test::Bencher;
use super::super::Hash; use super::super::Hash;
@ -454,7 +449,7 @@ mod tests {
let k0 = 0x_07_06_05_04_03_02_01_00_u64; let k0 = 0x_07_06_05_04_03_02_01_00_u64;
let k1 = 0x_0f_0e_0d_0c_0b_0a_09_08_u64; let k1 = 0x_0f_0e_0d_0c_0b_0a_09_08_u64;
let mut buf : ~[u8] = ~[]; let mut buf = Vec::new();
let mut t = 0; let mut t = 0;
let mut state_inc = SipState::new_with_keys(k0, k1); let mut state_inc = SipState::new_with_keys(k0, k1);
let mut state_full = SipState::new_with_keys(k0, k1); let mut state_full = SipState::new_with_keys(k0, k1);
@ -496,7 +491,7 @@ mod tests {
assert_eq!(vec, out); assert_eq!(vec, out);
state_full.reset(); state_full.reset();
state_full.write(buf); state_full.write(buf.as_slice());
let f = result_str(state_full.result()); let f = result_str(state_full.result());
let i = result_str(state_inc.result()); let i = result_str(state_inc.result());
let v = to_hex_str(&vecs[t]); let v = to_hex_str(&vecs[t]);

View File

@ -17,7 +17,7 @@ use iter::ExactSize;
use ops::Drop; use ops::Drop;
use option::{Some, None, Option}; use option::{Some, None, Option};
use result::{Ok, Err}; use result::{Ok, Err};
use slice::{OwnedVector, ImmutableVector, MutableVector}; use slice::{ImmutableVector, MutableVector};
use slice; use slice;
use vec::Vec; use vec::Vec;
@ -391,7 +391,7 @@ mod test {
/// A dummy reader intended at testing short-reads propagation. /// A dummy reader intended at testing short-reads propagation.
pub struct ShortReader { pub struct ShortReader {
lengths: ~[uint], lengths: Vec<uint>,
} }
impl Reader for ShortReader { impl Reader for ShortReader {
@ -554,7 +554,7 @@ mod test {
#[test] #[test]
fn test_short_reads() { fn test_short_reads() {
let inner = ShortReader{lengths: ~[0, 1, 2, 0, 1, 0]}; let inner = ShortReader{lengths: vec![0, 1, 2, 0, 1, 0]};
let mut reader = BufferedReader::new(inner); let mut reader = BufferedReader::new(inner);
let mut buf = [0, 0]; let mut buf = [0, 0];
assert_eq!(reader.read(buf), Ok(0)); assert_eq!(reader.read(buf), Ok(0));

View File

@ -21,7 +21,7 @@ use option::{Option, Some, None};
use result::{Ok, Err}; use result::{Ok, Err};
use io; use io;
use io::{IoError, IoResult, Reader}; use io::{IoError, IoResult, Reader};
use slice::{OwnedVector, ImmutableVector, Vector}; use slice::{ImmutableVector, Vector};
use ptr::RawPtr; use ptr::RawPtr;
/// An iterator that reads a single byte on each iteration, /// An iterator that reads a single byte on each iteration,
@ -503,21 +503,22 @@ mod test {
#[cfg(test)] #[cfg(test)]
mod bench { mod bench {
extern crate test; extern crate test;
use self::test::Bencher;
use container::Container; use container::Container;
use prelude::*;
use self::test::Bencher;
macro_rules! u64_from_be_bytes_bench_impl( macro_rules! u64_from_be_bytes_bench_impl(
($size:expr, $stride:expr, $start_index:expr) => ($size:expr, $stride:expr, $start_index:expr) =>
({ ({
use slice;
use super::u64_from_be_bytes; use super::u64_from_be_bytes;
let data = slice::from_fn($stride*100+$start_index, |i| i as u8); let data = Vec::from_fn($stride*100+$start_index, |i| i as u8);
let mut sum = 0u64; let mut sum = 0u64;
b.iter(|| { b.iter(|| {
let mut i = $start_index; let mut i = $start_index;
while i < data.len() { while i < data.len() {
sum += u64_from_be_bytes(data, i, $size); sum += u64_from_be_bytes(data.as_slice(), i, $size);
i += $stride; i += $stride;
} }
}); });

View File

@ -17,7 +17,7 @@ use result::{Err, Ok};
use io; use io;
use io::{Reader, Writer, Seek, Buffer, IoError, SeekStyle, IoResult}; use io::{Reader, Writer, Seek, Buffer, IoError, SeekStyle, IoResult};
use slice; use slice;
use slice::{Vector, ImmutableVector, MutableVector, OwnedCloneableVector}; use slice::{Vector, ImmutableVector, MutableVector};
use vec::Vec; use vec::Vec;
fn combine(seek: SeekStyle, cur: uint, end: uint, offset: i64) -> IoResult<u64> { fn combine(seek: SeekStyle, cur: uint, end: uint, offset: i64) -> IoResult<u64> {

View File

@ -228,11 +228,11 @@ use os;
use option::{Option, Some, None}; use option::{Option, Some, None};
use path::Path; use path::Path;
use result::{Ok, Err, Result}; use result::{Ok, Err, Result};
use str::{StrSlice, OwnedStr}; use str::StrSlice;
use str; use str;
use uint; use uint;
use unstable::finally::try_finally; use unstable::finally::try_finally;
use slice::{Vector, OwnedVector, MutableVector, ImmutableVector, OwnedCloneableVector}; use slice::{Vector, MutableVector, ImmutableVector};
use vec::Vec; use vec::Vec;
// Reexports // Reexports

View File

@ -16,6 +16,7 @@ use fmt;
use io::IoResult; use io::IoResult;
use io; use io;
use libc; use libc;
use mem;
use rt::rtio::{RtioProcess, IoFactory, LocalIo}; use rt::rtio::{RtioProcess, IoFactory, LocalIo};
/// Signal a process to exit, without forcibly killing it. Corresponds to /// Signal a process to exit, without forcibly killing it. Corresponds to
@ -416,12 +417,7 @@ impl Drop for Process {
drop(self.stdin.take()); drop(self.stdin.take());
drop(self.stdout.take()); drop(self.stdout.take());
drop(self.stderr.take()); drop(self.stderr.take());
loop { drop(mem::replace(&mut self.extra_io, ~[]));
match self.extra_io.pop() {
Some(_) => (),
None => break,
}
}
self.wait(); self.wait();
} }

View File

@ -28,7 +28,7 @@ use mem::drop;
use option::{Some, None}; use option::{Some, None};
use result::{Ok, Err}; use result::{Ok, Err};
use rt::rtio::{IoFactory, LocalIo, RtioSignal}; use rt::rtio::{IoFactory, LocalIo, RtioSignal};
use slice::{ImmutableVector, OwnedVector}; use slice::ImmutableVector;
use vec::Vec; use vec::Vec;
/// Signals that can be sent and received /// Signals that can be sent and received

View File

@ -46,7 +46,7 @@ use kinds::Send;
use mem::replace; use mem::replace;
use option::{None, Option, Some}; use option::{None, Option, Some};
use rt::task::{Task, LocalStorage}; use rt::task::{Task, LocalStorage};
use slice::{ImmutableVector, MutableVector, OwnedVector}; use slice::{ImmutableVector, MutableVector};
use vec::Vec; use vec::Vec;
/** /**

View File

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

View File

@ -1779,12 +1779,11 @@ mod bench {
extern crate test; extern crate test;
use self::test::Bencher; use self::test::Bencher;
use num; use num;
use slice;
use prelude::*; use prelude::*;
#[bench] #[bench]
fn bench_pow_function(b: &mut Bencher) { fn bench_pow_function(b: &mut Bencher) {
let v = slice::from_fn(1024, |n| n); let v = Vec::from_fn(1024, |n| n);
b.iter(|| {v.iter().fold(0, |old, new| num::pow(old, *new));}); b.iter(|| {v.iter().fold(0, |old, new| num::pow(old, *new));});
} }
} }

View File

@ -10,19 +10,21 @@
#![allow(missing_doc)] #![allow(missing_doc)]
use char;
use clone::Clone; use clone::Clone;
use container::Container; use container::Container;
use std::cmp::{Ord, Eq}; use iter::Iterator;
use ops::{Add, Sub, Mul, Div, Rem, Neg};
use option::{None, Option, Some};
use char;
use str::{StrSlice};
use str;
use slice::{CloneableVector, ImmutableVector, MutableVector};
use slice::OwnedVector;
use num;
use num::{NumCast, Zero, One, cast, Int}; use num::{NumCast, Zero, One, cast, Int};
use num::{Round, Float, FPNaN, FPInfinite, ToPrimitive}; use num::{Round, Float, FPNaN, FPInfinite, ToPrimitive};
use num;
use ops::{Add, Sub, Mul, Div, Rem, Neg};
use option::{None, Option, Some};
use slice::OwnedVector;
use slice::{CloneableVector, ImmutableVector, MutableVector};
use std::cmp::{Ord, Eq};
use str::{StrSlice};
use str;
use vec::Vec;
/// A flag that specifies whether to use exponential (scientific) notation. /// A flag that specifies whether to use exponential (scientific) notation.
pub enum ExponentFormat { pub enum ExponentFormat {
@ -293,7 +295,7 @@ pub fn float_to_str_bytes_common<T:NumCast+Zero+One+Eq+Ord+Float+Round+
} }
let neg = num < _0 || (negative_zero && _1 / num == Float::neg_infinity()); let neg = num < _0 || (negative_zero && _1 / num == Float::neg_infinity());
let mut buf: ~[u8] = ~[]; let mut buf = Vec::new();
let radix_gen: T = cast(radix as int).unwrap(); let radix_gen: T = cast(radix as int).unwrap();
let (num, exp) = match exp_format { let (num, exp) = match exp_format {
@ -411,23 +413,23 @@ pub fn float_to_str_bytes_common<T:NumCast+Zero+One+Eq+Ord+Float+Round+
// If reached left end of number, have to // If reached left end of number, have to
// insert additional digit: // insert additional digit:
if i < 0 if i < 0
|| buf[i as uint] == '-' as u8 || *buf.get(i as uint) == '-' as u8
|| buf[i as uint] == '+' as u8 { || *buf.get(i as uint) == '+' as u8 {
buf.insert((i + 1) as uint, value2ascii(1)); buf.insert((i + 1) as uint, value2ascii(1));
break; break;
} }
// Skip the '.' // Skip the '.'
if buf[i as uint] == '.' as u8 { i -= 1; continue; } if *buf.get(i as uint) == '.' as u8 { i -= 1; continue; }
// Either increment the digit, // Either increment the digit,
// or set to 0 if max and carry the 1. // or set to 0 if max and carry the 1.
let current_digit = ascii2value(buf[i as uint]); let current_digit = ascii2value(*buf.get(i as uint));
if current_digit < (radix - 1) { if current_digit < (radix - 1) {
buf[i as uint] = value2ascii(current_digit+1); *buf.get_mut(i as uint) = value2ascii(current_digit+1);
break; break;
} else { } else {
buf[i as uint] = value2ascii(0); *buf.get_mut(i as uint) = value2ascii(0);
i -= 1; i -= 1;
} }
} }
@ -444,25 +446,25 @@ pub fn float_to_str_bytes_common<T:NumCast+Zero+One+Eq+Ord+Float+Round+
let mut i = buf_max_i; let mut i = buf_max_i;
// discover trailing zeros of fractional part // discover trailing zeros of fractional part
while i > start_fractional_digits && buf[i] == '0' as u8 { while i > start_fractional_digits && *buf.get(i) == '0' as u8 {
i -= 1; i -= 1;
} }
// Only attempt to truncate digits if buf has fractional digits // Only attempt to truncate digits if buf has fractional digits
if i >= start_fractional_digits { if i >= start_fractional_digits {
// If buf ends with '.', cut that too. // If buf ends with '.', cut that too.
if buf[i] == '.' as u8 { i -= 1 } if *buf.get(i) == '.' as u8 { i -= 1 }
// only resize buf if we actually remove digits // only resize buf if we actually remove digits
if i < buf_max_i { if i < buf_max_i {
buf = buf.slice(0, i + 1).to_owned(); buf = Vec::from_slice(buf.slice(0, i + 1));
} }
} }
} // If exact and trailing '.', just cut that } // If exact and trailing '.', just cut that
else { else {
let max_i = buf.len() - 1; let max_i = buf.len() - 1;
if buf[max_i] == '.' as u8 { if *buf.get(max_i) == '.' as u8 {
buf = buf.slice(0, max_i).to_owned(); buf = Vec::from_slice(buf.slice(0, max_i));
} }
} }
@ -481,7 +483,7 @@ pub fn float_to_str_bytes_common<T:NumCast+Zero+One+Eq+Ord+Float+Round+
} }
} }
(buf, false) (buf.move_iter().collect(), false)
} }
/** /**

View File

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

View File

@ -28,10 +28,6 @@
#![allow(missing_doc)] #![allow(missing_doc)]
#[cfg(target_os = "macos")]
#[cfg(windows)]
use iter::range;
use clone::Clone; use clone::Clone;
use container::Container; use container::Container;
use libc; use libc;
@ -49,6 +45,7 @@ use path::{Path, GenericPath};
use iter::Iterator; use iter::Iterator;
use slice::{Vector, CloneableVector, ImmutableVector, MutableVector, OwnedVector}; use slice::{Vector, CloneableVector, ImmutableVector, MutableVector, OwnedVector};
use ptr::RawPtr; use ptr::RawPtr;
use vec::Vec;
#[cfg(unix)] #[cfg(unix)]
use c_str::ToCStr; use c_str::ToCStr;
@ -96,15 +93,16 @@ pub fn getcwd() -> Path {
#[cfg(windows)] #[cfg(windows)]
pub mod win32 { pub mod win32 {
use iter::Iterator;
use libc::types::os::arch::extra::DWORD; use libc::types::os::arch::extra::DWORD;
use libc; use libc;
use option::{None, Option}; use option::{None, Option};
use option; use option;
use os::TMPBUF_SZ; use os::TMPBUF_SZ;
use slice::{MutableVector, ImmutableVector, OwnedVector};
use str::StrSlice; use str::StrSlice;
use str; use str;
use slice::{MutableVector, ImmutableVector, OwnedVector}; use vec::Vec;
use slice;
pub fn fill_utf16_buf_and_decode(f: |*mut u16, DWORD| -> DWORD) pub fn fill_utf16_buf_and_decode(f: |*mut u16, DWORD| -> DWORD)
-> Option<~str> { -> Option<~str> {
@ -114,7 +112,7 @@ pub mod win32 {
let mut res = None; let mut res = None;
let mut done = false; let mut done = false;
while !done { while !done {
let mut buf = slice::from_elem(n as uint, 0u16); let mut buf = Vec::from_elem(n as uint, 0u16);
let k = f(buf.as_mut_ptr(), n); let k = f(buf.as_mut_ptr(), n);
if k == (0 as DWORD) { if k == (0 as DWORD) {
done = true; done = true;
@ -142,7 +140,7 @@ pub mod win32 {
} }
pub fn as_utf16_p<T>(s: &str, f: |*u16| -> T) -> T { pub fn as_utf16_p<T>(s: &str, f: |*u16| -> T) -> T {
let mut t = s.to_utf16(); let mut t = s.to_utf16().move_iter().collect::<Vec<u16>>();
// Null terminate before passing on. // Null terminate before passing on.
t.push(0u16); t.push(0u16);
f(t.as_ptr()) f(t.as_ptr())
@ -182,7 +180,7 @@ pub fn env() -> ~[(~str,~str)] {
pub fn env_as_bytes() -> ~[(~[u8],~[u8])] { pub fn env_as_bytes() -> ~[(~[u8],~[u8])] {
unsafe { unsafe {
#[cfg(windows)] #[cfg(windows)]
unsafe fn get_env_pairs() -> ~[~[u8]] { unsafe fn get_env_pairs() -> Vec<~[u8]> {
use c_str; use c_str;
use str::StrSlice; use str::StrSlice;
@ -195,7 +193,7 @@ pub fn env_as_bytes() -> ~[(~[u8],~[u8])] {
fail!("os::env() failure getting env string from OS: {}", fail!("os::env() failure getting env string from OS: {}",
os::last_os_error()); os::last_os_error());
} }
let mut result = ~[]; let mut result = Vec::new();
c_str::from_c_multistring(ch as *c_char, None, |cstr| { c_str::from_c_multistring(ch as *c_char, None, |cstr| {
result.push(cstr.as_bytes_no_nul().to_owned()); result.push(cstr.as_bytes_no_nul().to_owned());
}); });
@ -203,7 +201,7 @@ pub fn env_as_bytes() -> ~[(~[u8],~[u8])] {
result result
} }
#[cfg(unix)] #[cfg(unix)]
unsafe fn get_env_pairs() -> ~[~[u8]] { unsafe fn get_env_pairs() -> Vec<~[u8]> {
use c_str::CString; use c_str::CString;
extern { extern {
@ -214,7 +212,7 @@ pub fn env_as_bytes() -> ~[(~[u8],~[u8])] {
fail!("os::env() failure getting env string from OS: {}", fail!("os::env() failure getting env string from OS: {}",
os::last_os_error()); os::last_os_error());
} }
let mut result = ~[]; let mut result = Vec::new();
ptr::array_each(environ, |e| { ptr::array_each(environ, |e| {
let env_pair = CString::new(e, false).as_bytes_no_nul().to_owned(); let env_pair = CString::new(e, false).as_bytes_no_nul().to_owned();
result.push(env_pair); result.push(env_pair);
@ -222,8 +220,8 @@ pub fn env_as_bytes() -> ~[(~[u8],~[u8])] {
result result
} }
fn env_convert(input: ~[~[u8]]) -> ~[(~[u8], ~[u8])] { fn env_convert(input: Vec<~[u8]>) -> Vec<(~[u8], ~[u8])> {
let mut pairs = ~[]; let mut pairs = Vec::new();
for p in input.iter() { for p in input.iter() {
let vs: ~[&[u8]] = p.splitn(1, |b| *b == '=' as u8).collect(); let vs: ~[&[u8]] = p.splitn(1, |b| *b == '=' as u8).collect();
let key = vs[0].to_owned(); let key = vs[0].to_owned();
@ -234,7 +232,7 @@ pub fn env_as_bytes() -> ~[(~[u8],~[u8])] {
} }
with_env_lock(|| { with_env_lock(|| {
let unparsed_environ = get_env_pairs(); let unparsed_environ = get_env_pairs();
env_convert(unparsed_environ) env_convert(unparsed_environ).move_iter().collect()
}) })
} }
} }
@ -457,15 +455,14 @@ pub fn self_exe_name() -> Option<Path> {
fn load_self() -> Option<~[u8]> { fn load_self() -> Option<~[u8]> {
unsafe { unsafe {
use libc::funcs::extra::_NSGetExecutablePath; use libc::funcs::extra::_NSGetExecutablePath;
use slice;
let mut sz: u32 = 0; let mut sz: u32 = 0;
_NSGetExecutablePath(ptr::mut_null(), &mut sz); _NSGetExecutablePath(ptr::mut_null(), &mut sz);
if sz == 0 { return None; } if sz == 0 { return None; }
let mut v: ~[u8] = slice::with_capacity(sz as uint); let mut v: Vec<u8> = Vec::with_capacity(sz as uint);
let err = _NSGetExecutablePath(v.as_mut_ptr() as *mut i8, &mut sz); let err = _NSGetExecutablePath(v.as_mut_ptr() as *mut i8, &mut sz);
if err != 0 { return None; } if err != 0 { return None; }
v.set_len(sz as uint - 1); // chop off trailing NUL v.set_len(sz as uint - 1); // chop off trailing NUL
Some(v) Some(v.move_iter().collect())
} }
} }
@ -795,11 +792,9 @@ pub fn get_exit_status() -> int {
unsafe fn load_argc_and_argv(argc: int, argv: **c_char) -> ~[~[u8]] { unsafe fn load_argc_and_argv(argc: int, argv: **c_char) -> ~[~[u8]] {
use c_str::CString; use c_str::CString;
let mut args = ~[]; Vec::from_fn(argc as uint, |i| {
for i in range(0u, argc as uint) { CString::new(*argv.offset(i as int), false).as_bytes_no_nul().to_owned()
args.push(CString::new(*argv.offset(i as int), false).as_bytes_no_nul().to_owned()) }).move_iter().collect()
}
args
} }
/** /**
@ -842,27 +837,24 @@ fn real_args() -> ~[~str] {
let lpCmdLine = unsafe { GetCommandLineW() }; let lpCmdLine = unsafe { GetCommandLineW() };
let szArgList = unsafe { CommandLineToArgvW(lpCmdLine, lpArgCount) }; let szArgList = unsafe { CommandLineToArgvW(lpCmdLine, lpArgCount) };
let mut args = ~[]; let args = Vec::from_fn(nArgs as uint, |i| unsafe {
for i in range(0u, nArgs as uint) { // Determine the length of this argument.
unsafe { let ptr = *szArgList.offset(i as int);
// Determine the length of this argument. let mut len = 0;
let ptr = *szArgList.offset(i as int); while *ptr.offset(len as int) != 0 { len += 1; }
let mut len = 0;
while *ptr.offset(len as int) != 0 { len += 1; }
// Push it onto the list. // Push it onto the list.
let opt_s = slice::raw::buf_as_slice(ptr, len, |buf| { let opt_s = slice::raw::buf_as_slice(ptr, len, |buf| {
str::from_utf16(str::truncate_utf16_at_nul(buf)) str::from_utf16(str::truncate_utf16_at_nul(buf))
}); });
args.push(opt_s.expect("CommandLineToArgvW returned invalid UTF-16")); opt_s.expect("CommandLineToArgvW returned invalid UTF-16")
} });
}
unsafe { unsafe {
LocalFree(szArgList as *c_void); LocalFree(szArgList as *c_void);
} }
return args; return args.move_iter().collect();
} }
#[cfg(windows)] #[cfg(windows)]

View File

@ -74,7 +74,7 @@ use option::{Option, None, Some};
use str; use str;
use str::{MaybeOwned, Str, StrSlice, from_utf8_lossy}; use str::{MaybeOwned, Str, StrSlice, from_utf8_lossy};
use strbuf::StrBuf; use strbuf::StrBuf;
use slice::{OwnedCloneableVector, OwnedVector, Vector}; use slice::Vector;
use slice::{ImmutableEqVector, ImmutableVector}; use slice::{ImmutableEqVector, ImmutableVector};
use vec::Vec; use vec::Vec;

View File

@ -21,7 +21,7 @@ use option::{Option, None, Some};
use str; use str;
use str::Str; use str::Str;
use slice::{CloneableVector, RevSplits, Splits, Vector, VectorVector, use slice::{CloneableVector, RevSplits, Splits, Vector, VectorVector,
ImmutableEqVector, OwnedVector, ImmutableVector, OwnedCloneableVector}; ImmutableEqVector, OwnedVector, ImmutableVector};
use vec::Vec; use vec::Vec;
use super::{BytesContainer, GenericPath, GenericPathUnsafe}; use super::{BytesContainer, GenericPath, GenericPathUnsafe};

View File

@ -21,7 +21,7 @@ use io::Writer;
use iter::{AdditiveIterator, DoubleEndedIterator, Extendable, Rev, Iterator, Map}; use iter::{AdditiveIterator, DoubleEndedIterator, Extendable, Rev, Iterator, Map};
use option::{Option, Some, None}; use option::{Option, Some, None};
use slice::{Vector, OwnedVector, ImmutableVector}; use slice::{Vector, OwnedVector, ImmutableVector};
use str::{CharSplits, OwnedStr, Str, StrVector, StrSlice}; use str::{CharSplits, Str, StrVector, StrSlice};
use strbuf::StrBuf; use strbuf::StrBuf;
use vec::Vec; use vec::Vec;

View File

@ -56,7 +56,7 @@ pub use tuple::{Tuple1, Tuple2, Tuple3, Tuple4};
pub use tuple::{Tuple5, Tuple6, Tuple7, Tuple8}; pub use tuple::{Tuple5, Tuple6, Tuple7, Tuple8};
pub use tuple::{Tuple9, Tuple10, Tuple11, Tuple12}; pub use tuple::{Tuple9, Tuple10, Tuple11, Tuple12};
pub use slice::{ImmutableEqVector, ImmutableTotalOrdVector, ImmutableCloneableVector}; pub use slice::{ImmutableEqVector, ImmutableTotalOrdVector, ImmutableCloneableVector};
pub use slice::{OwnedVector, OwnedCloneableVector, OwnedEqVector}; pub use slice::{OwnedVector};
pub use slice::{MutableVector, MutableTotalOrdVector}; pub use slice::{MutableVector, MutableTotalOrdVector};
pub use slice::{Vector, VectorVector, CloneableVector, ImmutableVector}; pub use slice::{Vector, VectorVector, CloneableVector, ImmutableVector};
pub use strbuf::StrBuf; pub use strbuf::StrBuf;

View File

@ -170,10 +170,9 @@ pub fn mut_null<T>() -> *mut T { 0 as *mut T }
/// ///
/// ``` /// ```
/// use std::ptr; /// use std::ptr;
/// use std::slice;
/// ///
/// unsafe fn from_buf_raw<T>(ptr: *T, elts: uint) -> ~[T] { /// unsafe fn from_buf_raw<T>(ptr: *T, elts: uint) -> Vec<T> {
/// let mut dst = slice::with_capacity(elts); /// let mut dst = Vec::with_capacity(elts);
/// dst.set_len(elts); /// dst.set_len(elts);
/// ptr::copy_memory(dst.as_mut_ptr(), ptr, elts); /// ptr::copy_memory(dst.as_mut_ptr(), ptr, elts);
/// dst /// dst

View File

@ -28,7 +28,7 @@ use reflect::{MovePtr, align};
use result::{Ok, Err}; use result::{Ok, Err};
use str::StrSlice; use str::StrSlice;
use to_str::ToStr; use to_str::ToStr;
use slice::{Vector, OwnedVector}; use slice::Vector;
use intrinsics::{Disr, Opaque, TyDesc, TyVisitor, get_tydesc, visit_tydesc}; use intrinsics::{Disr, Opaque, TyDesc, TyVisitor, get_tydesc, visit_tydesc};
use raw; use raw;
use vec::Vec; use vec::Vec;

View File

@ -125,13 +125,14 @@ mod imp {
unsafe fn load_argc_and_argv(argc: int, argv: **u8) -> ~[~[u8]] { unsafe fn load_argc_and_argv(argc: int, argv: **u8) -> ~[~[u8]] {
use c_str::CString; use c_str::CString;
use ptr::RawPtr; use ptr::RawPtr;
use {slice, libc}; use libc;
use slice::CloneableVector; use slice::CloneableVector;
use vec::Vec;
slice::from_fn(argc as uint, |i| { Vec::from_fn(argc as uint, |i| {
let cs = CString::new(*(argv as **libc::c_char).offset(i as int), false); let cs = CString::new(*(argv as **libc::c_char).offset(i as int), false);
cs.as_bytes_no_nul().to_owned() cs.as_bytes_no_nul().to_owned()
}) }).move_iter().collect()
} }
#[cfg(test)] #[cfg(test)]

File diff suppressed because it is too large Load Diff

View File

@ -80,7 +80,7 @@ use char;
use char::Char; use char::Char;
use clone::Clone; use clone::Clone;
use cmp::{Eq, TotalEq, Ord, TotalOrd, Equiv, Ordering}; use cmp::{Eq, TotalEq, Ord, TotalOrd, Equiv, Ordering};
use container::{Container, Mutable}; use container::Container;
use fmt; use fmt;
use io::Writer; use io::Writer;
use iter::{Iterator, FromIterator, Extendable, range}; use iter::{Iterator, FromIterator, Extendable, range};
@ -92,7 +92,7 @@ use option::{None, Option, Some};
use ptr; use ptr;
use from_str::FromStr; use from_str::FromStr;
use slice; use slice;
use slice::{OwnedVector, OwnedCloneableVector, ImmutableVector, MutableVector}; use slice::{OwnedVector, ImmutableVector, MutableVector};
use slice::{Vector}; use slice::{Vector};
use vec::Vec; use vec::Vec;
use default::Default; use default::Default;
@ -588,7 +588,7 @@ enum NormalizationForm {
pub struct Normalizations<'a> { pub struct Normalizations<'a> {
kind: NormalizationForm, kind: NormalizationForm,
iter: Chars<'a>, iter: Chars<'a>,
buffer: ~[(char, u8)], buffer: Vec<(char, u8)>,
sorted: bool sorted: bool
} }
@ -597,7 +597,7 @@ impl<'a> Iterator<char> for Normalizations<'a> {
fn next(&mut self) -> Option<char> { fn next(&mut self) -> Option<char> {
use unicode::decompose::canonical_combining_class; use unicode::decompose::canonical_combining_class;
match self.buffer.head() { match self.buffer.as_slice().head() {
Some(&(c, 0)) => { Some(&(c, 0)) => {
self.sorted = false; self.sorted = false;
self.buffer.shift(); self.buffer.shift();
@ -622,7 +622,7 @@ impl<'a> Iterator<char> for Normalizations<'a> {
decomposer(ch, |d| { decomposer(ch, |d| {
let class = canonical_combining_class(d); let class = canonical_combining_class(d);
if class == 0 && !*sorted { if class == 0 && !*sorted {
canonical_sort(*buffer); canonical_sort(buffer.as_mut_slice());
*sorted = true; *sorted = true;
} }
buffer.push((d, class)); buffer.push((d, class));
@ -632,7 +632,7 @@ impl<'a> Iterator<char> for Normalizations<'a> {
} }
if !self.sorted { if !self.sorted {
canonical_sort(self.buffer); canonical_sort(self.buffer.as_mut_slice());
self.sorted = true; self.sorted = true;
} }
@ -1336,22 +1336,23 @@ impl<'a> fmt::Show for MaybeOwned<'a> {
pub mod raw { pub mod raw {
use cast; use cast;
use container::Container; use container::Container;
use iter::Iterator;
use libc; use libc;
use ptr;
use ptr::RawPtr; use ptr::RawPtr;
use str::{is_utf8, OwnedStr, StrSlice}; use ptr;
use slice;
use slice::{MutableVector, ImmutableVector, OwnedVector};
use raw::Slice; use raw::Slice;
use slice::{MutableVector, ImmutableVector, OwnedVector, Vector};
use str::{is_utf8, StrSlice};
use vec::Vec;
/// Create a Rust string from a *u8 buffer of the given length /// Create a Rust string from a *u8 buffer of the given length
pub unsafe fn from_buf_len(buf: *u8, len: uint) -> ~str { pub unsafe fn from_buf_len(buf: *u8, len: uint) -> ~str {
let mut v: ~[u8] = slice::with_capacity(len); let mut v = Vec::with_capacity(len);
ptr::copy_memory(v.as_mut_ptr(), buf, len); ptr::copy_memory(v.as_mut_ptr(), buf, len);
v.set_len(len); v.set_len(len);
assert!(is_utf8(v)); assert!(is_utf8(v.as_slice()));
::cast::transmute(v) ::cast::transmute(v.move_iter().collect::<~[u8]>())
} }
#[lang="strdup_uniq"] #[lang="strdup_uniq"]
@ -1594,16 +1595,6 @@ impl Container for ~str {
fn len(&self) -> uint { self.as_slice().len() } fn len(&self) -> uint { self.as_slice().len() }
} }
impl Mutable for ~str {
/// Remove all content, make the string empty
#[inline]
fn clear(&mut self) {
unsafe {
self.set_len(0)
}
}
}
/// Methods for string slices /// Methods for string slices
pub trait StrSlice<'a> { pub trait StrSlice<'a> {
/// Returns true if one string contains another /// Returns true if one string contains another
@ -2396,7 +2387,7 @@ impl<'a> StrSlice<'a> for &'a str {
fn nfd_chars(&self) -> Normalizations<'a> { fn nfd_chars(&self) -> Normalizations<'a> {
Normalizations { Normalizations {
iter: self.chars(), iter: self.chars(),
buffer: ~[], buffer: Vec::new(),
sorted: false, sorted: false,
kind: NFD kind: NFD
} }
@ -2406,7 +2397,7 @@ impl<'a> StrSlice<'a> for &'a str {
fn nfkd_chars(&self) -> Normalizations<'a> { fn nfkd_chars(&self) -> Normalizations<'a> {
Normalizations { Normalizations {
iter: self.chars(), iter: self.chars(),
buffer: ~[], buffer: Vec::new(),
sorted: false, sorted: false,
kind: NFKD kind: NFKD
} }
@ -2544,22 +2535,22 @@ impl<'a> StrSlice<'a> for &'a str {
fn to_owned(&self) -> ~str { fn to_owned(&self) -> ~str {
let len = self.len(); let len = self.len();
unsafe { unsafe {
let mut v = slice::with_capacity(len); let mut v = Vec::with_capacity(len);
ptr::copy_memory(v.as_mut_ptr(), self.as_ptr(), len); ptr::copy_memory(v.as_mut_ptr(), self.as_ptr(), len);
v.set_len(len); v.set_len(len);
::cast::transmute(v) ::cast::transmute(v.move_iter().collect::<~[u8]>())
} }
} }
fn to_utf16(&self) -> ~[u16] { fn to_utf16(&self) -> ~[u16] {
let mut u = ~[]; let mut u = Vec::new();;
for ch in self.chars() { for ch in self.chars() {
let mut buf = [0u16, ..2]; let mut buf = [0u16, ..2];
let n = ch.encode_utf16(buf /* as mut slice! */); let n = ch.encode_utf16(buf /* as mut slice! */);
u.push_all(buf.slice_to(n)); u.push_all(buf.slice_to(n));
} }
u u.move_iter().collect()
} }
#[inline] #[inline]
@ -2694,29 +2685,30 @@ impl<'a> StrSlice<'a> for &'a str {
if slen == 0 { return tlen; } if slen == 0 { return tlen; }
if tlen == 0 { return slen; } if tlen == 0 { return slen; }
let mut dcol = slice::from_fn(tlen + 1, |x| x); let mut dcol = Vec::from_fn(tlen + 1, |x| x);
for (i, sc) in self.chars().enumerate() { for (i, sc) in self.chars().enumerate() {
let mut current = i; let mut current = i;
dcol[0] = current + 1; *dcol.get_mut(0) = current + 1;
for (j, tc) in t.chars().enumerate() { for (j, tc) in t.chars().enumerate() {
let next = dcol[j + 1]; let next = *dcol.get(j + 1);
if sc == tc { if sc == tc {
dcol[j + 1] = current; *dcol.get_mut(j + 1) = current;
} else { } else {
dcol[j + 1] = ::cmp::min(current, next); *dcol.get_mut(j + 1) = ::cmp::min(current, next);
dcol[j + 1] = ::cmp::min(dcol[j + 1], dcol[j]) + 1; *dcol.get_mut(j + 1) = ::cmp::min(*dcol.get(j + 1),
*dcol.get(j)) + 1;
} }
current = next; current = next;
} }
} }
return dcol[tlen]; return *dcol.get(tlen);
} }
fn subslice_offset(&self, inner: &str) -> uint { fn subslice_offset(&self, inner: &str) -> uint {
@ -2738,43 +2730,21 @@ impl<'a> StrSlice<'a> for &'a str {
/// Methods for owned strings /// Methods for owned strings
pub trait OwnedStr { pub trait OwnedStr {
/// Shorten a string to the specified length (which must be <= the current length)
fn truncate(&mut self, len: uint);
/// Consumes the string, returning the underlying byte buffer. /// Consumes the string, returning the underlying byte buffer.
/// ///
/// The buffer does not have a null terminator. /// The buffer does not have a null terminator.
fn into_bytes(self) -> ~[u8]; fn into_bytes(self) -> ~[u8];
/// Sets the length of a string
///
/// This will explicitly set the size of the string, without actually
/// modifying its buffers, so it is up to the caller to ensure that
/// the string is actually the specified size.
unsafe fn set_len(&mut self, new_len: uint);
/// Pushes the given string onto this string, returning the concatenation of the two strings. /// Pushes the given string onto this string, returning the concatenation of the two strings.
fn append(self, rhs: &str) -> ~str; fn append(self, rhs: &str) -> ~str;
} }
impl OwnedStr for ~str { impl OwnedStr for ~str {
#[inline]
fn truncate(&mut self, len: uint) {
assert!(len <= self.len());
assert!(self.is_char_boundary(len));
unsafe { self.set_len(len); }
}
#[inline] #[inline]
fn into_bytes(self) -> ~[u8] { fn into_bytes(self) -> ~[u8] {
unsafe { cast::transmute(self) } unsafe { cast::transmute(self) }
} }
#[inline]
unsafe fn set_len(&mut self, new_len: uint) {
raw::as_owned_vec(self).set_len(new_len)
}
#[inline] #[inline]
fn append(self, rhs: &str) -> ~str { fn append(self, rhs: &str) -> ~str {
let mut new_str = StrBuf::from_owned_str(self); let mut new_str = StrBuf::from_owned_str(self);
@ -3409,8 +3379,7 @@ mod tests {
assert_eq!(a.subslice_offset(c), 0); assert_eq!(a.subslice_offset(c), 0);
let string = "a\nb\nc"; let string = "a\nb\nc";
let mut lines = ~[]; let lines: ~[&str] = string.lines().collect();
for line in string.lines() { lines.push(line) }
assert_eq!(string.subslice_offset(lines[0]), 0); assert_eq!(string.subslice_offset(lines[0]), 0);
assert_eq!(string.subslice_offset(lines[1]), 2); assert_eq!(string.subslice_offset(lines[1]), 2);
assert_eq!(string.subslice_offset(lines[2]), 4); assert_eq!(string.subslice_offset(lines[2]), 4);
@ -4259,9 +4228,9 @@ mod bench {
#[bench] #[bench]
fn from_utf8_lossy_100_invalid(b: &mut Bencher) { fn from_utf8_lossy_100_invalid(b: &mut Bencher) {
let s = ::slice::from_elem(100, 0xF5u8); let s = Vec::from_elem(100, 0xF5u8);
b.iter(|| { b.iter(|| {
let _ = from_utf8_lossy(s); let _ = from_utf8_lossy(s.as_slice());
}); });
} }

View File

@ -23,12 +23,13 @@
use cast; use cast;
use clone::Clone; use clone::Clone;
use iter::Iterator;
use kinds::Send; use kinds::Send;
use ops::Drop; use ops::Drop;
use ptr::RawPtr; use ptr::RawPtr;
use sync::atomics::{fence, AtomicUint, Relaxed, Acquire, Release}; use sync::atomics::{fence, AtomicUint, Relaxed, Acquire, Release};
use slice;
use ty::Unsafe; use ty::Unsafe;
use vec::Vec;
/// An atomically reference counted pointer. /// An atomically reference counted pointer.
/// ///
@ -73,7 +74,8 @@ impl<T: Send> UnsafeArc<T> {
~[] // need to free data here ~[] // need to free data here
} else { } else {
let ptr = new_inner(data, num_handles); let ptr = new_inner(data, num_handles);
slice::from_fn(num_handles, |_| UnsafeArc { data: ptr }) let v = Vec::from_fn(num_handles, |_| UnsafeArc { data: ptr });
v.move_iter().collect()
} }
} }
} }

View File

@ -61,7 +61,7 @@ use ptr::RawPtr;
use sync::arc::UnsafeArc; use sync::arc::UnsafeArc;
use sync::atomics::{AtomicInt, AtomicPtr, SeqCst}; use sync::atomics::{AtomicInt, AtomicPtr, SeqCst};
use unstable::sync::Exclusive; use unstable::sync::Exclusive;
use slice::{OwnedVector, ImmutableVector}; use slice::ImmutableVector;
use vec::Vec; use vec::Vec;
// Once the queue is less than 1/K full, then it will be downsized. Note that // Once the queue is less than 1/K full, then it will be downsized. Note that

View File

@ -115,7 +115,7 @@ mod tests {
#[test] #[test]
fn exclusive_new_arc() { fn exclusive_new_arc() {
unsafe { unsafe {
let mut futures = ~[]; let mut futures = Vec::new();
let num_tasks = 10; let num_tasks = 10;
let count = 10; let count = 10;

View File

@ -614,13 +614,9 @@ impl<T> Vec<T> {
/// ``` /// ```
#[inline] #[inline]
pub fn as_mut_slice<'a>(&'a mut self) -> &'a mut [T] { pub fn as_mut_slice<'a>(&'a mut self) -> &'a mut [T] {
// See the comment in as_slice() for what's going on here. unsafe {
let slice = if mem::size_of::<T>() == 0 { transmute(Slice { data: self.as_mut_ptr() as *T, len: self.len })
Slice { data: 1 as *T, len: self.len } }
} else {
Slice { data: self.ptr as *T, len: self.len }
};
unsafe { transmute(slice) }
} }
/// Creates a consuming iterator, that is, one that moves each /// Creates a consuming iterator, that is, one that moves each
@ -1143,7 +1139,15 @@ impl<T> Vec<T> {
/// would also make any pointers to it invalid. /// would also make any pointers to it invalid.
#[inline] #[inline]
pub fn as_ptr(&self) -> *T { pub fn as_ptr(&self) -> *T {
self.as_slice().as_ptr() // If we have a 0-sized vector, then the base pointer should not be NULL
// because an iterator over the slice will attempt to yield the base
// pointer as the first element in the vector, but this will end up
// being Some(NULL) which is optimized to None.
if mem::size_of::<T>() == 0 {
1 as *T
} else {
self.ptr as *T
}
} }
/// Returns a mutable unsafe pointer to the vector's buffer. /// Returns a mutable unsafe pointer to the vector's buffer.
@ -1155,7 +1159,12 @@ impl<T> Vec<T> {
/// would also make any pointers to it invalid. /// would also make any pointers to it invalid.
#[inline] #[inline]
pub fn as_mut_ptr(&mut self) -> *mut T { pub fn as_mut_ptr(&mut self) -> *mut T {
self.as_mut_slice().as_mut_ptr() // see above for the 0-size check
if mem::size_of::<T>() == 0 {
1 as *mut T
} else {
self.ptr
}
} }
/// Retains only the elements specified by the predicate. /// Retains only the elements specified by the predicate.
@ -1356,16 +1365,7 @@ impl<T> Vector<T> for Vec<T> {
/// ``` /// ```
#[inline] #[inline]
fn as_slice<'a>(&'a self) -> &'a [T] { fn as_slice<'a>(&'a self) -> &'a [T] {
// If we have a 0-sized vector, then the base pointer should not be NULL unsafe { transmute(Slice { data: self.as_ptr(), len: self.len }) }
// because an iterator over the slice will attempt to yield the base
// pointer as the first element in the vector, but this will end up
// being Some(NULL) which is optimized to None.
let slice = if mem::size_of::<T>() == 0 {
Slice { data: 1 as *T, len: self.len }
} else {
Slice { data: self.ptr as *T, len: self.len }
};
unsafe { transmute(slice) }
} }
} }

View File

@ -20,7 +20,6 @@ use rsparse = parse;
use std::fmt::parse; use std::fmt::parse;
use collections::{HashMap, HashSet}; use collections::{HashMap, HashSet};
use std::slice;
#[deriving(Eq)] #[deriving(Eq)]
enum ArgumentType { enum ArgumentType {
@ -609,7 +608,7 @@ impl<'a, 'b> Context<'a, 'b> {
fn to_expr(&self, extra: @ast::Expr) -> @ast::Expr { fn to_expr(&self, extra: @ast::Expr) -> @ast::Expr {
let mut lets = Vec::new(); let mut lets = Vec::new();
let mut locals = Vec::new(); let mut locals = Vec::new();
let mut names = slice::from_fn(self.name_positions.len(), |_| None); let mut names = Vec::from_fn(self.name_positions.len(), |_| None);
let mut pats = Vec::new(); let mut pats = Vec::new();
let mut heads = Vec::new(); let mut heads = Vec::new();
@ -673,7 +672,7 @@ impl<'a, 'b> Context<'a, 'b> {
let lname = self.ecx.ident_of(format!("__arg{}", *name)); let lname = self.ecx.ident_of(format!("__arg{}", *name));
pats.push(self.ecx.pat_ident(e.span, lname)); pats.push(self.ecx.pat_ident(e.span, lname));
heads.push(self.ecx.expr_addr_of(e.span, e)); heads.push(self.ecx.expr_addr_of(e.span, e));
names[*self.name_positions.get(name)] = *names.get_mut(*self.name_positions.get(name)) =
Some(self.format_arg(e.span, Some(self.format_arg(e.span,
Named((*name).clone()), Named((*name).clone()),
self.ecx.expr_ident(e.span, lname))); self.ecx.expr_ident(e.span, lname)));

View File

@ -16,7 +16,6 @@ use collections::{TrieMap, TreeMap, HashMap, HashSet};
use std::os; use std::os;
use rand::{Rng, IsaacRng, SeedableRng}; use rand::{Rng, IsaacRng, SeedableRng};
use std::uint; use std::uint;
use std::slice;
fn timed(label: &str, f: ||) { fn timed(label: &str, f: ||) {
let start = time::precise_time_s(); let start = time::precise_time_s();
@ -99,7 +98,7 @@ fn main() {
} }
}; };
let mut rand = slice::with_capacity(n_keys); let mut rand = Vec::with_capacity(n_keys);
{ {
let mut rng: IsaacRng = SeedableRng::from_seed(&[1, 1, 1, 1, 1, 1, 1]); let mut rng: IsaacRng = SeedableRng::from_seed(&[1, 1, 1, 1, 1, 1, 1]);
@ -130,7 +129,7 @@ fn main() {
{ {
println!(" Random integers:"); println!(" Random integers:");
let mut map: TreeMap<uint,uint> = TreeMap::new(); let mut map: TreeMap<uint,uint> = TreeMap::new();
vector(&mut map, n_keys, rand); vector(&mut map, n_keys, rand.as_slice());
} }
// FIXME: #9970 // FIXME: #9970
@ -149,7 +148,7 @@ fn main() {
{ {
println!(" Random integers:"); println!(" Random integers:");
let mut map: HashMap<uint,uint> = HashMap::new(); let mut map: HashMap<uint,uint> = HashMap::new();
vector(&mut map, n_keys, rand); vector(&mut map, n_keys, rand.as_slice());
} }
// FIXME: #9970 // FIXME: #9970
@ -168,6 +167,6 @@ fn main() {
{ {
println!(" Random integers:"); println!(" Random integers:");
let mut map: TrieMap<uint> = TrieMap::new(); let mut map: TrieMap<uint> = TrieMap::new();
vector(&mut map, n_keys, rand); vector(&mut map, n_keys, rand.as_slice());
} }
} }

View File

@ -9,7 +9,6 @@
// except according to those terms. // except according to those terms.
use std::os; use std::os;
use std::slice;
fn max(a: i32, b: i32) -> i32 { fn max(a: i32, b: i32) -> i32 {
if a > b { if a > b {
@ -20,13 +19,17 @@ fn max(a: i32, b: i32) -> i32 {
} }
fn fannkuch_redux(n: i32) -> i32 { fn fannkuch_redux(n: i32) -> i32 {
let mut perm = slice::from_elem(n as uint, 0i32); let mut perm = Vec::from_elem(n as uint, 0i32);
let mut perm1 = slice::from_fn(n as uint, |i| i as i32); let mut perm1 = Vec::from_fn(n as uint, |i| i as i32);
let mut count = slice::from_elem(n as uint, 0i32); let mut count = Vec::from_elem(n as uint, 0i32);
let mut max_flips_count = 0i32; let mut max_flips_count = 0i32;
let mut perm_count = 0i32; let mut perm_count = 0i32;
let mut checksum = 0i32; let mut checksum = 0i32;
let perm = perm.as_mut_slice();
let perm1 = perm1.as_mut_slice();
let count = count.as_mut_slice();
let mut r = n; let mut r = n;
loop { loop {
while r != 1 { while r != 1 {

View File

@ -12,7 +12,6 @@ use std::cmp::min;
use std::io::{stdout, IoResult}; use std::io::{stdout, IoResult};
use std::os; use std::os;
use std::slice::bytes::copy_memory; use std::slice::bytes::copy_memory;
use std::slice;
static LINE_LEN: uint = 60; static LINE_LEN: uint = 60;
static LOOKUP_SIZE: uint = 4 * 1024; static LOOKUP_SIZE: uint = 4 * 1024;
@ -90,10 +89,10 @@ impl<'a, W: Writer> RepeatFasta<'a, W> {
fn make(&mut self, n: uint) -> IoResult<()> { fn make(&mut self, n: uint) -> IoResult<()> {
let alu_len = self.alu.len(); let alu_len = self.alu.len();
let mut buf = slice::from_elem(alu_len + LINE_LEN, 0u8); let mut buf = Vec::from_elem(alu_len + LINE_LEN, 0u8);
let alu: &[u8] = self.alu.as_bytes(); let alu: &[u8] = self.alu.as_bytes();
copy_memory(buf, alu); copy_memory(buf.as_mut_slice(), alu);
let buf_len = buf.len(); let buf_len = buf.len();
copy_memory(buf.mut_slice(alu_len, buf_len), copy_memory(buf.mut_slice(alu_len, buf_len),
alu.slice_to(LINE_LEN)); alu.slice_to(LINE_LEN));

View File

@ -14,7 +14,6 @@ use std::from_str::FromStr;
use std::iter::count; use std::iter::count;
use std::cmp::min; use std::cmp::min;
use std::os; use std::os;
use std::slice::from_elem;
use sync::{Arc, RWLock}; use sync::{Arc, RWLock};
fn A(i: uint, j: uint) -> f64 { fn A(i: uint, j: uint) -> f64 {

View File

@ -13,5 +13,4 @@
fn main() { fn main() {
~[1]; //~ ERROR use of deprecated `~[]` ~[1]; //~ ERROR use of deprecated `~[]`
//~^ ERROR use of deprecated `~[]` //~^ ERROR use of deprecated `~[]`
std::slice::with_capacity::<int>(10); //~ ERROR use of deprecated `~[]`
} }

View File

@ -29,7 +29,12 @@ use test::B;
// Make sure this import is warned about when at least one of its imported names // Make sure this import is warned about when at least one of its imported names
// is unused // is unused
use std::slice::{from_fn, from_elem}; //~ ERROR unused import use test2::{foo, bar}; //~ ERROR unused import
mod test2 {
pub fn foo() {}
pub fn bar() {}
}
mod test { mod test {
pub trait A { fn a(&self) {} } pub trait A { fn a(&self) {} }
@ -66,5 +71,5 @@ fn main() {
let mut b = 4; let mut b = 4;
swap(&mut a, &mut b); swap(&mut a, &mut b);
test::C.b(); test::C.b();
let _a = from_elem(0, 0); let _a = foo();
} }

View File

@ -36,7 +36,7 @@ fn double() {
} }
fn runtest(me: &str) { fn runtest(me: &str) {
let mut env = os::env(); let mut env = os::env().move_iter().collect::<Vec<(~str, ~str)>>();
match env.iter().position(|&(ref s, _)| "RUST_BACKTRACE" == *s) { match env.iter().position(|&(ref s, _)| "RUST_BACKTRACE" == *s) {
Some(i) => { env.remove(i); } Some(i) => { env.remove(i); }
None => {} None => {}