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
#![feature(get_type_id)]

use std::any::{Any, TypeId};

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

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

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

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

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


#[doc(hidden)]
#[inline]
pub fn get_type_id<T: ?Sized + Any>(obj: &T) -> TypeId {
    obj.get_type_id()
}

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

/// Use this macro if `impl_downcast!` can't generate the full statement for your
/// type (due to assoc-types or type-params).  
#[macro_export]
macro_rules! impl_downcast_items {
    ($t_param:ty) => {
        fn is_type(&self) -> bool {
            use std::any::TypeId;

            $crate::get_type_id(self) == TypeId::of::<$t_param>()
        }
        
        unsafe fn unsafe_downcast_ref(&self) -> &$t_param {
            use $crate::TraitObject;
            use std::mem;
            
            let obj: TraitObject = mem::transmute(self);
            mem::transmute(obj.data)
        }

        fn downcast_ref(&self) -> Option<&$t_param> {
            use $crate::Downcast;

            if Downcast::<$t_param>::is_type(self) {
                Some(unsafe { self.unsafe_downcast_ref() })
            } else {
                None
            }
        }
        
        unsafe fn unsafe_downcast_mut(&mut self) -> &mut $t_param {
            use $crate::TraitObject;
            use std::mem;
            
            let obj: TraitObject = mem::transmute(self);
            mem::transmute(obj.data)
        }
        
        fn downcast_mut(&mut self) -> Option<&mut $t_param> {
            use $crate::Downcast;

            if Downcast::<$t_param>::is_type(self) {
                Some(unsafe { self.unsafe_downcast_mut() })
            } else {
                None
            }
        }

        fn downcast_boxed(self: Box<Self>) -> Result<Box<$t_param>, Box<Self>> {
            use $crate::{Downcast, TraitObject};
            use std::mem;

            if Downcast::<$t_param>::is_type(&*self) {
                unsafe {
                    let obj: TraitObject = mem::transmute(self);
                    Ok(mem::transmute(obj.data))
                }
            } else {
                Err(self)            
            }
        }
    };
}

#[macro_export]
macro_rules! impl_downcast {
    ($base:ty) => {
        impl<__T> $crate::Downcast<__T> for $base 
            where __T: ::std::any::Any
        {
            impl_downcast_items!(__T);
        }
    };
}

/// Use this macro if `downcast_methods!` can't generate the full statement for your
/// type (due to assoc-types or type-params).  
#[macro_export]
macro_rules! downcast_method_items {
    () => {
        pub fn is<__T>(&self) -> bool 
            where __T: ::std::any::Any, Self: $crate::Downcast<__T>
        {
            $crate::Downcast::<__T>::is_type(self)
        }

        pub unsafe fn unsafe_downcast_ref<__T>(&self) -> &__T
            where __T: ::std::any::Any, Self: $crate::Downcast<__T>
        {
            $crate::Downcast::<__T>::unsafe_downcast_ref(self)
        }

        pub fn downcast_ref<__T>(&self) -> Option<&__T> 
            where __T: ::std::any::Any, Self: $crate::Downcast<__T>
        {
            $crate::Downcast::<__T>::downcast_ref(self)
        }

        pub unsafe fn unsafe_downcast_mut<__T>(&mut self) -> &mut __T
            where __T: ::std::any::Any, Self: $crate::Downcast<__T>
        {
            $crate::Downcast::<__T>::unsafe_downcast_mut(self)
        }

        pub fn downcast_mut<__T>(&mut self) -> Option<&mut __T> 
            where __T: ::std::any::Any, Self: $crate::Downcast<__T>
        {
            $crate::Downcast::<__T>::downcast_mut(self)
        }

        pub fn downcast_boxed<__T>(self: Box<Self>) ->  Result<Box<__T>, Box<Self>>
            where __T: ::std::any::Any, Self: $crate::Downcast<__T>
        {
            $crate::Downcast::<__T>::downcast_boxed(self)
        }
    };
}


/// 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 {
    ($ty:ty) => {
        impl $ty {
            downcast_method_items!();
        }
    };
}