Skip to content

Commit ad21976

Browse files
committed
core: Add vec::capacity
1 parent 5e42c5c commit ad21976

File tree

1 file changed

+19
-0
lines changed

1 file changed

+19
-0
lines changed

src/libcore/vec.rs

Lines changed: 19 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -9,6 +9,7 @@ export is_not_empty;
99
export same_length;
1010
export reserve;
1111
export reserve_at_least;
12+
export capacity;
1213
export len;
1314
export from_fn;
1415
export from_elem;
@@ -134,6 +135,14 @@ fn reserve_at_least<T>(&v: [const T], n: uint) {
134135
reserve(v, uint::next_power_of_two(n));
135136
}
136137

138+
#[doc = "
139+
Returns the number of elements the vector can hold without reallocating
140+
"]
141+
fn capacity<T>(&&v: [const T]) -> uint unsafe {
142+
let repr: **unsafe::vec_repr = ::unsafe::reinterpret_cast(addr_of(v));
143+
(**repr).alloc / sys::size_of::<T>()
144+
}
145+
137146
#[doc = "Returns the length of a vector"]
138147
#[inline(always)]
139148
pure fn len<T>(&&v: [const T]) -> uint unsafe {
@@ -1801,6 +1810,16 @@ mod tests {
18011810
unshift(x, 0);
18021811
assert x == [0, 1, 2, 3];
18031812
}
1813+
1814+
#[test]
1815+
fn test_capacity() {
1816+
let mut v = [0u64];
1817+
reserve(v, 10u);
1818+
assert capacity(v) == 10u;
1819+
let mut v = [0u32];
1820+
reserve(v, 10u);
1821+
assert capacity(v) == 10u;
1822+
}
18041823
}
18051824

18061825
// Local Variables:

0 commit comments

Comments
 (0)