1
Fork 0

auto merge of #17029 : alexcrichton/rust/vec-stable, r=aturon

The following methods, types, and names have become stable:

* Vec
* Vec::as_mut_slice
* Vec::as_slice
* Vec::capacity
* Vec::clear
* Vec::default
* Vec::grow
* Vec::insert
* Vec::len
* Vec::new
* Vec::pop
* Vec::push
* Vec::remove
* Vec::set_len
* Vec::shrink_to_fit
* Vec::truncate
* Vec::with_capacity
* vec::raw
* vec::raw::from_buf
* vec::raw::from_raw_parts

The following have become unstable:

* Vec::dedup        // naming
* Vec::from_fn      // naming and unboxed closures
* Vec::get_mut      // will be removed for IndexMut
* Vec::grow_fn      // unboxed closures and naming
* Vec::retain       // unboxed closures
* Vec::swap_remove  // uncertain naming
* Vec::from_elem    // uncertain semantics
* vec::unzip        // should be generic for all collections

The following have been deprecated

* Vec::append - call .extend()
* Vec::append_one - call .push()
* Vec::from_slice - call .to_vec()
* Vec::grow_set - call .grow() and then .push()
* Vec::into_vec - move the vector instead
* Vec::move_iter - renamed to iter_move()
* Vec::push_all - call .extend()
* Vec::to_vec - call .clone()
* Vec:from_raw_parts - moved to raw::from_raw_parts

This is a breaking change in terms of the signature of the `Vec::grow` function.
The argument used to be taken by reference, but it is now taken by value. Code
must update by removing a leading `&` sigil or by calling `.clone()` to create a
value.

[breaking-change]
This commit is contained in:
bors 2014-09-22 05:30:30 +00:00
commit cbb07e81be
39 changed files with 252 additions and 210 deletions

View file

@ -273,8 +273,8 @@ fn run_pretty_test(config: &Config, props: &TestProps, testfile: &Path) {
format!("--target={}", config.target),
"-L".to_string(),
aux_dir.as_str().unwrap().to_string());
args.push_all_move(split_maybe_args(&config.target_rustcflags));
args.push_all_move(split_maybe_args(&props.compile_flags));
args.extend(split_maybe_args(&config.target_rustcflags).into_iter());
args.extend(split_maybe_args(&props.compile_flags).into_iter());
return ProcArgs {
prog: config.rustc_path.as_str().unwrap().to_string(),
args: args,
@ -321,8 +321,8 @@ actual:\n\
config.build_base.as_str().unwrap().to_string(),
"-L".to_string(),
aux_dir.as_str().unwrap().to_string());
args.push_all_move(split_maybe_args(&config.target_rustcflags));
args.push_all_move(split_maybe_args(&props.compile_flags));
args.extend(split_maybe_args(&config.target_rustcflags).into_iter());
args.extend(split_maybe_args(&props.compile_flags).into_iter());
// FIXME (#9639): This needs to handle non-utf8 paths
return ProcArgs {
prog: config.rustc_path.as_str().unwrap().to_string(),
@ -1095,11 +1095,12 @@ fn compile_test_(config: &Config, props: &TestProps,
testfile: &Path, extra_args: &[String]) -> ProcRes {
let aux_dir = aux_output_dir_name(config, testfile);
// FIXME (#9639): This needs to handle non-utf8 paths
let link_args = vec!("-L".to_string(),
aux_dir.as_str().unwrap().to_string());
let mut link_args = vec!("-L".to_string(),
aux_dir.as_str().unwrap().to_string());
link_args.extend(extra_args.iter().map(|s| s.clone()));
let args = make_compile_args(config,
props,
link_args.append(extra_args),
link_args,
|a, b| ThisFile(make_exe_name(a, b)), testfile);
compose_and_run_compiler(config, props, testfile, args, None)
}
@ -1146,16 +1147,16 @@ fn compose_and_run_compiler(
for rel_ab in props.aux_builds.iter() {
let abs_ab = config.aux_base.join(rel_ab.as_slice());
let aux_props = header::load_props(&abs_ab);
let crate_type = if aux_props.no_prefer_dynamic {
let mut crate_type = if aux_props.no_prefer_dynamic {
Vec::new()
} else {
vec!("--crate-type=dylib".to_string())
};
crate_type.extend(extra_link_args.clone().into_iter());
let aux_args =
make_compile_args(config,
&aux_props,
crate_type.append(
extra_link_args.as_slice()),
crate_type,
|a,b| {
let f = make_lib_name(a, b, testfile);
ThisDirectory(f.dir_path())
@ -1246,11 +1247,11 @@ fn make_compile_args(config: &Config,
};
args.push(path.as_str().unwrap().to_string());
if props.force_host {
args.push_all_move(split_maybe_args(&config.host_rustcflags));
args.extend(split_maybe_args(&config.host_rustcflags).into_iter());
} else {
args.push_all_move(split_maybe_args(&config.target_rustcflags));
args.extend(split_maybe_args(&config.target_rustcflags).into_iter());
}
args.push_all_move(split_maybe_args(&props.compile_flags));
args.extend(split_maybe_args(&props.compile_flags).into_iter());
return ProcArgs {
prog: config.rustc_path.as_str().unwrap().to_string(),
args: args,
@ -1267,10 +1268,9 @@ fn make_lib_name(config: &Config, auxfile: &Path, testfile: &Path) -> Path {
fn make_exe_name(config: &Config, testfile: &Path) -> Path {
let mut f = output_base_name(config, testfile);
if !os::consts::EXE_SUFFIX.is_empty() {
match f.filename().map(|s| Vec::from_slice(s).append(os::consts::EXE_SUFFIX.as_bytes())) {
Some(v) => f.set_filename(v),
None => ()
}
let mut fname = f.filename().unwrap().to_vec();
fname.extend(os::consts::EXE_SUFFIX.bytes());
f.set_filename(fname);
}
f
}
@ -1286,7 +1286,7 @@ fn make_run_args(config: &Config, props: &TestProps, testfile: &Path) ->
args.push(exe_file.as_str().unwrap().to_string());
// Add the arguments in the run_flags directive
args.push_all_move(split_maybe_args(&props.run_flags));
args.extend(split_maybe_args(&props.run_flags).into_iter());
let prog = args.remove(0).unwrap();
return ProcArgs {
@ -1381,12 +1381,10 @@ fn make_out_name(config: &Config, testfile: &Path, extension: &str) -> Path {
}
fn aux_output_dir_name(config: &Config, testfile: &Path) -> Path {
let mut f = output_base_name(config, testfile);
match f.filename().map(|s| Vec::from_slice(s).append(b".libaux")) {
Some(v) => f.set_filename(v),
None => ()
}
f
let f = output_base_name(config, testfile);
let mut fname = f.filename().unwrap().to_vec();
fname.extend("libaux".bytes());
f.with_filename(fname)
}
fn output_testname(testfile: &Path) -> Path {
@ -1598,8 +1596,10 @@ fn append_suffix_to_stem(p: &Path, suffix: &str) -> Path {
if suffix.len() == 0 {
(*p).clone()
} else {
let stem = p.filestem().unwrap();
p.with_filename(Vec::from_slice(stem).append(b"-").append(suffix.as_bytes()))
let mut stem = p.filestem().unwrap().to_vec();
stem.extend("-".bytes());
stem.extend(suffix.bytes());
p.with_filename(stem)
}
}
@ -1607,13 +1607,14 @@ fn compile_test_and_save_bitcode(config: &Config, props: &TestProps,
testfile: &Path) -> ProcRes {
let aux_dir = aux_output_dir_name(config, testfile);
// FIXME (#9639): This needs to handle non-utf8 paths
let link_args = vec!("-L".to_string(),
aux_dir.as_str().unwrap().to_string());
let mut link_args = vec!("-L".to_string(),
aux_dir.as_str().unwrap().to_string());
let llvm_args = vec!("--emit=bc,obj".to_string(),
"--crate-type=lib".to_string());
link_args.extend(llvm_args.into_iter());
let args = make_compile_args(config,
props,
link_args.append(llvm_args.as_slice()),
link_args,
|a, b| ThisDirectory(output_base_name(a, b).dir_path()),
testfile);
compose_and_run_compiler(config, props, testfile, args, None)

View file

@ -3833,8 +3833,9 @@ fn map<A: Clone, B: Clone>(f: |A| -> B, xs: &[A]) -> Vec<B> {
return vec![];
}
let first: B = f(xs[0].clone());
let rest: Vec<B> = map(f, xs.slice(1, xs.len()));
return vec![first].append(rest.as_slice());
let mut rest: Vec<B> = map(f, xs.slice(1, xs.len()));
rest.insert(0, first);
return rest;
}
~~~~

View file

@ -631,7 +631,7 @@ impl Bitv {
let old_size = self.storage.len();
let size = (size + uint::BITS - 1) / uint::BITS;
if old_size < size {
self.storage.grow(size - old_size, &0);
self.storage.grow(size - old_size, 0);
}
}
@ -687,7 +687,7 @@ impl Bitv {
// Allocate new words, if needed
if new_nwords > self.storage.len() {
let to_add = new_nwords - self.storage.len();
self.storage.grow(to_add, &full_value);
self.storage.grow(to_add, full_value);
}
// Adjust internal bit count
self.nbits = new_nbits;

View file

@ -283,7 +283,11 @@ pub trait CloneableVector<T> {
impl<'a, T: Clone> CloneableVector<T> for &'a [T] {
/// Returns a copy of `v`.
#[inline]
fn to_vec(&self) -> Vec<T> { Vec::from_slice(*self) }
fn to_vec(&self) -> Vec<T> {
let mut vector = Vec::with_capacity(self.len());
vector.push_all(*self);
vector
}
#[inline(always)]
fn into_vec(self) -> Vec<T> { self.to_vec() }
@ -1039,7 +1043,7 @@ mod tests {
fn test_grow() {
// Test on-stack grow().
let mut v = vec![];
v.grow(2u, &1i);
v.grow(2u, 1i);
{
let v = v.as_slice();
assert_eq!(v.len(), 2u);
@ -1048,7 +1052,7 @@ mod tests {
}
// Test on-heap grow().
v.grow(3u, &2i);
v.grow(3u, 2i);
{
let v = v.as_slice();
assert_eq!(v.len(), 5u);

View file

@ -67,6 +67,7 @@ use core::prelude::{range};
use {Deque, MutableSeq};
use hash;
use ringbuf::RingBuf;
use slice::CloneableVector;
use string::String;
use unicode;
use vec::Vec;
@ -754,7 +755,7 @@ pub trait StrAllocating: Str {
#[inline]
fn to_owned(&self) -> String {
unsafe {
mem::transmute(Vec::from_slice(self.as_slice().as_bytes()))
mem::transmute(self.as_slice().as_bytes().to_vec())
}
}

View file

@ -23,6 +23,7 @@ use core::raw::Slice as RawSlice;
use {Mutable, MutableSeq};
use hash;
use slice::CloneableVector;
use str;
use str::{CharRange, StrAllocating, MaybeOwned, Owned};
use str::Slice as MaybeOwnedSlice; // So many `Slice`s...
@ -75,9 +76,7 @@ impl String {
/// ```
#[inline]
pub fn from_str(string: &str) -> String {
String {
vec: Vec::from_slice(string.as_bytes())
}
String { vec: string.as_bytes().to_vec() }
}
/// Deprecated. Replaced by `string::raw::from_parts`

View file

@ -99,6 +99,7 @@ use slice::{Items, MutItems};
/// to use `Vec::with_capacity` whenever possible to specify how big the vector
/// is expected to get.
#[unsafe_no_drop_flag]
#[stable]
pub struct Vec<T> {
len: uint,
cap: uint,
@ -116,6 +117,7 @@ impl<T> Vec<T> {
/// let mut vec: Vec<int> = Vec::new();
/// ```
#[inline]
#[stable]
pub fn new() -> Vec<T> {
// We want ptr to never be NULL so instead we set it to some arbitrary
// non-null value which is fine since we never call deallocate on the ptr
@ -152,6 +154,7 @@ impl<T> Vec<T> {
/// vec.push(11);
/// ```
#[inline]
#[stable]
pub fn with_capacity(capacity: uint) -> Vec<T> {
if mem::size_of::<T>() == 0 {
Vec { len: 0, cap: uint::MAX, ptr: EMPTY as *mut T }
@ -177,6 +180,8 @@ impl<T> Vec<T> {
/// assert_eq!(vec, vec![0, 2, 4]);
/// ```
#[inline]
#[unstable = "the naming is uncertain as well as this migrating to unboxed \
closures in the future"]
pub fn from_fn(length: uint, op: |uint| -> T) -> Vec<T> {
unsafe {
let mut xs = Vec::with_capacity(length);
@ -229,6 +234,7 @@ impl<T> Vec<T> {
/// }
/// }
/// ```
#[experimental]
pub unsafe fn from_raw_parts(length: uint, capacity: uint,
ptr: *mut T) -> Vec<T> {
Vec { len: length, cap: capacity, ptr: ptr }
@ -249,6 +255,7 @@ impl<T> Vec<T> {
/// assert_eq!(odd, vec![1, 3]);
/// ```
#[inline]
#[experimental]
pub fn partition(self, f: |&T| -> bool) -> (Vec<T>, Vec<T>) {
let mut lefts = Vec::new();
let mut rights = Vec::new();
@ -266,36 +273,18 @@ impl<T> Vec<T> {
}
impl<T: Clone> Vec<T> {
/// Iterates over the `second` vector, copying each element and appending it to
/// the `first`. Afterwards, the `first` is then returned for use again.
///
/// # Example
///
/// ```
/// let vec = vec![1i, 2i];
/// let vec = vec.append([3i, 4i]);
/// assert_eq!(vec, vec![1, 2, 3, 4]);
/// ```
/// Deprecated, call `extend` instead.
#[inline]
#[deprecated = "this function has been deprecated in favor of extend()"]
pub fn append(mut self, second: &[T]) -> Vec<T> {
self.push_all(second);
self
}
/// Constructs a `Vec` by cloning elements of a slice.
///
/// # Example
///
/// ```
/// let slice = [1i, 2, 3];
/// let vec = Vec::from_slice(slice);
/// ```
/// Deprecated, call `to_vec()` instead
#[inline]
pub fn from_slice(values: &[T]) -> Vec<T> {
let mut vector = Vec::new();
vector.push_all(values);
vector
}
#[deprecated = "this function has been deprecated in favor of to_vec()"]
pub fn from_slice(values: &[T]) -> Vec<T> { values.to_vec() }
/// Constructs a `Vec` with copies of a value.
///
@ -307,6 +296,7 @@ impl<T: Clone> Vec<T> {
/// println!("{}", vec); // prints [hi, hi, hi]
/// ```
#[inline]
#[unstable = "this functionality may become more generic over all collections"]
pub fn from_elem(length: uint, value: T) -> Vec<T> {
unsafe {
let mut xs = Vec::with_capacity(length);
@ -333,6 +323,7 @@ impl<T: Clone> Vec<T> {
/// assert_eq!(vec, vec![1, 2, 3, 4]);
/// ```
#[inline]
#[experimental]
pub fn push_all(&mut self, other: &[T]) {
self.reserve_additional(other.len());
@ -359,15 +350,16 @@ impl<T: Clone> Vec<T> {
///
/// ```
/// let mut vec = vec!["hello"];
/// vec.grow(2, &("world"));
/// vec.grow(2, "world");
/// assert_eq!(vec, vec!["hello", "world", "world"]);
/// ```
pub fn grow(&mut self, n: uint, value: &T) {
#[stable]
pub fn grow(&mut self, n: uint, value: T) {
self.reserve_additional(n);
let mut i: uint = 0u;
while i < n {
self.push((*value).clone());
self.push(value.clone());
i += 1u;
}
}
@ -382,15 +374,17 @@ impl<T: Clone> Vec<T> {
/// # Example
///
/// ```
/// # #![allow(deprecated)]
/// let mut vec = vec!["a", "b", "c"];
/// vec.grow_set(1, &("fill"), "d");
/// vec.grow_set(4, &("fill"), "e");
/// assert_eq!(vec, vec!["a", "d", "c", "fill", "e"]);
/// ```
#[deprecated = "call .grow() and .push() manually instead"]
pub fn grow_set(&mut self, index: uint, initval: &T, value: T) {
let l = self.len();
if index >= l {
self.grow(index - l + 1u, initval);
self.grow(index - l + 1u, initval.clone());
}
*self.get_mut(index) = value;
}
@ -409,6 +403,7 @@ impl<T: Clone> Vec<T> {
/// assert_eq!(even, vec![2i, 4]);
/// assert_eq!(odd, vec![1i, 3]);
/// ```
#[experimental]
pub fn partitioned(&self, f: |&T| -> bool) -> (Vec<T>, Vec<T>) {
let mut lefts = Vec::new();
let mut rights = Vec::new();
@ -427,9 +422,7 @@ impl<T: Clone> Vec<T> {
#[unstable]
impl<T:Clone> Clone for Vec<T> {
fn clone(&self) -> Vec<T> {
Vec::from_slice(self.as_slice())
}
fn clone(&self) -> Vec<T> { self.as_slice().to_vec() }
fn clone_from(&mut self, other: &Vec<T>) {
// drop anything in self that will not be overwritten
@ -449,6 +442,7 @@ impl<T:Clone> Clone for Vec<T> {
}
}
#[experimental = "waiting on Index stability"]
impl<T> Index<uint,T> for Vec<T> {
#[inline]
#[allow(deprecated)] // allow use of get
@ -506,6 +500,8 @@ impl<T> ops::SliceMut<uint, [T]> for Vec<T> {
self.as_mut_slice().slice_mut_(start, end)
}
}
#[experimental = "waiting on FromIterator stability"]
impl<T> FromIterator<T> for Vec<T> {
#[inline]
fn from_iter<I:Iterator<T>>(mut iterator: I) -> Vec<T> {
@ -518,6 +514,7 @@ impl<T> FromIterator<T> for Vec<T> {
}
}
#[experimental = "waiting on Extendable stability"]
impl<T> Extendable<T> for Vec<T> {
#[inline]
fn extend<I: Iterator<T>>(&mut self, mut iterator: I) {
@ -529,6 +526,7 @@ impl<T> Extendable<T> for Vec<T> {
}
}
#[unstable = "waiting on PartialEq stability"]
impl<T: PartialEq> PartialEq for Vec<T> {
#[inline]
fn eq(&self, other: &Vec<T>) -> bool {
@ -536,6 +534,7 @@ impl<T: PartialEq> PartialEq for Vec<T> {
}
}
#[unstable = "waiting on PartialOrd stability"]
impl<T: PartialOrd> PartialOrd for Vec<T> {
#[inline]
fn partial_cmp(&self, other: &Vec<T>) -> Option<Ordering> {
@ -543,13 +542,16 @@ impl<T: PartialOrd> PartialOrd for Vec<T> {
}
}
#[unstable = "waiting on Eq stability"]
impl<T: Eq> Eq for Vec<T> {}
#[experimental]
impl<T: PartialEq, V: Slice<T>> Equiv<V> for Vec<T> {
#[inline]
fn equiv(&self, other: &V) -> bool { self.as_slice() == other.as_slice() }
}
#[unstable = "waiting on Ord stability"]
impl<T: Ord> Ord for Vec<T> {
#[inline]
fn cmp(&self, other: &Vec<T>) -> Ordering {
@ -557,15 +559,19 @@ impl<T: Ord> Ord for Vec<T> {
}
}
#[experimental = "waiting on Collection stability"]
impl<T> Collection for Vec<T> {
#[inline]
#[stable]
fn len(&self) -> uint {
self.len
}
}
impl<T: Clone> CloneableVector<T> for Vec<T> {
#[deprecated = "call .clone() instead"]
fn to_vec(&self) -> Vec<T> { self.clone() }
#[deprecated = "move the vector instead"]
fn into_vec(self) -> Vec<T> { self }
}
@ -600,6 +606,7 @@ impl<T> Vec<T> {
/// assert_eq!(vec.capacity(), 10);
/// ```
#[inline]
#[stable]
pub fn capacity(&self) -> uint {
self.cap
}
@ -683,6 +690,7 @@ impl<T> Vec<T> {
/// let mut vec = vec![1i, 2, 3];
/// vec.shrink_to_fit();
/// ```
#[stable]
pub fn shrink_to_fit(&mut self) {
if mem::size_of::<T>() == 0 { return }
@ -706,17 +714,9 @@ impl<T> Vec<T> {
}
}
/// Appends one element to the vector provided. The vector itself is then
/// returned for use again.
///
/// # Example
///
/// ```
/// let vec = vec![1i, 2];
/// let vec = vec.append_one(3);
/// assert_eq!(vec, vec![1, 2, 3]);
/// ```
/// Deprecated, call `push` instead
#[inline]
#[deprecated = "call .push() instead"]
pub fn append_one(mut self, x: T) -> Vec<T> {
self.push(x);
self
@ -734,6 +734,7 @@ impl<T> Vec<T> {
/// vec.truncate(2);
/// assert_eq!(vec, vec![1, 2]);
/// ```
#[unstable = "waiting on failure semantics"]
pub fn truncate(&mut self, len: uint) {
unsafe {
// drop any extra elements
@ -757,6 +758,7 @@ impl<T> Vec<T> {
/// foo(vec.as_mut_slice());
/// ```
#[inline]
#[stable]
pub fn as_mut_slice<'a>(&'a mut self) -> &'a mut [T] {
unsafe {
mem::transmute(RawSlice {
@ -796,7 +798,6 @@ impl<T> Vec<T> {
}
}
/// Sets the length of a vector.
///
/// This will explicitly set the size of the vector, without actually
@ -812,6 +813,7 @@ impl<T> Vec<T> {
/// }
/// ```
#[inline]
#[stable]
pub unsafe fn set_len(&mut self, len: uint) {
self.len = len;
}
@ -850,6 +852,7 @@ impl<T> Vec<T> {
/// assert_eq!(vec, vec![1i, 4, 3]);
/// ```
#[inline]
#[unstable = "this is likely to be moved to actual indexing"]
pub fn get_mut<'a>(&'a mut self, index: uint) -> &'a mut T {
&mut self.as_mut_slice()[index]
}
@ -1020,6 +1023,7 @@ impl<T> Vec<T> {
/// assert_eq!(v.swap_remove(2), None);
/// ```
#[inline]
#[unstable = "the naming of this function may be altered"]
pub fn swap_remove(&mut self, index: uint) -> Option<T> {
let length = self.len();
if length > 0 && index < length - 1 {
@ -1088,6 +1092,7 @@ impl<T> Vec<T> {
/// vec.insert(4, 5);
/// assert_eq!(vec, vec![1, 4, 2, 3, 5]);
/// ```
#[unstable = "failure semantics need settling"]
pub fn insert(&mut self, index: uint, element: T) {
let len = self.len();
assert!(index <= len);
@ -1124,6 +1129,7 @@ impl<T> Vec<T> {
/// // v is unchanged:
/// assert_eq!(v, vec![1, 3]);
/// ```
#[unstable = "failure semantics need settling"]
pub fn remove(&mut self, index: uint) -> Option<T> {
let len = self.len();
if index < len {
@ -1155,11 +1161,13 @@ impl<T> Vec<T> {
/// # Example
///
/// ```
/// # #![allow(deprecated)]
/// let mut vec = vec![box 1i];
/// vec.push_all_move(vec![box 2, box 3, box 4]);
/// assert_eq!(vec, vec![box 1, box 2, box 3, box 4]);
/// ```
#[inline]
#[deprecated = "use .extend(other.into_iter())"]
pub fn push_all_move(&mut self, other: Vec<T>) {
self.extend(other.into_iter());
}
@ -1410,6 +1418,7 @@ impl<T> Vec<T> {
/// vec.retain(|x| x%2 == 0);
/// assert_eq!(vec, vec![2, 4]);
/// ```
#[unstable = "the closure argument may become an unboxed closure"]
pub fn retain(&mut self, f: |&T| -> bool) {
let len = self.len();
let mut del = 0u;
@ -1441,6 +1450,7 @@ impl<T> Vec<T> {
/// vec.grow_fn(3, |i| i);
/// assert_eq!(vec, vec![0, 1, 0, 1, 2]);
/// ```
#[unstable = "this function may be renamed or change to unboxed closures"]
pub fn grow_fn(&mut self, n: uint, f: |uint| -> T) {
self.reserve_additional(n);
for i in range(0u, n) {
@ -1467,8 +1477,10 @@ impl<T:Ord> Vec<T> {
}
}
#[experimental = "waiting on Mutable stability"]
impl<T> Mutable for Vec<T> {
#[inline]
#[stable]
fn clear(&mut self) {
self.truncate(0)
}
@ -1499,6 +1511,7 @@ impl<T: PartialEq> Vec<T> {
/// vec.dedup();
/// assert_eq!(vec, vec![1i, 2, 3, 2]);
/// ```
#[unstable = "this function may be renamed"]
pub fn dedup(&mut self) {
unsafe {
// Although we have a mutable reference to `self`, we cannot make
@ -1596,6 +1609,7 @@ impl<T> Slice<T> for Vec<T> {
/// foo(vec.as_slice());
/// ```
#[inline]
#[stable]
fn as_slice<'a>(&'a self) -> &'a [T] {
unsafe { mem::transmute(RawSlice { data: self.as_ptr(), len: self.len }) }
}
@ -1627,18 +1641,21 @@ impl<T> Drop for Vec<T> {
}
}
#[stable]
impl<T> Default for Vec<T> {
fn default() -> Vec<T> {
Vec::new()
}
}
#[experimental = "waiting on Show stability"]
impl<T:fmt::Show> fmt::Show for Vec<T> {
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
self.as_slice().fmt(f)
}
}
#[experimental = "waiting on MutableSeq stability"]
impl<T> MutableSeq<T> for Vec<T> {
/// Appends an element to the back of a collection.
///
@ -1654,6 +1671,7 @@ impl<T> MutableSeq<T> for Vec<T> {
/// assert_eq!(vec, vec!(1, 2, 3));
/// ```
#[inline]
#[stable]
fn push(&mut self, value: T) {
if mem::size_of::<T>() == 0 {
// zero-size types consume no memory, so we can't rely on the address space running out
@ -1680,6 +1698,7 @@ impl<T> MutableSeq<T> for Vec<T> {
}
#[inline]
#[stable]
fn pop(&mut self) -> Option<T> {
if self.len == 0 {
None
@ -1765,6 +1784,7 @@ impl<T> Drop for MoveItems<T> {
/// 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.
#[unstable = "this functionality may become more generic over time"]
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);
@ -1777,6 +1797,7 @@ pub fn unzip<T, U, V: Iterator<(T, U)>>(mut iter: V) -> (Vec<T>, Vec<U>) {
}
/// Unsafe vector operations.
#[unstable]
pub mod raw {
use super::Vec;
use core::ptr;
@ -1786,6 +1807,7 @@ pub mod raw {
/// The elements of the buffer are copied into the vector without cloning,
/// as if `ptr::read()` were called on them.
#[inline]
#[unstable]
pub unsafe fn from_buf<T>(ptr: *const T, elts: uint) -> Vec<T> {
let mut dst = Vec::with_capacity(elts);
dst.set_len(elts);

View file

@ -170,7 +170,7 @@ impl<'a,T:Clone> MaybeOwnedVector<'a,T> {
pub fn into_vec(self) -> Vec<T> {
match self {
Growable(v) => v,
Borrowed(v) => Vec::from_slice(v),
Borrowed(v) => v.to_vec(),
}
}
}

View file

@ -87,7 +87,7 @@ impl Writer for SeekableMemWriter {
// currently are
let difference = self.pos as i64 - self.buf.len() as i64;
if difference > 0 {
self.buf.grow(difference as uint, &0);
self.buf.grow(difference as uint, 0);
}
// Figure out what bytes will be used to overwrite what's currently

View file

@ -156,7 +156,7 @@ impl<'r> Compiler<'r> {
Capture(cap, name, x) => {
let len = self.names.len();
if cap >= len {
self.names.grow(10 + cap - len, &None)
self.names.grow(10 + cap - len, None)
}
*self.names.get_mut(cap) = name;

View file

@ -986,9 +986,9 @@ fn combine_ranges(unordered: Vec<(char, char)>) -> Vec<(char, char)> {
// (or any of their negated forms). Note that this does not handle negation.
fn perl_unicode_class(which: char) -> Vec<(char, char)> {
match which.to_lowercase() {
'd' => Vec::from_slice(PERLD),
's' => Vec::from_slice(PERLS),
'w' => Vec::from_slice(PERLW),
'd' => PERLD.to_vec(),
's' => PERLS.to_vec(),
'w' => PERLW.to_vec(),
_ => unreachable!(),
}
}
@ -997,7 +997,7 @@ fn perl_unicode_class(which: char) -> Vec<(char, char)> {
// `Cat` expression will never be a direct child of another `Cat` expression.
fn concat_flatten(x: Ast, y: Ast) -> Ast {
match (x, y) {
(Cat(mut xs), Cat(ys)) => { xs.push_all_move(ys); Cat(xs) }
(Cat(mut xs), Cat(ys)) => { xs.extend(ys.into_iter()); Cat(xs) }
(Cat(mut xs), ast) => { xs.push(ast); Cat(xs) }
(ast, Cat(mut xs)) => { xs.insert(0, ast); Cat(xs) }
(ast1, ast2) => Cat(vec!(ast1, ast2)),
@ -1019,7 +1019,7 @@ fn is_valid_cap(c: char) -> bool {
fn find_class(classes: NamedClasses, name: &str) -> Option<Vec<(char, char)>> {
match classes.binary_search(|&(s, _)| s.cmp(&name)) {
slice::Found(i) => Some(Vec::from_slice(classes[i].val1())),
slice::Found(i) => Some(classes[i].val1().to_vec()),
slice::NotFound(_) => None,
}
}

View file

@ -133,7 +133,7 @@ impl<'a> NfaGen<'a> {
let init_groups = self.vec_expr(range(0, num_cap_locs),
|cx, _| cx.expr_none(self.sp));
let prefix_lit = Rc::new(Vec::from_slice(self.prog.prefix.as_slice().as_bytes()));
let prefix_lit = Rc::new(self.prog.prefix.as_slice().as_bytes().to_vec());
let prefix_bytes = self.cx.expr_lit(self.sp, ast::LitBinary(prefix_lit));
let check_prefix = self.check_prefix();

View file

@ -505,7 +505,7 @@ fn external_path(cx: &DocContext, name: &str, substs: &subst::Substs) -> Path {
.iter()
.filter_map(|v| v.clean(cx))
.collect();
let types = Vec::from_slice(substs.types.get_slice(subst::TypeSpace));
let types = substs.types.get_slice(subst::TypeSpace).to_vec();
let types = types.clean(cx);
Path {
global: false,
@ -661,8 +661,8 @@ impl<'a> Clean<Generics> for (&'a ty::Generics, subst::ParamSpace) {
fn clean(&self, cx: &DocContext) -> Generics {
let (me, space) = *self;
Generics {
type_params: Vec::from_slice(me.types.get_slice(space)).clean(cx),
lifetimes: Vec::from_slice(me.regions.get_slice(space)).clean(cx),
type_params: me.types.get_slice(space).to_vec().clean(cx),
lifetimes: me.regions.get_slice(space).to_vec().clean(cx),
}
}
}
@ -991,7 +991,7 @@ impl Clean<Item> for ty::Method {
self.fty.sig.clone()),
s => {
let sig = ty::FnSig {
inputs: Vec::from_slice(self.fty.sig.inputs.slice_from(1)),
inputs: self.fty.sig.inputs.slice_from(1).to_vec(),
..self.fty.sig.clone()
};
let s = match s {

View file

@ -183,8 +183,8 @@ mod imp {
impl Lock {
pub fn new(p: &Path) -> Lock {
let p_16: Vec<u16> = p.as_str().unwrap().utf16_units().collect();
let p_16 = p_16.append_one(0);
let mut p_16: Vec<u16> = p.as_str().unwrap().utf16_units().collect();
p_16.push(0);
let handle = unsafe {
libc::CreateFileW(p_16.as_ptr(),
libc::FILE_GENERIC_READ |

View file

@ -740,8 +740,9 @@ impl<'a> SourceCollector<'a> {
root_path.push_str("../");
});
cur.push(Vec::from_slice(p.filename().expect("source has no filename"))
.append(b".html"));
let mut fname = p.filename().expect("source has no filename").to_vec();
fname.extend(".html".bytes());
cur.push(fname);
let mut w = BufferedWriter::new(try!(File::create(&cur)));
let title = format!("{} -- source", cur.filename_display());

View file

@ -47,6 +47,7 @@ mod imp {
use core::prelude::*;
use alloc::boxed::Box;
use collections::slice::CloneableVector;
use collections::vec::Vec;
use core::mem;
use core::slice;
@ -106,7 +107,7 @@ mod imp {
let mut len = 0;
while *base.offset(len) != 0 { len += 1; }
slice::raw::buf_as_slice(base, len as uint, |slice| {
Vec::from_slice(slice)
slice.to_vec()
})
})
}

View file

@ -655,7 +655,7 @@ impl rtio::RtioUdpSocket for UdpWatcher {
// see comments in StreamWatcher::write for why we may allocate a buffer
// here.
let data = if guard.can_timeout {Some(Vec::from_slice(buf))} else {None};
let data = if guard.can_timeout {Some(buf.to_vec())} else {None};
let uv_buf = if guard.can_timeout {
slice_to_uv_buf(data.as_ref().unwrap().as_slice())
} else {

View file

@ -159,7 +159,7 @@ impl StreamWatcher {
//
// To do this, the write context has an optionally owned vector of
// bytes.
let data = if may_timeout {Some(Vec::from_slice(buf))} else {None};
let data = if may_timeout {Some(buf.to_vec())} else {None};
let uv_buf = if may_timeout {
slice_to_uv_buf(data.as_ref().unwrap().as_slice())
} else {

View file

@ -21,8 +21,7 @@ use mem;
use option::{Option, Some, None};
use slice::{ImmutableSlice, MutableSlice, Slice};
use str::{Str, StrSlice};
use str;
use string::String;
use string::{mod, String};
use to_string::IntoStr;
use vec::Vec;
@ -113,7 +112,7 @@ impl Ascii {
/// Check if the character is a letter or number
#[inline]
pub fn is_alphanumeric(&self) -> bool {
self.is_alpha() || self.is_digit()
self.is_alphabetic() || self.is_digit()
}
/// Check if the character is a space or horizontal tab
@ -169,7 +168,7 @@ impl Ascii {
/// Checks if the character is punctuation
#[inline]
pub fn is_punctuation(&self) -> bool {
self.is_graph() && !self.is_alnum()
self.is_graph() && !self.is_alphanumeric()
}
/// Checks if the character is a valid hex digit
@ -338,12 +337,12 @@ impl<'a> AsciiStr for &'a [Ascii] {
#[inline]
fn to_lower(&self) -> Vec<Ascii> {
self.iter().map(|a| a.to_lower()).collect()
self.iter().map(|a| a.to_lowercase()).collect()
}
#[inline]
fn to_upper(&self) -> Vec<Ascii> {
self.iter().map(|a| a.to_upper()).collect()
self.iter().map(|a| a.to_uppercase()).collect()
}
#[inline]
@ -410,13 +409,13 @@ impl<'a> AsciiExt<String> for &'a str {
#[inline]
fn to_ascii_upper(&self) -> String {
// Vec<u8>::to_ascii_upper() preserves the UTF-8 invariant.
unsafe { str::raw::from_utf8_owned(self.as_bytes().to_ascii_upper()) }
unsafe { string::raw::from_utf8(self.as_bytes().to_ascii_upper()) }
}
#[inline]
fn to_ascii_lower(&self) -> String {
// Vec<u8>::to_ascii_lower() preserves the UTF-8 invariant.
unsafe { str::raw::from_utf8_owned(self.as_bytes().to_ascii_lower()) }
unsafe { string::raw::from_utf8(self.as_bytes().to_ascii_lower()) }
}
#[inline]
@ -429,13 +428,13 @@ impl OwnedAsciiExt for String {
#[inline]
fn into_ascii_upper(self) -> String {
// Vec<u8>::into_ascii_upper() preserves the UTF-8 invariant.
unsafe { str::raw::from_utf8_owned(self.into_bytes().into_ascii_upper()) }
unsafe { string::raw::from_utf8(self.into_bytes().into_ascii_upper()) }
}
#[inline]
fn into_ascii_lower(self) -> String {
// Vec<u8>::into_ascii_lower() preserves the UTF-8 invariant.
unsafe { str::raw::from_utf8_owned(self.into_bytes().into_ascii_lower()) }
unsafe { string::raw::from_utf8(self.into_bytes().into_ascii_lower()) }
}
}

View file

@ -1288,7 +1288,7 @@ impl<K: Eq + Hash<S>, V: Clone, S, H: Hasher<S>> HashMap<K, V, H> {
/// let s: String = map.get_copy(&1);
/// ```
pub fn get_copy(&self, k: &K) -> V {
(*self.get(k)).clone()
self[*k].clone()
}
}
@ -1325,6 +1325,7 @@ impl<K: Eq + Hash<S>, V, S, H: Hasher<S> + Default> Default for HashMap<K, V, H>
impl<K: Eq + Hash<S>, V, S, H: Hasher<S>> Index<K, V> for HashMap<K, V, H> {
#[inline]
#[allow(deprecated)]
fn index<'a>(&'a self, index: &K) -> &'a V {
self.get(index)
}

View file

@ -846,8 +846,8 @@ impl<K: Clone, V: Clone> Clone for RawTable<K, V> {
(full.hash(), k.clone(), v.clone())
};
*new_buckets.raw.hash = h.inspect();
mem::overwrite(new_buckets.raw.key, k);
mem::overwrite(new_buckets.raw.val, v);
ptr::write(new_buckets.raw.key, k);
ptr::write(new_buckets.raw.val, v);
}
Empty(..) => {
*new_buckets.raw.hash = EMPTY_BUCKET;

View file

@ -281,6 +281,7 @@ pub mod dl {
#[cfg(target_os = "windows")]
pub mod dl {
use c_str::ToCStr;
use collections::MutableSeq;
use iter::Iterator;
use libc;
use os;
@ -295,8 +296,8 @@ pub mod dl {
// Windows expects Unicode data
let filename_cstr = filename.to_c_str();
let filename_str = str::from_utf8(filename_cstr.as_bytes_no_nul()).unwrap();
let filename_str: Vec<u16> = filename_str.utf16_units().collect();
let filename_str = filename_str.append_one(0);
let mut filename_str: Vec<u16> = filename_str.utf16_units().collect();
filename_str.push(0);
LoadLibraryW(filename_str.as_ptr() as *const libc::c_void) as *mut u8
}

View file

@ -38,9 +38,9 @@ impl Writer for Stdio {
}
pub fn on_fail(obj: &Any + Send, file: &'static str, line: uint) {
let msg = match obj.as_ref::<&'static str>() {
let msg = match obj.downcast_ref::<&'static str>() {
Some(s) => *s,
None => match obj.as_ref::<String>() {
None => match obj.downcast_ref::<String>() {
Some(s) => s.as_slice(),
None => "Box<Any>",
}

View file

@ -162,7 +162,7 @@ impl<W: Writer> BufferedWriter<W> {
fn flush_buf(&mut self) -> IoResult<()> {
if self.pos != 0 {
let ret = self.inner.get_mut_ref().write(self.buf.slice_to(self.pos));
let ret = self.inner.as_mut().unwrap().write(self.buf.slice_to(self.pos));
self.pos = 0;
ret
} else {
@ -174,7 +174,7 @@ impl<W: Writer> BufferedWriter<W> {
///
/// This type does not expose the ability to get a mutable reference to the
/// underlying reader because that could possibly corrupt the buffer.
pub fn get_ref<'a>(&'a self) -> &'a W { self.inner.get_ref() }
pub fn get_ref<'a>(&'a self) -> &'a W { self.inner.as_ref().unwrap() }
/// Unwraps this `BufferedWriter`, returning the underlying writer.
///
@ -193,7 +193,7 @@ impl<W: Writer> Writer for BufferedWriter<W> {
}
if buf.len() > self.buf.len() {
self.inner.get_mut_ref().write(buf)
self.inner.as_mut().unwrap().write(buf)
} else {
let dst = self.buf.slice_from_mut(self.pos);
slice::bytes::copy_memory(dst, buf);
@ -203,7 +203,7 @@ impl<W: Writer> Writer for BufferedWriter<W> {
}
fn flush(&mut self) -> IoResult<()> {
self.flush_buf().and_then(|()| self.inner.get_mut_ref().flush())
self.flush_buf().and_then(|()| self.inner.as_mut().unwrap().flush())
}
}
@ -273,7 +273,7 @@ impl<W> InternalBufferedWriter<W> {
impl<W: Reader> Reader for InternalBufferedWriter<W> {
fn read(&mut self, buf: &mut [u8]) -> IoResult<uint> {
self.get_mut().inner.get_mut_ref().read(buf)
self.get_mut().inner.as_mut().unwrap().read(buf)
}
}

View file

@ -15,7 +15,7 @@ use comm::{Sender, Receiver};
use io;
use option::{None, Option, Some};
use result::{Ok, Err};
use slice::{bytes, MutableSlice, ImmutableSlice};
use slice::{bytes, MutableSlice, ImmutableSlice, CloneableVector};
use str::StrSlice;
use super::{Reader, Writer, IoResult};
use vec::Vec;
@ -118,7 +118,7 @@ impl Clone for ChanWriter {
impl Writer for ChanWriter {
fn write(&mut self, buf: &[u8]) -> IoResult<()> {
self.tx.send_opt(Vec::from_slice(buf)).map_err(|_| {
self.tx.send_opt(buf.to_vec()).map_err(|_| {
io::IoError {
kind: io::BrokenPipe,
desc: "Pipe closed",

View file

@ -16,13 +16,14 @@
// FIXME: Iteration should probably be considered separately
use collections::{Collection, MutableSeq};
use iter::Iterator;
use option::{Option, Some, None};
use result::{Ok, Err};
use io;
use io::{IoError, IoResult, Reader};
use slice::{ImmutableSlice, Slice};
use io;
use iter::Iterator;
use num::Int;
use option::{Option, Some, None};
use ptr::RawPtr;
use result::{Ok, Err};
use slice::{ImmutableSlice, Slice};
/// An iterator that reads a single byte on each iteration,
/// until `.read_byte()` returns `EndOfFile`.
@ -76,16 +77,15 @@ impl<'r, R: Reader> Iterator<IoResult<u8>> for Bytes<'r, R> {
///
/// This function returns the value returned by the callback, for convenience.
pub fn u64_to_le_bytes<T>(n: u64, size: uint, f: |v: &[u8]| -> T) -> T {
use mem::{to_le16, to_le32, to_le64};
use mem::transmute;
// LLVM fails to properly optimize this when using shifts instead of the to_le* intrinsics
assert!(size <= 8u);
match size {
1u => f(&[n as u8]),
2u => f(unsafe { transmute::<_, [u8, ..2]>(to_le16(n as u16)) }),
4u => f(unsafe { transmute::<_, [u8, ..4]>(to_le32(n as u32)) }),
8u => f(unsafe { transmute::<_, [u8, ..8]>(to_le64(n)) }),
2u => f(unsafe { transmute::<_, [u8, ..2]>((n as u16).to_le()) }),
4u => f(unsafe { transmute::<_, [u8, ..4]>((n as u32).to_le()) }),
8u => f(unsafe { transmute::<_, [u8, ..8]>(n.to_le()) }),
_ => {
let mut bytes = vec!();
@ -116,16 +116,15 @@ pub fn u64_to_le_bytes<T>(n: u64, size: uint, f: |v: &[u8]| -> T) -> T {
///
/// This function returns the value returned by the callback, for convenience.
pub fn u64_to_be_bytes<T>(n: u64, size: uint, f: |v: &[u8]| -> T) -> T {
use mem::{to_be16, to_be32, to_be64};
use mem::transmute;
// LLVM fails to properly optimize this when using shifts instead of the to_be* intrinsics
assert!(size <= 8u);
match size {
1u => f(&[n as u8]),
2u => f(unsafe { transmute::<_, [u8, ..2]>(to_be16(n as u16)) }),
4u => f(unsafe { transmute::<_, [u8, ..4]>(to_be32(n as u32)) }),
8u => f(unsafe { transmute::<_, [u8, ..8]>(to_be64(n)) }),
2u => f(unsafe { transmute::<_, [u8, ..2]>((n as u16).to_be()) }),
4u => f(unsafe { transmute::<_, [u8, ..4]>((n as u32).to_be()) }),
8u => f(unsafe { transmute::<_, [u8, ..8]>(n.to_be()) }),
_ => {
let mut bytes = vec!();
let mut i = size;
@ -152,7 +151,6 @@ pub fn u64_to_be_bytes<T>(n: u64, size: uint, f: |v: &[u8]| -> T) -> T {
/// 32-bit value is parsed.
pub fn u64_from_be_bytes(data: &[u8], start: uint, size: uint) -> u64 {
use ptr::{copy_nonoverlapping_memory};
use mem::from_be64;
use slice::MutableSlice;
assert!(size <= 8u);
@ -166,7 +164,7 @@ pub fn u64_from_be_bytes(data: &[u8], start: uint, size: uint) -> u64 {
let ptr = data.as_ptr().offset(start as int);
let out = buf.as_mut_ptr();
copy_nonoverlapping_memory(out.offset((8 - size) as int), ptr, size);
from_be64(*(out as *const u64))
(*(out as *const u64)).to_be()
}
}

View file

@ -61,7 +61,7 @@ use io::{IoResult, IoError, FileStat, SeekStyle, Seek, Writer, Reader};
use io::{Read, Truncate, SeekCur, SeekSet, ReadWrite, SeekEnd, Append};
use io::UpdateIoError;
use io;
use iter::Iterator;
use iter::{Iterator, Extendable};
use kinds::Send;
use libc;
use option::{Some, None, Option};
@ -688,7 +688,7 @@ impl Iterator<Path> for Directories {
e, path.display()));
match result {
Ok(dirs) => { self.stack.push_all_move(dirs); }
Ok(dirs) => { self.stack.extend(dirs.into_iter()); }
Err(..) => {}
}
}

View file

@ -103,7 +103,12 @@ impl<'a> Parser<'a> {
// Commit only if parser read till EOF
fn read_till_eof<T>(&mut self, cb: |&mut Parser| -> Option<T>)
-> Option<T> {
self.read_atomically(|p| cb(p).filtered(|_| p.is_eof()))
self.read_atomically(|p| {
match cb(p) {
Some(x) => if p.is_eof() {Some(x)} else {None},
None => None,
}
})
}
// Return result of first successful parser
@ -152,7 +157,10 @@ impl<'a> Parser<'a> {
// Return char and advance iff next char is equal to requested
fn read_given_char(&mut self, c: char) -> Option<char> {
self.read_atomically(|p| {
p.read_char().filtered(|&next| next == c)
match p.read_char() {
Some(next) if next == c => Some(next),
_ => None,
}
})
}
@ -232,8 +240,8 @@ impl<'a> Parser<'a> {
fn ipv6_addr_from_head_tail(head: &[u16], tail: &[u16]) -> IpAddr {
assert!(head.len() + tail.len() <= 8);
let mut gs = [0u16, ..8];
gs.copy_from(head);
gs.slice_mut(8 - tail.len(), 8).copy_from(tail);
gs.clone_from_slice(head);
gs.slice_mut(8 - tail.len(), 8).clone_from_slice(tail);
Ipv6Addr(gs[0], gs[1], gs[2], gs[3], gs[4], gs[5], gs[6], gs[7])
}

View file

@ -79,7 +79,7 @@ impl TempDir {
/// Access the wrapped `std::path::Path` to the temporary directory.
pub fn path<'a>(&'a self) -> &'a Path {
self.path.get_ref()
self.path.as_ref().unwrap()
}
/// Close and remove the temporary directory

View file

@ -112,7 +112,6 @@
// Don't link to std. We are std.
#![no_std]
#![allow(deprecated)]
#![deny(missing_doc)]
#![reexport_test_harness_main = "test_main"]

View file

@ -46,15 +46,14 @@ use ptr::RawPtr;
use ptr;
use result::{Err, Ok, Result};
use slice::{Slice, ImmutableSlice, MutableSlice, ImmutablePartialEqSlice};
use slice::CloneableVector;
use str::{Str, StrSlice, StrAllocating};
use string::String;
use sync::atomic::{AtomicInt, INIT_ATOMIC_INT, SeqCst};
use vec::Vec;
#[cfg(unix)]
use c_str::ToCStr;
#[cfg(unix)]
use libc::c_char;
#[cfg(unix)] use c_str::ToCStr;
#[cfg(unix)] use libc::c_char;
/// Get the number of cores available
pub fn num_cpus() -> uint {
@ -260,8 +259,11 @@ pub fn env_as_bytes() -> Vec<(Vec<u8>,Vec<u8>)> {
let mut i = 0;
while *ch.offset(i) != 0 {
let p = &*ch.offset(i);
let len = ptr::position(p, |c| *c == 0);
raw::buf_as_slice(p, len, |s| {
let mut len = 0;
while *(p as *const _).offset(len) != 0 {
len += 1;
}
raw::buf_as_slice(p, len as uint, |s| {
result.push(String::from_utf16_lossy(s).into_bytes());
});
i += len as int + 1;
@ -276,17 +278,18 @@ pub fn env_as_bytes() -> Vec<(Vec<u8>,Vec<u8>)> {
extern {
fn rust_env_pairs() -> *const *const c_char;
}
let environ = rust_env_pairs();
let mut environ = rust_env_pairs();
if environ as uint == 0 {
fail!("os::env() failure getting env string from OS: {}",
os::last_os_error());
}
let mut result = Vec::new();
ptr::array_each(environ, |e| {
while *environ != 0 as *const _ {
let env_pair =
Vec::from_slice(CString::new(e, false).as_bytes_no_nul());
CString::new(*environ, false).as_bytes_no_nul().to_vec();
result.push(env_pair);
});
environ = environ.offset(1);
}
result
}
@ -294,9 +297,9 @@ pub fn env_as_bytes() -> Vec<(Vec<u8>,Vec<u8>)> {
let mut pairs = Vec::new();
for p in input.iter() {
let mut it = p.as_slice().splitn(1, |b| *b == b'=');
let key = Vec::from_slice(it.next().unwrap());
let key = it.next().unwrap().to_vec();
let default: &[u8] = &[];
let val = Vec::from_slice(it.next().unwrap_or(default));
let val = it.next().unwrap_or(default).to_vec();
pairs.push((key, val));
}
pairs
@ -350,8 +353,7 @@ pub fn getenv_as_bytes(n: &str) -> Option<Vec<u8>> {
if s.is_null() {
None
} else {
Some(Vec::from_slice(CString::new(s as *const i8,
false).as_bytes_no_nul()))
Some(CString::new(s as *const i8, false).as_bytes_no_nul().to_vec())
}
})
}
@ -364,8 +366,8 @@ pub fn getenv(n: &str) -> Option<String> {
unsafe {
with_env_lock(|| {
use os::windows::{fill_utf16_buf_and_decode};
let n: Vec<u16> = n.utf16_units().collect();
let n = n.append_one(0);
let mut n: Vec<u16> = n.utf16_units().collect();
n.push(0);
fill_utf16_buf_and_decode(|buf, sz| {
libc::GetEnvironmentVariableW(n.as_ptr(), buf, sz)
})
@ -411,10 +413,10 @@ pub fn setenv<T: BytesContainer>(n: &str, v: T) {
#[cfg(windows)]
fn _setenv(n: &str, v: &[u8]) {
let n: Vec<u16> = n.utf16_units().collect();
let n = n.append_one(0);
let v: Vec<u16> = ::str::from_utf8(v).unwrap().utf16_units().collect();
let v = v.append_one(0);
let mut n: Vec<u16> = n.utf16_units().collect();
n.push(0);
let mut v: Vec<u16> = ::str::from_utf8(v).unwrap().utf16_units().collect();
v.push(0);
unsafe {
with_env_lock(|| {
@ -441,8 +443,8 @@ pub fn unsetenv(n: &str) {
#[cfg(windows)]
fn _unsetenv(n: &str) {
let n: Vec<u16> = n.utf16_units().collect();
let n = n.append_one(0);
let mut n: Vec<u16> = n.utf16_units().collect();
n.push(0);
unsafe {
with_env_lock(|| {
libc::SetEnvironmentVariableW(n.as_ptr(), ptr::null());
@ -882,7 +884,11 @@ pub fn change_dir(p: &Path) -> bool {
#[cfg(windows)]
fn chdir(p: &Path) -> bool {
let p = match p.as_str() {
Some(s) => s.utf16_units().collect::<Vec<u16>>().append_one(0),
Some(s) => {
let mut p = s.utf16_units().collect::<Vec<u16>>();
p.push(0);
p
}
None => return false,
};
unsafe {
@ -1099,8 +1105,7 @@ unsafe fn load_argc_and_argv(argc: int,
use c_str::CString;
Vec::from_fn(argc as uint, |i| {
Vec::from_slice(CString::new(*argv.offset(i as int),
false).as_bytes_no_nul())
CString::new(*argv.offset(i as int), false).as_bytes_no_nul().to_vec()
})
}
@ -1169,7 +1174,7 @@ fn real_args_as_bytes() -> Vec<Vec<u8>> {
mem::transmute(objc_msgSend(tmp, utf8Sel));
let s = CString::new(utf_c_str, false);
if s.is_not_null() {
res.push(Vec::from_slice(s.as_bytes_no_nul()))
res.push(s.as_bytes_no_nul().to_vec())
}
}
}

View file

@ -76,7 +76,7 @@ use option::{Option, None, Some};
use str;
use str::{MaybeOwned, Str, StrSlice};
use string::String;
use slice::Slice;
use slice::{Slice, CloneableVector};
use slice::{ImmutablePartialEqSlice, ImmutableSlice};
use vec::Vec;
@ -480,7 +480,7 @@ pub trait GenericPath: Clone + GenericPathUnsafe {
let extlen = extension.container_as_bytes().len();
match (name.rposition_elem(&dot), extlen) {
(None, 0) | (Some(0), 0) => None,
(Some(idx), 0) => Some(Vec::from_slice(name.slice_to(idx))),
(Some(idx), 0) => Some(name.slice_to(idx).to_vec()),
(idx, extlen) => {
let idx = match idx {
None | Some(0) => name.len(),
@ -798,7 +798,7 @@ pub trait BytesContainer {
/// Consumes the receiver and converts it into Vec<u8>
#[inline]
fn container_into_owned_bytes(self) -> Vec<u8> {
Vec::from_slice(self.container_as_bytes())
self.container_as_bytes().to_vec()
}
/// Returns the receiver interpreted as a utf-8 string, if possible
#[inline]

View file

@ -264,7 +264,7 @@ impl GenericPath for Path {
#[inline]
fn is_absolute(&self) -> bool {
*self.repr.get(0) == SEP_BYTE
self.repr[0] == SEP_BYTE
}
fn is_ancestor_of(&self, other: &Path) -> bool {
@ -399,7 +399,7 @@ impl Path {
}
};
match val {
None => Vec::from_slice(v.as_slice()),
None => v.as_slice().to_vec(),
Some(val) => val
}
}
@ -409,7 +409,7 @@ impl Path {
/// /a/b/c and a/b/c yield the same set of components.
/// A path of "/" yields no components. A path of "." yields one component.
pub fn components<'a>(&'a self) -> Components<'a> {
let v = if *self.repr.get(0) == SEP_BYTE {
let v = if self.repr[0] == SEP_BYTE {
self.repr.slice_from(1)
} else { self.repr.as_slice() };
let mut ret = v.split(is_sep_byte);

View file

@ -264,10 +264,10 @@ impl GenericPathUnsafe for Path {
let repr = me.repr.as_slice();
match me.prefix {
Some(DiskPrefix) => {
repr.as_bytes()[0] == path.as_bytes()[0].to_ascii().to_upper().to_byte()
repr.as_bytes()[0] == path.as_bytes()[0].to_ascii().to_uppercase().to_byte()
}
Some(VerbatimDiskPrefix) => {
repr.as_bytes()[4] == path.as_bytes()[0].to_ascii().to_upper().to_byte()
repr.as_bytes()[4] == path.as_bytes()[0].to_ascii().to_uppercase().to_byte()
}
_ => false
}
@ -371,7 +371,7 @@ impl GenericPath for Path {
#[inline]
fn into_vec(self) -> Vec<u8> {
Vec::from_slice(self.repr.as_bytes())
self.repr.into_bytes()
}
#[inline]
@ -776,9 +776,9 @@ impl Path {
let mut s = String::from_str(s.slice_to(len));
unsafe {
let v = s.as_mut_vec();
*v.get_mut(0) = v.get(0)
*v.get_mut(0) = (*v)[0]
.to_ascii()
.to_upper()
.to_uppercase()
.to_byte();
}
if is_abs {
@ -794,7 +794,7 @@ impl Path {
let mut s = String::from_str(s.slice_to(len));
unsafe {
let v = s.as_mut_vec();
*v.get_mut(4) = v.get(4).to_ascii().to_upper().to_byte();
*v.get_mut(4) = (*v)[4].to_ascii().to_uppercase().to_byte();
}
Some(s)
}
@ -815,12 +815,14 @@ impl Path {
let mut s = String::with_capacity(n);
match prefix {
Some(DiskPrefix) => {
s.push_char(prefix_.as_bytes()[0].to_ascii().to_upper().to_char());
s.push_char(prefix_.as_bytes()[0].to_ascii()
.to_uppercase().to_char());
s.push_char(':');
}
Some(VerbatimDiskPrefix) => {
s.push_str(prefix_.slice_to(4));
s.push_char(prefix_.as_bytes()[4].to_ascii().to_upper().to_char());
s.push_char(prefix_.as_bytes()[4].to_ascii()
.to_uppercase().to_char());
s.push_str(prefix_.slice_from(5));
}
Some(UNCPrefix(a,b)) => {
@ -1619,7 +1621,7 @@ mod tests {
t!(s: "a\\b\\c", ["d".to_string(), "e".to_string()], "a\\b\\c\\d\\e");
t!(v: b"a\\b\\c", [b"d", b"e"], b"a\\b\\c\\d\\e");
t!(v: b"a\\b\\c", [b"d", b"\\e", b"f"], b"\\e\\f");
t!(v: b"a\\b\\c", [Vec::from_slice(b"d"), Vec::from_slice(b"e")],
t!(v: b"a\\b\\c", [b"d".to_vec(), b"e".to_vec()],
b"a\\b\\c\\d\\e");
}
@ -1759,7 +1761,7 @@ mod tests {
t!(s: "a\\b\\c", ["d", "\\e", "f"], "\\e\\f");
t!(s: "a\\b\\c", ["d".to_string(), "e".to_string()], "a\\b\\c\\d\\e");
t!(v: b"a\\b\\c", [b"d", b"e"], b"a\\b\\c\\d\\e");
t!(v: b"a\\b\\c", [Vec::from_slice(b"d"), Vec::from_slice(b"e")],
t!(v: b"a\\b\\c", [b"d".to_vec(), b"e".to_vec()],
b"a\\b\\c\\d\\e");
}

View file

@ -79,7 +79,7 @@ impl<T> TaskPool<T> {
/// Executes the function `f` on a task in the pool. The function
/// receives a reference to the local data returned by the `init_fn`.
pub fn execute(&mut self, f: proc(&T):Send) {
self.channels.get(self.next_index).send(Execute(f));
self.channels[self.next_index].send(Execute(f));
self.next_index += 1;
if self.next_index == self.channels.len() { self.next_index = 0; }
}

View file

@ -505,8 +505,8 @@ fn format(val: Param, op: FormatOp, flags: Flags) -> Result<Vec<u8> ,String> {
if flags.precision > s.len() {
let mut s_ = Vec::with_capacity(flags.precision);
let n = flags.precision - s.len();
s_.grow(n, &b'0');
s_.push_all_move(s);
s_.grow(n, b'0');
s_.extend(s.into_iter());
s = s_;
}
assert!(!s.is_empty(), "string conversion produced empty result");
@ -524,7 +524,7 @@ fn format(val: Param, op: FormatOp, flags: Flags) -> Result<Vec<u8> ,String> {
FormatHex => {
if flags.alternate {
let s_ = replace(&mut s, vec!(b'0', b'x'));
s.push_all_move(s_);
s.extend(s_.into_iter());
}
}
FormatHEX => {
@ -536,7 +536,7 @@ fn format(val: Param, op: FormatOp, flags: Flags) -> Result<Vec<u8> ,String> {
.collect();
if flags.alternate {
let s_ = replace(&mut s, vec!(b'0', b'X'));
s.push_all_move(s_);
s.extend(s_.into_iter());
}
}
FormatString => unreachable!()
@ -546,7 +546,7 @@ fn format(val: Param, op: FormatOp, flags: Flags) -> Result<Vec<u8> ,String> {
Words(s) => {
match op {
FormatString => {
let mut s = Vec::from_slice(s.as_bytes());
let mut s = s.as_bytes().to_vec();
if flags.precision > 0 && flags.precision < s.len() {
s.truncate(flags.precision);
}
@ -562,11 +562,11 @@ fn format(val: Param, op: FormatOp, flags: Flags) -> Result<Vec<u8> ,String> {
if flags.width > s.len() {
let n = flags.width - s.len();
if flags.left {
s.grow(n, &b' ');
s.grow(n, b' ');
} else {
let mut s_ = Vec::with_capacity(flags.width);
s_.grow(n, &b' ');
s_.push_all_move(s);
s_.grow(n, b' ');
s_.extend(s.into_iter());
s = s_;
}
}

View file

@ -290,9 +290,8 @@ pub fn parse(file: &mut io::Reader, longnames: bool)
match nulpos {
Some(len) => {
string_map.insert(name.to_string(),
Vec::from_slice(
string_table.slice(offset as uint,
offset as uint + len)))
string_table.slice(offset as uint,
offset as uint + len).to_vec())
},
None => {
return Err("invalid file: missing NUL in \
@ -314,10 +313,10 @@ pub fn parse(file: &mut io::Reader, longnames: bool)
/// Create a dummy TermInfo struct for msys terminals
pub fn msys_terminfo() -> Box<TermInfo> {
let mut strings = HashMap::new();
strings.insert("sgr0".to_string(), Vec::from_slice(b"\x1B[0m"));
strings.insert("bold".to_string(), Vec::from_slice(b"\x1B[1m"));
strings.insert("setaf".to_string(), Vec::from_slice(b"\x1B[3%p1%dm"));
strings.insert("setab".to_string(), Vec::from_slice(b"\x1B[4%p1%dm"));
strings.insert("sgr0".to_string(), b"\x1B[0m".to_vec());
strings.insert("bold".to_string(), b"\x1B[1m".to_vec());
strings.insert("setaf".to_string(), b"\x1B[3%p1%dm".to_vec());
strings.insert("setab".to_string(), b"\x1B[4%p1%dm".to_vec());
box TermInfo {
names: vec!("cygwin".to_string()), // msys is a fork of an older cygwin version
bools: HashMap::new(),

View file

@ -261,13 +261,13 @@ impl<'a, T: FloatMath + FromPrimitive> Stats<T> for &'a [T] {
}
fn percentile(self, pct: T) -> T {
let mut tmp = Vec::from_slice(self);
let mut tmp = self.to_vec();
local_sort(tmp.as_mut_slice());
percentile_of_sorted(tmp.as_slice(), pct)
}
fn quartiles(self) -> (T,T,T) {
let mut tmp = Vec::from_slice(self);
let mut tmp = self.to_vec();
local_sort(tmp.as_mut_slice());
let first = FromPrimitive::from_uint(25).unwrap();
let a = percentile_of_sorted(tmp.as_slice(), first);
@ -318,7 +318,7 @@ fn percentile_of_sorted<T: Float + FromPrimitive>(sorted_samples: &[T],
///
/// See: http://en.wikipedia.org/wiki/Winsorising
pub fn winsorize<T: Float + FromPrimitive>(samples: &mut [T], pct: T) {
let mut tmp = Vec::from_slice(samples);
let mut tmp = samples.to_vec();
local_sort(tmp.as_mut_slice());
let lo = percentile_of_sorted(tmp.as_slice(), pct);
let hundred: T = FromPrimitive::from_uint(100).unwrap();

View file

@ -12,7 +12,7 @@ fn main() {
let mut vector = vec![1u, 2];
for &x in vector.iter() {
let cap = vector.capacity();
vector.grow(cap, &0u); //~ ERROR cannot borrow
vector.grow(cap, 0u); //~ ERROR cannot borrow
*vector.get_mut(1u) = 5u; //~ ERROR cannot borrow
}
}