vec::with_capacity: do one alloc for non-managed

This commit is contained in:
Daniel Micay 2013-07-09 21:59:30 -04:00
parent 137d1fb210
commit f74250e3a9

View file

@ -27,7 +27,7 @@ use option::{None, Option, Some};
use ptr::to_unsafe_ptr; use ptr::to_unsafe_ptr;
use ptr; use ptr;
use ptr::RawPtr; use ptr::RawPtr;
use rt::global_heap::realloc_raw; use rt::global_heap::{malloc_raw, realloc_raw};
use sys; use sys;
use sys::size_of; use sys::size_of;
use uint; use uint;
@ -101,12 +101,31 @@ pub fn to_owned<T:Copy>(t: &[T]) -> ~[T] {
} }
/// Creates a new vector with a capacity of `capacity` /// Creates a new vector with a capacity of `capacity`
#[cfg(stage0)]
pub fn with_capacity<T>(capacity: uint) -> ~[T] { pub fn with_capacity<T>(capacity: uint) -> ~[T] {
let mut vec = ~[]; let mut vec = ~[];
vec.reserve(capacity); vec.reserve(capacity);
vec vec
} }
/// Creates a new vector with a capacity of `capacity`
#[cfg(not(stage0))]
pub fn with_capacity<T>(capacity: uint) -> ~[T] {
unsafe {
if contains_managed::<T>() {
let mut vec = ~[];
vec.reserve(capacity);
vec
} else {
let alloc = capacity * sys::nonzero_size_of::<T>();
let ptr = malloc_raw(alloc + size_of::<raw::VecRepr>()) as *mut raw::VecRepr;
(*ptr).unboxed.alloc = alloc;
(*ptr).unboxed.fill = 0;
cast::transmute(ptr)
}
}
}
/** /**
* Builds a vector by calling a provided function with an argument * Builds a vector by calling a provided function with an argument
* function that pushes an element to the back of a vector. * function that pushes an element to the back of a vector.