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
161
162
163
164
165
166
167
use std::any::Any;
use std::mem;

pub trait Downcast<T: Any + Sized>: Any {
    fn is_type(&self) -> bool;
    
    unsafe fn unchecked_downcast_ref(&self) -> &T;

    fn downcast_ref(&self) -> Option<&T>;

    unsafe fn unchecked_downcast_mut(&mut self) -> &mut T;

    fn downcast_mut(&mut self) -> Option<&mut T>;  

    unsafe fn unchecked_downcast(self: Box<Self>) -> Box<T>;

    fn downcast(self: Box<Self>) -> Result<Box<T>, Box<Self>>;
}

#[doc(hidden)]
#[derive(Clone, Copy)]
pub struct TraitObject {
    pub data: *mut (),
    pub vtable: *mut (),
}

#[doc(hidden)]
#[inline(always)]
pub fn to_trait_object<B: ?Sized>(base: &B) -> TraitObject {
    assert_eq!(mem::size_of::<&B>(), mem::size_of::<TraitObject>());
    unsafe { *mem::transmute::<&&B, *const TraitObject>(&base) }
}

/// Implements `Downcast<T: $base>` for `$base`.
#[macro_export]
macro_rules! impl_downcast { 
    (@items $t:ty) => {
        #[inline(always)]
        fn is_type(&self) -> bool {
            unsafe { 
                let dummy: &Self = ::std::mem::uninitialized::<&$t>();
                ::downcast::to_trait_object(self).vtable == ::downcast::to_trait_object(dummy).vtable
            }
        }
        
        #[inline(always)]
        unsafe fn unchecked_downcast_ref(&self) -> &$t {
            ::std::mem::transmute(::downcast::to_trait_object(self).data)
        }

        #[inline(always)]
        fn downcast_ref(&self) -> Option<&$t> {
            if ::downcast::Downcast::<$t>::is_type(self) {
                Some(unsafe { self.unchecked_downcast_ref() })
            } else {
                None
            }
        }
        
        #[inline(always)]
        unsafe fn unchecked_downcast_mut(&mut self) -> &mut $t {
            ::std::mem::transmute(::downcast::to_trait_object(self).data)
        }
        
        #[inline(always)]
        fn downcast_mut(&mut self) -> Option<&mut $t> {
            if ::downcast::Downcast::<$t>::is_type(self) {
                Some(unsafe { self.unchecked_downcast_mut() })
            } else {
                None
            }
        }

        #[inline(always)]
        unsafe fn unchecked_downcast(self: Box<Self>) -> Box<$t> {
            let ret = ::std::mem::transmute::<_, Box<T>>(::downcast::to_trait_object(&*self).data);
            ::std::mem::forget(self);
            ret
        }

        #[inline(always)]
        fn downcast(self: Box<Self>) -> Result<Box<$t>, Box<Self>> {
            if ::downcast::Downcast::<$t>::is_type(&*self) {
                Ok(unsafe { self.unchecked_downcast() })
            } else {
                Err(self)            
            }
        }
    };
    ($base:ident) => {
        impl<T> ::downcast::Downcast<T> for $base
            where T: $base
        {
            impl_downcast!(@items T);
        }
    };
}

/// Use this macro if you want to provide `downcast`-methods on your type without 
/// requiring your users to import `Downcast`.
#[macro_export]
macro_rules! downcast_methods {
    (@items) => {
        #[allow(unused)]
        #[inline(always)]
        pub fn is<T>(&self) -> bool 
            where T: ::std::any::Any, Self: ::downcast::Downcast<T>
        {
            ::downcast::Downcast::<T>::is_type(self)
        }

        #[allow(unused)]
        #[inline(always)]
        pub unsafe fn unchecked_downcast_ref<T>(&self) -> &T
            where T: ::std::any::Any, Self: ::downcast::Downcast<T>
        {
            ::downcast::Downcast::<T>::unchecked_downcast_ref(self)
        }

        #[allow(unused)]
        #[inline(always)]
        pub fn downcast_ref<T>(&self) -> Option<&T> 
            where T: ::std::any::Any, Self: ::downcast::Downcast<T>
        {
            ::downcast::Downcast::<T>::downcast_ref(self)
        }

        #[allow(unused)]
        #[inline(always)]
        pub unsafe fn unchecked_downcast_mut<T>(&mut self) -> &mut T
            where T: ::std::any::Any, Self: ::downcast::Downcast<T>
        {
            ::downcast::Downcast::<T>::unchecked_downcast_mut(self)
        }

        #[allow(unused)]
        #[inline(always)]
        pub fn downcast_mut<T>(&mut self) -> Option<&mut T> 
            where T: ::std::any::Any, Self: ::downcast::Downcast<T>
        {
            ::downcast::Downcast::<T>::downcast_mut(self)
        }

        #[allow(unused)]
        #[inline(always)]
        pub unsafe fn unchecked_downcast<T>(self: Box<Self>) -> Box<T>
            where T: ::std::any::Any, Self: ::downcast::Downcast<T>
        {
            ::downcast::Downcast::<T>::unchecked_downcast(self)
        }

        #[allow(unused)]
        #[inline(always)]
        pub fn downcast<T>(self: Box<Self>) ->  Result<Box<T>, Box<Self>>
            where T: ::std::any::Any, Self: ::downcast::Downcast<T>
        {
            ::downcast::Downcast::<T>::downcast(self)
        }
    };
    ($ty:ty) => {
        impl $ty {
            downcast_methods!(@items);
        }
    };
}