2012-03-20 21:06:04 -05:00
|
|
|
// Dynamic arenas.
|
|
|
|
|
|
|
|
export arena, arena_with_size;
|
|
|
|
|
|
|
|
import list;
|
|
|
|
|
|
|
|
type chunk = {data: [u8], mut fill: uint};
|
|
|
|
type arena = {mut chunks: list::list<@chunk>};
|
|
|
|
|
|
|
|
fn chunk(size: uint) -> @chunk {
|
2012-03-28 23:04:13 -05:00
|
|
|
let mut v = [];
|
|
|
|
vec::reserve(v, size);
|
|
|
|
@{ data: v, mut fill: 0u }
|
2012-03-20 21:06:04 -05:00
|
|
|
}
|
|
|
|
|
|
|
|
fn arena_with_size(initial_size: uint) -> arena {
|
|
|
|
ret {mut chunks: list::cons(chunk(initial_size), @list::nil)};
|
|
|
|
}
|
|
|
|
|
|
|
|
fn arena() -> arena {
|
|
|
|
arena_with_size(32u)
|
|
|
|
}
|
|
|
|
|
|
|
|
impl arena for arena {
|
2012-03-21 07:45:52 -05:00
|
|
|
fn alloc(n_bytes: uint, align: uint) -> *() {
|
|
|
|
let alignm1 = align - 1u;
|
2012-03-20 21:06:04 -05:00
|
|
|
let mut head = list::head(self.chunks);
|
2012-03-21 07:45:52 -05:00
|
|
|
|
|
|
|
let mut start = head.fill;
|
|
|
|
start = (start + alignm1) & !alignm1;
|
|
|
|
let mut end = start + n_bytes;
|
|
|
|
|
|
|
|
if end > vec::len(head.data) {
|
2012-03-20 21:06:04 -05:00
|
|
|
// Allocate a new chunk.
|
|
|
|
let new_min_chunk_size = uint::max(n_bytes, vec::len(head.data));
|
|
|
|
head = chunk(uint::next_power_of_two(new_min_chunk_size));
|
|
|
|
self.chunks = list::cons(head, @self.chunks);
|
2012-03-21 07:45:52 -05:00
|
|
|
start = 0u;
|
|
|
|
end = n_bytes;
|
2012-03-20 21:06:04 -05:00
|
|
|
}
|
|
|
|
|
2012-03-28 22:26:28 -05:00
|
|
|
unsafe {
|
|
|
|
let p = ptr::offset(vec::unsafe::to_ptr(head.data), start);
|
|
|
|
head.fill = end;
|
|
|
|
ret unsafe::reinterpret_cast(p);
|
|
|
|
}
|
2012-03-20 21:06:04 -05:00
|
|
|
}
|
|
|
|
}
|
|
|
|
|