use StackAllocator;
pub struct DoubleBufferedAllocator {
buffers: [StackAllocator; 2],
current: bool,
}
impl DoubleBufferedAllocator {
pub fn with_capacity(capacity: usize) -> Self {
DoubleBufferedAllocator {
buffers: [StackAllocator::with_capacity(capacity), StackAllocator::with_capacity(capacity)],
current: false,
}
}
pub fn active_buffer(&self) -> &StackAllocator {
&self.buffers[self.current as usize]
}
pub fn inactive_buffer(&self) -> &StackAllocator {
&self.buffers[!self.current as usize]
}
pub fn reset_current(&self) {
self.buffers[self.current as usize].reset();
}
pub fn swap_buffers(&mut self) {
self.current = !self.current;
}
pub fn alloc<T>(&self, value: T) -> &mut T {
self.buffers[self.current as usize].alloc(value)
}
}
#[cfg(test)]
mod double_buffer_allocator_test {
use super::*;
#[test]
fn new() {
let alloc = DoubleBufferedAllocator::with_capacity(100);
assert_eq!(alloc.active_buffer().stack().cap(), 100);
assert_eq!(alloc.inactive_buffer().stack().cap(), 100);
}
#[test]
fn reset() {
let alloc = DoubleBufferedAllocator::with_capacity(100);
let active_buffer_top_stack = alloc.active_buffer().marker();
let inactive_buffer_top_stack = alloc.inactive_buffer().marker();
assert_eq!(alloc.active_buffer().stack().ptr(), active_buffer_top_stack);
assert_eq!(alloc.inactive_buffer().stack().ptr(), inactive_buffer_top_stack);
let my_i32 = alloc.alloc(25);
let active_buffer_top_stack = alloc.active_buffer().marker();
let inactive_buffer_top_stack = alloc.inactive_buffer().marker();
assert_ne!(alloc.active_buffer().stack().ptr(), active_buffer_top_stack);
assert_eq!(alloc.inactive_buffer().stack().ptr(), inactive_buffer_top_stack);
alloc.reset_current();
let active_buffer_top_stack = alloc.active_buffer().marker();
let inactive_buffer_top_stack = alloc.inactive_buffer().marker();
assert_eq!(alloc.active_buffer().stack().ptr(), active_buffer_top_stack);
assert_eq!(alloc.inactive_buffer().stack().ptr(), inactive_buffer_top_stack);
}
#[test]
fn swap() {
let mut alloc = DoubleBufferedAllocator::with_capacity(100);
let first_buffer_top_stack = alloc.buffers[0].marker();
let second_buffer_top_stack = alloc.buffers[1].marker();
assert_eq!(alloc.buffers[0].stack().ptr(), first_buffer_top_stack);
assert_eq!(alloc.buffers[1].stack().ptr(), second_buffer_top_stack);
alloc.swap_buffers();
let my_i32 = alloc.alloc(25);
let first_buffer_top_stack = alloc.buffers[0].marker();
let second_buffer_top_stack = alloc.buffers[1].marker();
assert_eq!(alloc.buffers[0].stack().ptr(), first_buffer_top_stack);
assert_ne!(alloc.buffers[1].stack().ptr(), second_buffer_top_stack);
}
}