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
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
#![feature(allocator_api)]
#![feature(ptr_metadata)]

#![no_std]

#[doc=include_str!("../README.md")]
type _DocTestReadme = ();

extern crate alloc;

use alloc::boxed::Box;
use alloc::rc::Rc;
use alloc::sync::Arc;
use arraybox::{ArrayBox, BufFor};
use downcast_rs::{Downcast, impl_downcast};
use core::alloc::Allocator;
use core::any::TypeId;
use core::ops::Deref;
use core::ptr::{self, DynMetadata, Pointee};

#[doc(hidden)]
pub use core::any::TypeId as core_any_TypeId;
#[doc(hidden)]
pub use core::option::Option as core_option_Option;

pub type BoxedInterfaceMetadata =
    ArrayBox<'static, dyn IsInterfaceMetadata, BufFor<InterfaceMetadata<dyn IsInterfaceMetadata>>>
;

pub trait IsInterfaceMetadata: Downcast { }

impl_downcast!(IsInterfaceMetadata);

pub struct InterfaceMetadata<DynInterface: ?Sized>(pub DynMetadata<DynInterface>);

impl<DynInterface: ?Sized + 'static> IsInterfaceMetadata for InterfaceMetadata<DynInterface> { }

pub unsafe trait SupportsInterfaces {
    fn get_interface_metadata(&self, dyn_interface_id: TypeId) -> Option<BoxedInterfaceMetadata>;
}

pub fn dyn_cast_ref<T: SupportsInterfaces + ?Sized, DynInterface: ?Sized + 'static>(
    x: &T
) -> Option<&DynInterface> where DynInterface: Pointee<Metadata=DynMetadata<DynInterface>> {
    unsafe { dyn_cast_raw(x, |x| (x as *const T, ()), |x, ()| &*x) }
}

pub fn dyn_cast_mut<T: SupportsInterfaces + ?Sized, DynInterface: ?Sized + 'static>(
    x: &mut T
) -> Option<&mut DynInterface> where DynInterface: Pointee<Metadata=DynMetadata<DynInterface>> {
    unsafe { dyn_cast_raw_mut(x, |x| (x as *mut T, ()), |x, ()| &mut *x) }
}

pub fn dyn_cast_box<T: SupportsInterfaces + ?Sized, DynInterface: ?Sized + 'static, A: Allocator>(
    x: Box<T, A>
) -> Option<Box<DynInterface, A>> where DynInterface: Pointee<Metadata=DynMetadata<DynInterface>> {
    unsafe { dyn_cast_raw_mut(x, Box::into_raw_with_allocator, Box::from_raw_in) }
}

pub fn dyn_cast_rc<T: SupportsInterfaces + ?Sized, DynInterface: ?Sized + 'static>(
    x: Rc<T>
) -> Option<Rc<DynInterface>> where
    DynInterface: Pointee<Metadata=DynMetadata<DynInterface>>,
    T: Pointee<Metadata=DynMetadata<T>>
{
    unsafe { dyn_cast_raw(x, |x| (Rc::into_raw(x), ()), |x, ()| Rc::from_raw(x)) }
}

pub fn dyn_cast_arc<T: SupportsInterfaces + ?Sized, DynInterface: ?Sized + 'static>(
    x: Arc<T>
) -> Option<Arc<DynInterface>> where
    DynInterface: Pointee<Metadata=DynMetadata<DynInterface>>,
    T: Pointee<Metadata=DynMetadata<T>>
{
    unsafe { dyn_cast_raw(x, |x| (Arc::into_raw(x), ()), |x, ()| Arc::from_raw(x)) }
}

pub unsafe fn dyn_cast_raw_mut<
    T: SupportsInterfaces + ?Sized,
    DynInterface: ?Sized + 'static,
    X: Deref<Target=T>,
    Y,
    A
>(
    x: X,
    into_raw_parts: fn(X) -> (*mut T, A),
    from_raw_parts: unsafe fn(*mut DynInterface, A) -> Y
) -> Option<Y> where DynInterface: Pointee<Metadata=DynMetadata<DynInterface>> {
    let metadata = x.get_interface_metadata(TypeId::of::<DynInterface>())?;
    let metadata = metadata.downcast_ref::<InterfaceMetadata<DynInterface>>()
        .unwrap_or_else(|| panic!("invalid get_dyn_cast_metadata implementation"))
        .0
    ;
    let (raw_ptr, a) = into_raw_parts(x);
    let raw_ptr = raw_ptr.to_raw_parts().0;
    let raw_ptr = ptr::from_raw_parts_mut(raw_ptr, metadata);
    let x = from_raw_parts(raw_ptr, a);
    Some(x)
}

pub unsafe fn dyn_cast_raw<
    T: SupportsInterfaces + ?Sized,
    DynInterface: ?Sized + 'static,
    X: Deref<Target=T>,
    Y,
    A
>(
    x: X,
    into_raw_parts: fn(X) -> (*const T, A),
    from_raw_parts: unsafe fn(*const DynInterface, A) -> Y
) -> Option<Y> where DynInterface: Pointee<Metadata=DynMetadata<DynInterface>> {
    let metadata = x.get_interface_metadata(TypeId::of::<DynInterface>())?;
    let metadata = metadata.downcast_ref::<InterfaceMetadata<DynInterface>>()
        .unwrap_or_else(|| panic!("invalid get_dyn_cast_metadata implementation"))
        .0
    ;
    let (raw_ptr, a) = into_raw_parts(x);
    let raw_ptr = raw_ptr.to_raw_parts().0;
    let raw_ptr = ptr::from_raw_parts(raw_ptr, metadata);
    let x = from_raw_parts(raw_ptr, a);
    Some(x)
}

#[inline]
pub fn try_get_interface_metadata_for<DynInterface: ?Sized + 'static>(
    dyn_interface_id: TypeId,
    this: &DynInterface,
) -> Option<BoxedInterfaceMetadata> where DynInterface: Pointee<Metadata=DynMetadata<DynInterface>> {
    if dyn_interface_id == TypeId::of::<DynInterface>() {
        Some(ArrayBox::new(InterfaceMetadata(ptr::metadata(this as *const DynInterface))))
    } else {
        None
    }
}

#[macro_export]
macro_rules! impl_supports_interfaces {
    (
        $name:ty $(: $($($interface:path),+ $(,)?)?)?
    ) => {
        unsafe impl $crate::SupportsInterfaces for $name {
            fn get_interface_metadata(
                &self,
                dyn_interface_id: $crate::core_any_TypeId
            ) -> $crate::core_option_Option<$crate::BoxedInterfaceMetadata> {
                $($($(
                    if
                        let $crate::core_option_Option::Some(metadata) =
                            $crate::try_get_interface_metadata_for::<dyn $interface>(
                                dyn_interface_id, self
                            )
                    {
                        return $crate::core_option_Option::Some(metadata);
                    }
                )+)?)?
                None
            }
        }
    };
}