use bumpalo::Bump;
pub struct Zone {
bump: Bump,
}
impl Zone {
pub fn new() -> Self {
Self { bump: Bump::new() }
}
pub fn alloc<T>(&self, value: T) -> &T {
self.bump.alloc(value)
}
}
impl Default for Zone {
fn default() -> Self {
Self::new()
}
}
#[cfg(test)]
mod tests {
use super::Zone;
#[test]
fn test_alloc_single_value() {
let zone = Zone::new();
let r: &u32 = zone.alloc(99_u32);
assert_eq!(*r, 99);
}
#[test]
fn test_alloc_many_objects() {
let zone = Zone::new();
let count = 10_000_usize;
let refs: Vec<&usize> = (0..count).map(|i| zone.alloc(i)).collect();
for (i, r) in refs.iter().enumerate() {
assert_eq!(**r, i, "value at index {i} was corrupted");
}
}
#[test]
fn test_alloc_struct() {
#[derive(Debug, PartialEq)]
struct Point {
x: f64,
y: f64,
}
let zone = Zone::new();
let p = zone.alloc(Point { x: 1.5, y: -2.5 });
assert_eq!(p.x, 1.5);
assert_eq!(p.y, -2.5);
}
#[test]
fn test_alloc_string_slices() {
let zone = Zone::new();
let a = zone.alloc("hello");
let b = zone.alloc("world");
assert_eq!(*a, "hello");
assert_eq!(*b, "world");
}
#[test]
fn test_default_is_new() {
let zone: Zone = Zone::default();
let v = zone.alloc(42_i32);
assert_eq!(*v, 42);
}
#[test]
fn test_alloc_references_remain_valid() {
let zone = Zone::new();
let r1 = zone.alloc(1_u64);
let r2 = zone.alloc(2_u64);
let r3 = zone.alloc(3_u64);
assert_eq!(*r1, 1);
assert_eq!(*r2, 2);
assert_eq!(*r3, 3);
}
}