use bumpalo::Bump;
use std::ops::Deref;
#[derive(Default)]
pub struct Allocator {
bump: Bump,
}
impl Allocator {
#[inline]
pub fn new() -> Self {
Self { bump: Bump::new() }
}
#[inline]
pub fn with_capacity(capacity: usize) -> Self {
Self {
bump: Bump::with_capacity(capacity),
}
}
#[inline]
pub fn alloc_str(&self, s: &str) -> &str {
self.bump.alloc_str(s)
}
#[inline]
pub fn as_bump(&self) -> &Bump {
&self.bump
}
#[inline]
pub fn reset(&mut self) {
self.bump.reset();
}
#[inline]
pub fn allocated_bytes(&self) -> usize {
self.bump.allocated_bytes()
}
}
impl Deref for Allocator {
type Target = Bump;
#[inline]
fn deref(&self) -> &Self::Target {
&self.bump
}
}
impl AsRef<Bump> for Allocator {
#[inline]
fn as_ref(&self) -> &Bump {
&self.bump
}
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn test_allocator_new() {
let allocator = Allocator::new();
assert_eq!(allocator.allocated_bytes(), 0);
}
#[test]
fn test_allocator_default() {
let allocator = Allocator::default();
assert_eq!(allocator.allocated_bytes(), 0);
}
#[test]
fn test_alloc_str() {
let allocator = Allocator::new();
let s = allocator.alloc_str("hello world");
assert_eq!(s, "hello world");
}
#[test]
fn test_reset() {
let mut allocator = Allocator::new();
let _ = allocator.alloc_str("hello");
assert!(allocator.allocated_bytes() > 0);
allocator.reset();
}
}