Essentially, I need to store a NetworkVariableInner<Box<dyn NetworkTransferable + 'static>>
inside a hashmap, and want to give the user a pointer to it inside a wrapper called NetworkVariable<T>
:
#[derive(Clone)]
pub struct NetworkVariableInner<T: NetworkTransferable + 'static> {
inner: Accessor<T>
}
pub struct NetworkVariable<T: NetworkTransferable + 'static> {
ptr: NetworkVariableInner<Box<dyn NetworkTransferable + 'static>>,
// we store a T here, that way, when we deref, we can map Box<dyn NetworkTransferable> to Box<T>
_pd: PhantomData<T>
}
impl<T: NetworkTransferable + 'static> NetworkVariable<T> {
pub fn new(ptr: NetworkVariableInner<Box<dyn NetworkTransferable + 'static>>) -> Self {
Self { ptr, _pd: Default::default() }
}
}
impl<T: NetworkTransferable + 'static> Deref for NetworkVariable<T> {
type Target = Accessor<T>;
fn deref(&self) -> &Self::Target {
let ref reinterpreted = unsafe { std::mem::transmute_copy::<_, NetworkVariableInner<Box<T>>>(&self.ptr) };
&reinterpreted.inner
}
}
Accessor<Box<T>>
is the inner element I'm trying to deref to
Since the type is stored inside PhantomData
, the size/alignment should be preserved. The data type won't change over time, so I figured that reinterpreting the type-variable from Box<dyn NetworkTransferable + 'static>
to Box<T>
should be okay. I haven't used transmute_copy
before, so I want to make sure I'm doing it correctly, and if possible, if there is a safer way of doing what I'm trying to do