Skip to content

Commit f74250e

Browse files
committed
vec::with_capacity: do one alloc for non-managed
1 parent 137d1fb commit f74250e

File tree

1 file changed

+20
-1
lines changed

1 file changed

+20
-1
lines changed

src/libstd/vec.rs

+20-1
Original file line numberDiff line numberDiff line change
@@ -27,7 +27,7 @@ use option::{None, Option, Some};
2727
use ptr::to_unsafe_ptr;
2828
use ptr;
2929
use ptr::RawPtr;
30-
use rt::global_heap::realloc_raw;
30+
use rt::global_heap::{malloc_raw, realloc_raw};
3131
use sys;
3232
use sys::size_of;
3333
use uint;
@@ -101,12 +101,31 @@ pub fn to_owned<T:Copy>(t: &[T]) -> ~[T] {
101101
}
102102

103103
/// Creates a new vector with a capacity of `capacity`
104+
#[cfg(stage0)]
104105
pub fn with_capacity<T>(capacity: uint) -> ~[T] {
105106
let mut vec = ~[];
106107
vec.reserve(capacity);
107108
vec
108109
}
109110

111+
/// Creates a new vector with a capacity of `capacity`
112+
#[cfg(not(stage0))]
113+
pub fn with_capacity<T>(capacity: uint) -> ~[T] {
114+
unsafe {
115+
if contains_managed::<T>() {
116+
let mut vec = ~[];
117+
vec.reserve(capacity);
118+
vec
119+
} else {
120+
let alloc = capacity * sys::nonzero_size_of::<T>();
121+
let ptr = malloc_raw(alloc + size_of::<raw::VecRepr>()) as *mut raw::VecRepr;
122+
(*ptr).unboxed.alloc = alloc;
123+
(*ptr).unboxed.fill = 0;
124+
cast::transmute(ptr)
125+
}
126+
}
127+
}
128+
110129
/**
111130
* Builds a vector by calling a provided function with an argument
112131
* function that pushes an element to the back of a vector.

0 commit comments

Comments
 (0)