vim_rs/types/convert.rs
1use std::any;
2/// Casts one trait to another. For example:
3///
4/// Example: `let virtual_device = <dyn VirtualDeviceTrait>::from_ref(data_object_trait_ref)?`;
5pub trait CastFrom<From: ?Sized> {
6 /// Casts a reference to a trait object. If the cast fails, [`std::option::Option::None`] is
7 /// returned.
8 fn from_ref<'a>(from: &'a From) -> Option<&'a Self>;
9 /// Casts a boxed trait object to another trait object. If the cast fails, the original boxed
10 /// trait object is returned in [`std::result::Result::Err`].
11 fn from_box(from: Box<From>) -> Result<Box<Self>, Box<dyn any::Any>>;
12}
13
14/// Casts one trait to another. For example:
15///
16/// Example: `let virtual_device: &dyn VirtualDeviceTrait = data_object_trait_ref.into_ref()?`;
17pub trait CastInto<To: ?Sized> {
18 /// Casts a reference to a trait object. If the cast fails, [`std::option::Option::None`] is
19 /// returned.
20 fn into_ref<'a>(&'a self) -> Option<&'a To>;
21 /// Casts a boxed trait object to another trait object. If the cast fails, the original boxed
22 /// trait object is returned in [`std::result::Result::Err`].
23 fn into_box(self: Box<Self>) -> Result<Box<To>, Box<dyn any::Any>>;
24}
25
26impl<To: CastFrom<T> + ?Sized, T: ?Sized + 'static> CastInto<To> for T {
27 fn into_ref<'a>(&'a self) -> Option<&'a To> {
28 CastFrom::from_ref(self)
29 }
30
31 fn into_box(self: Box<Self>) -> Result<Box<To>, Box<dyn any::Any + 'static>> {
32 CastFrom::from_box(self)
33 }
34}
35