forked from nulang-org/nulang
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathheap.rs
More file actions
77 lines (66 loc) · 1.67 KB
/
Copy pathheap.rs
File metadata and controls
77 lines (66 loc) · 1.67 KB
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
74
75
76
77
//! Per-actor heap with bump allocator.
/// Actor-local heap allocator.
pub struct ActorHeap {
memory: Vec<u8>,
offset: usize,
size_class: usize,
}
impl ActorHeap {
pub fn new(size_class: usize) -> Self {
let capacity = match size_class {
0 => 256,
1 => 1024,
2 => 4096,
3 => 16 * 1024,
4 => 64 * 1024,
_ => 256 * 1024,
};
ActorHeap {
memory: vec![0; capacity],
offset: 0,
size_class,
}
}
/// Allocate `size` bytes, returning offset into memory.
pub fn alloc(&mut self, size: usize) -> Option<usize> {
let aligned = (size + 7) & !7; // 8-byte alignment
if self.offset + aligned > self.memory.len() {
return None; // Out of memory
}
let addr = self.offset;
self.offset += aligned;
Some(addr)
}
pub fn reset(&mut self) {
self.offset = 0;
}
pub fn as_slice(&self) -> &[u8] {
&self.memory[..self.offset]
}
pub fn as_mut_slice(&mut self) -> &mut [u8] {
&mut self.memory[..self.offset]
}
pub fn capacity(&self) -> usize {
self.memory.len()
}
pub fn used(&self) -> usize {
self.offset
}
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn test_heap_alloc() {
let mut heap = ActorHeap::new(0);
let a1 = heap.alloc(16).unwrap();
let a2 = heap.alloc(8).unwrap();
assert!(a2 > a1);
assert_eq!(heap.used(), 24);
}
#[test]
fn test_heap_oom() {
let mut heap = ActorHeap::new(0);
assert!(heap.alloc(300).is_none());
}
}