Files
multiverse/xcom-ultra/xcu-memory-pool/src/allocator.rs
T

35 lines
1.1 KiB
Rust

//! [TSM.ID].[11031972] — Platform X Ecosystem
//! Bump allocator for temporary allocations
use crate::{PoolError, Result};
pub struct BumpAllocator {
buffer: Vec<u8>,
offset: usize,
high_water: usize,
}
impl BumpAllocator {
pub fn new(capacity: usize) -> Result<Self> {
if capacity == 0 { return Err(PoolError::InvalidBlockSize); }
Ok(Self { buffer: vec![0u8; capacity], offset: 0, high_water: 0 })
}
pub fn alloc(&mut self, size: usize, align: usize) -> Result<&mut [u8]> {
let aligned_offset = (self.offset + align - 1) & !(align - 1);
if aligned_offset + size > self.buffer.len() { return Err(PoolError::OutOfMemory); }
self.offset = aligned_offset + size;
if self.offset > self.high_water { self.high_water = self.offset; }
Ok(&mut self.buffer[aligned_offset..self.offset])
}
pub fn reset(&mut self) {
self.buffer.fill(0);
self.offset = 0;
}
pub fn used(&self) -> usize { self.offset }
pub fn remaining(&self) -> usize { self.buffer.len() - self.offset }
pub fn high_water_mark(&self) -> usize { self.high_water }
}