1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
use std::any::type_name;
use std::convert::TryFrom;
pub trait Cast {
#[inline]
fn cast<T>(self) -> T
where
T: TryFrom<Self>,
Self: Sized + std::fmt::Display + Copy,
{
T::try_from(self).unwrap_or_else(|_| {
panic!(
"Failed to convert from {}: {} to {}",
type_name::<Self>(),
self,
type_name::<T>(),
)
})
}
}
impl<U> Cast for U {}
#[inline]
pub const fn cast_to_ptr<T: ?Sized, U>(val: &T) -> *const U {
let ptr: *const _ = val;
ptr.cast()
}
#[inline]
pub fn cast_to_mut_ptr<T: ?Sized, U>(val: &mut T) -> *mut U {
let ptr: *mut _ = val;
ptr.cast()
}