-
Notifications
You must be signed in to change notification settings - Fork 0
/
arena.rs
73 lines (63 loc) · 1.92 KB
/
arena.rs
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
use std::alloc;
use std::cell;
use crate::stats;
const DEFAULT_CAPACITY: usize = 512 * 1024 * 1024;
const DEFAULT_ALIGNMENT: usize = 16;
#[derive(Debug)]
pub struct Arena {
buf: *mut u8,
cap: usize,
len: cell::Cell<usize>,
align: usize,
}
impl Arena {
pub fn new(capacity: usize, align: usize) -> Self {
let cap = capacity;
let len = cell::Cell::new(0);
let lay = alloc::Layout::from_size_align(capacity, align).unwrap();
unsafe {
let buf = alloc::alloc(lay);
Arena { cap, len, buf, align }
}
}
pub fn alloc<T: Copy>(&self, item: T) -> &T {
let size = self.align(std::mem::size_of::<T>());
let len = self.len.get();
if len + size >= self.cap { panic!("[INTERNAL ERROR]: arena ran out of memory"); }
self.len.set(len + size);
stats::ARENA_MEMORY.inc(size);
unsafe {
let ptr = self.buf.add(len) as *mut T;
ptr.write(item);
&*ptr
}
}
pub unsafe fn alloc_slice_mut<T: Copy>(&self, count: usize) -> &mut [T] {
let size = self.align(std::mem::size_of::<T>()) * count;
let len = self.len.get();
if len + size >= self.cap { panic!("[INTERNAL ERROR]: arena ran out of memory"); }
self.len.set(len + size);
stats::ARENA_MEMORY.inc(size);
let ptr = self.buf.add(len) as *mut T;
let len = count;
std::slice::from_raw_parts_mut(ptr, len)
}
fn align(&self, addr: usize) -> usize {
(addr + self.align - 1) & !(self.align - 1)
}
fn layout(&self) -> alloc::Layout {
alloc::Layout::from_size_align(self.cap, self.align).unwrap()
}
}
impl Default for Arena {
fn default() -> Self {
Arena::new(DEFAULT_CAPACITY, DEFAULT_ALIGNMENT)
}
}
impl Drop for Arena {
fn drop(&mut self) {
unsafe {
alloc::dealloc(self.buf, self.layout());
}
}
}