use std::collections::HashMap;
use std::ptr::NonNull;
#[derive(Debug)]
pub(crate) struct InfostructKeeper<T, R> {
map: HashMap<NonNull<R>, Box<T>>,
}
impl<T: AsRef<R>, R> Default for InfostructKeeper<T, R> {
fn default() -> Self {
InfostructKeeper {
map: Default::default(),
}
}
}
impl<T: AsRef<R>, R> InfostructKeeper<T, R> {
pub fn keep(&mut self, owned_struct: T) -> NonNull<R> {
let boxed = Box::new(owned_struct);
let ref_to_infostruct: &R = (*boxed).as_ref();
let stable_ptr_to_infostruct: NonNull<R> = ref_to_infostruct.into();
self.map.insert(stable_ptr_to_infostruct, boxed);
stable_ptr_to_infostruct
}
pub fn release(&mut self, handle: NonNull<R>) -> Option<T> {
self.map.remove(&handle).map(|boxed| *boxed)
}
}