use std::any::Any; use anyhow::Result; pub struct BoxAny(Box); impl BoxAny { pub fn new(value: T) -> Self where T: Send + Sync + 'static, { Self(Box::new(value)) } pub fn unbox_or_default(self) -> T where T: Default + 'static, { match self.0.downcast::() { Ok(value) => *value, Err(_) => T::default(), } } pub fn unbox_or_error(self) -> Result where T: 'static, { match self.0.downcast::() { Ok(value) => Ok(*value), Err(e) => Err(anyhow::anyhow!( "downcast error to {} failed: {:?}", std::any::type_name::(), e )), } } pub fn unbox_or_none(self) -> Option where T: 'static, { match self.0.downcast::() { Ok(value) => Some(*value), Err(_) => None, } } #[allow(dead_code)] pub fn downcast_ref(&self) -> Option<&T> { self.0.downcast_ref() } }