pr3.3
This commit is contained in:
@@ -0,0 +1,74 @@
|
||||
use crate::{ObjectHeader, ObjectKind};
|
||||
use prometeu_bytecode::HeapRef;
|
||||
|
||||
/// Internal stored object: header plus opaque payload bytes.
|
||||
#[derive(Debug, Clone)]
|
||||
pub struct StoredObject {
|
||||
pub header: ObjectHeader,
|
||||
pub payload: Vec<u8>,
|
||||
}
|
||||
|
||||
/// Simple vector-backed heap. No GC or compaction.
|
||||
#[derive(Debug, Default, Clone)]
|
||||
pub struct Heap {
|
||||
objects: Vec<StoredObject>,
|
||||
}
|
||||
|
||||
impl Heap {
|
||||
pub fn new() -> Self { Self { objects: Vec::new() } }
|
||||
|
||||
/// Allocate a new object with the given kind and raw payload bytes.
|
||||
/// Returns an opaque `HeapRef` handle.
|
||||
pub fn allocate_object(&mut self, kind: ObjectKind, payload: &[u8]) -> HeapRef {
|
||||
let header = ObjectHeader::new(kind, payload.len() as u32);
|
||||
let obj = StoredObject { header, payload: payload.to_vec() };
|
||||
let idx = self.objects.len();
|
||||
self.objects.push(obj);
|
||||
HeapRef(idx as u32)
|
||||
}
|
||||
|
||||
/// Returns true if this handle refers to an allocated object.
|
||||
pub fn is_valid(&self, r: HeapRef) -> bool {
|
||||
(r.0 as usize) < self.objects.len()
|
||||
}
|
||||
|
||||
/// Get immutable access to an object's header by handle.
|
||||
pub fn header(&self, r: HeapRef) -> Option<&ObjectHeader> {
|
||||
self.objects.get(r.0 as usize).map(|o| &o.header)
|
||||
}
|
||||
|
||||
/// Current number of allocated objects.
|
||||
pub fn len(&self) -> usize { self.objects.len() }
|
||||
pub fn is_empty(&self) -> bool { self.objects.is_empty() }
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
|
||||
#[test]
|
||||
fn basic_allocation_returns_valid_refs() {
|
||||
let mut heap = Heap::new();
|
||||
|
||||
let r1 = heap.allocate_object(ObjectKind::String, b"hello");
|
||||
let r2 = heap.allocate_object(ObjectKind::Bytes, &[1, 2, 3, 4]);
|
||||
let r3 = heap.allocate_object(ObjectKind::Array, &[]);
|
||||
|
||||
assert!(heap.is_valid(r1));
|
||||
assert!(heap.is_valid(r2));
|
||||
assert!(heap.is_valid(r3));
|
||||
assert_eq!(heap.len(), 3);
|
||||
|
||||
let h1 = heap.header(r1).unwrap();
|
||||
assert_eq!(h1.kind, ObjectKind::String);
|
||||
assert_eq!(h1.payload_len, 5);
|
||||
|
||||
let h2 = heap.header(r2).unwrap();
|
||||
assert_eq!(h2.kind, ObjectKind::Bytes);
|
||||
assert_eq!(h2.payload_len, 4);
|
||||
|
||||
let h3 = heap.header(r3).unwrap();
|
||||
assert_eq!(h3.kind, ObjectKind::Array);
|
||||
assert_eq!(h3.payload_len, 0);
|
||||
}
|
||||
}
|
||||
Reference in New Issue
Block a user