I've been backed into a corner where I need to transmute a boxed trait object to the correct trait type. I know for certain that in this match arm the boxed item is this trait object, I'm just transmuting it because the type can't be written in the signature, yet transmute fails:
error[E0512]: transmute called with types of different sizes
--> src/datatype/mod.rs:168:32
|
168 | let cast_val = std::mem::transmute::<Box<T>, Box<interface::PartitioningController>>(val);
| ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
|
= note: source type: std::boxed::Box<T> (pointer to T)
= note: target type: std::boxed::Box<datatype::interface::PartitioningController + 'static> (128 bits)
Fake method with extraneous types removed:
fn from_box<T: ?Sized>(name: &str, val: Box<T>) -> Option<Self> {
match name {
"Partitioning" => unsafe {
let cast_val = std::mem::transmute::<Box<T>, Box<interface::PartitioningController>>(val);
Some(DefaultInterfaceControllers::Partitioning(cast_val))
},
_ => None,
}
}
I understand boxes can be one of two sizes (depending on whether they point to a struct or a trait object), but have no idea how to express this in the T type constraint. This fn will only ever be taking boxed trait objects.
And, yes, I know this is major code stench, but when dealing with user/macro defined types/traits this is sometimes the only way out. I'm asking how to remove the safety on a footgun.