#[derive(Debug, Default)]
pub struct BoxPool {
inner: Vec<Box<dyn 'static + std::any::Any>>,
}
impl BoxPool {
pub fn new() -> Self {
Self { inner: Vec::new() }
}
#[must_use]
pub fn push<T: 'static>(&mut self, b: Box<T>) -> *const T {
let raw = b.as_ref() as *const T;
self.inner.push(b);
raw
}
#[must_use]
pub fn push_vec<T: 'static>(&mut self, v: Vec<T>) -> (usize, *const T) {
let len = v.len();
let raw = v.as_ptr();
let boxed_v = Box::new(v);
self.inner.push(boxed_v);
(len, raw)
}
}
pub trait GetRawWithBoxPool<T> {
fn get_raw_with_pool(&self, pool: &mut BoxPool) -> T;
}
pub trait GetRaw<T> {
fn get_raw(&self) -> T;
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn test_box_pool() {
let mut pool = BoxPool::new();
let b = Box::new(42);
let raw = pool.push(b);
assert_eq!(unsafe { *raw }, 42);
let v = vec![1, 2, 3];
let (len, raw_v) = pool.push_vec(v);
assert_eq!(len, 3);
assert_eq!(unsafe { *raw_v }, 1);
}
}