I'm working on an interface that can accept user defined types and I want it to work for both Send + Sync and non-Send+Sync types. And for that I'm using and Arc.
The problem I have is that Arc::downcast Is implemented only for Any + Send + Sync + 'static
and I need it for Any + 'static
. Here's what I did:
pub fn downcast_arc<T>(arc: Arc<dyn Any>) -> Result<Arc<T>, Arc<dyn Any>>
where
T: Any + 'static,
{
if (*arc).is::<T>() {
let ptr = Arc::into_raw(arc).cast::<T>();
Ok(unsafe { Arc::from_raw(ptr) })
} else {
Err(arc)
}
}
It works, but is this safe?