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
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
use std::any::{Any, TypeId};
/// Trait for types that return a reference to self as `dyn Any`.
///
/// Used to construct [`DowncastTrait`].
pub trait AsAny: 'static {
fn as_any(&self) -> &dyn Any;
}
impl<T: 'static> AsAny for T {
fn as_any(&self) -> &dyn Any {
self
}
}
/// A trait for trait objects that can be downcast to a reference
/// to the concrete type they wrap.
// NOTE: We don't auto-derive this trait for all types that satisfy
// the bound. Instead it needs to be derived manually for trait
// object types only.
pub trait DowncastTrait: AsAny {
/// Cast trait object reference to a reference to a concrete type `T`.
///
/// Panics if the inner value of `self` does not have type `T`.
#[inline]
fn downcast_checked<T: AsAny>(&self) -> &T {
assert_eq!(
self.as_any().type_id(),
TypeId::of::<T>(),
"downcast_checked from incorrect type to {}",
std::any::type_name::<T>()
);
unsafe { &*(self as *const _ as *const T) }
}
/// Cast trait object reference to a mutable reference to a concrete type `T`.
///
/// Panics if the inner value of `self` does not have type `T`.
#[inline]
fn downcast_mut_checked<T: AsAny>(&mut self) -> &mut T {
assert_eq!(
(self as &Self).as_any().type_id(),
TypeId::of::<T>(),
"downcast_mut_checked from incorrect type to {}",
std::any::type_name::<T>()
);
unsafe { &mut *(self as *mut _ as *mut T) }
}
/// Cast trait object reference to a reference to a concrete type `T`, eliding type checking.
///
/// # Safety
///
/// The inner value of `self` must be of type `T`.
#[inline]
unsafe fn downcast<T: AsAny>(&self) -> &T {
unsafe {
debug_assert_eq!(
self.as_any().type_id(),
TypeId::of::<T>(),
"downcast from incorrect type to {}",
std::any::type_name::<T>()
);
&*(self as *const _ as *const T)
}
}
/// Cast trait object reference to a reference to a mutable reference to concrete type `T`,
/// eliding type checking.
///
/// # Safety
///
/// The inner value of `self` must be of type `T`.
#[inline]
unsafe fn downcast_mut<T: AsAny>(&mut self) -> &mut T {
unsafe {
debug_assert_eq!(
(self as &Self).as_any().type_id(),
TypeId::of::<T>(),
"downcast_mut from incorrect type {} to {}",
std::any::type_name::<Self>(),
std::any::type_name::<T>()
);
&mut *(self as *mut _ as *mut T)
}
}
}