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
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
/*!
This module is a general interface to `traitcast` which does not rely on a
global registry. This makes it more flexible at the cost of having to create
a registry and pass it around. If you do not want to do that, use the root
`traitcast` module which provides a convenient global registry.
*/

#[cfg(feature = "use_inventory")]
pub mod inventory;

// #[cfg(test)]
// pub mod tests;

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

/// A registry defining how to cast into some set of traits.
pub struct Registry {
    pub tables: anymap::Map<dyn anymap::any::Any + Sync>,
}

impl Registry {
    /// Makes a new, empty trait registry.
    pub fn new() -> Registry {
        Registry {
            tables: anymap::Map::new(),
        }
    }

    /// Updates the table defining how to cast into the given trait.
    pub fn insert<DynTrait: ?Sized + 'static>(
        &mut self,
        table: CastIntoTrait<DynTrait>,
    ) {
        self.tables.insert(table);
    }

    /// Gets the table defining how to cast into the given trait.
    ///
    /// This method is designed to be chained with from_mut, from_ref or
    /// from_box.
    ///
    /// # Examples
    /// ```text
    /// let x: &dyn Bar = ...;
    /// registry.cast_into::<Foo>()?.from_ref(x)
    ///
    /// let x: &mut dyn Bar = ...;
    /// registry.cast_into::<Foo>()?.from_mut(x)
    ///
    /// let x: Box<dyn Bar> = ...;
    /// registry.cast_into::<Foo>()?.from_box(x)
    /// ```
    pub fn cast_into<To>(&self) -> Option<&CastIntoTrait<To>>
    where
        To: ?Sized + 'static,
    {
        self.tables.get::<CastIntoTrait<To>>()
    }
}

/// Provides methods for casting into the target trait object from other trait
/// objects.
pub struct CastIntoTrait<DynTrait: ?Sized> {
    pub map: HashMap<TypeId, ImplEntry<DynTrait>>,
}

impl<DynTrait: ?Sized> CastIntoTrait<DynTrait> {
    pub fn new() -> Self {
        CastIntoTrait { map: HashMap::new() }
    }
}

impl<DynTrait: ?Sized> std::iter::FromIterator<ImplEntry<DynTrait>>
    for CastIntoTrait<DynTrait>
{
    fn from_iter<T>(iter: T) -> Self
    where
        T: IntoIterator<Item = ImplEntry<DynTrait>>,
    {
        CastIntoTrait {
            map: iter.into_iter().map(|x| (x.tid, x)).collect(),
        }
    }
}

impl<To: ?Sized + 'static> CastIntoTrait<To> {
    /// Tries to cast the given reference to a dynamic trait object. This will
    /// always return None if the implementation of the target trait, for the
    /// concrete type of x, has not been registered via `traitcast_to_impl!`.
    pub fn from_ref<'a, From>(&self, x: &'a From) -> Option<&'a To>
    where
        From: TraitcastFrom + ?Sized,
    {
        let x = (*x).as_any_ref();
        let tid = x.type_id();
        let s = self.map.get(&tid)?;
        (s.cast_ref)(x)
    }

    /// Tries to cast the given mutable reference to a dynamic trait object.
    /// This will always return None if the implementation of the target trait,
    /// for the concrete type of x, has not been registered via
    /// `traitcast_to_impl!`.
    pub fn from_mut<'a, From>(&self, x: &'a mut From) -> Option<&'a mut To>
    where
        From: TraitcastFrom + ?Sized,
    {
        let x = (*x).as_any_mut();
        let tid = (x as &dyn Any).type_id();
        let s = self.map.get(&tid)?;
        (s.cast_mut)(x)
    }

    /// Tries to cast the given pointer to a dynamic trait object. This will
    /// always return Err if the implementation of the target trait, for the
    /// concrete type of x, has not been registered via `traitcast_to_impl!`.
    pub fn from_box<From>(&self, x: Box<From>) -> Result<Box<To>, Box<dyn Any>>
    where
        From: TraitcastFrom + ?Sized,
    {
        let x = x.as_any_box();

        // Must ensure we take the type id of what's in the box, not the type
        // id of the box itself.
        let tid = (*x).type_id();

        let s = match self.map.get(&tid) {
            Some(s) => s,
            None => return Err(x),
        };

        (s.cast_box)(x)
    }
}

/// An entry in the table for a particular castable trait. Stores methods to
/// cast into one particular struct that implements the trait.
pub struct ImplEntry<DynTrait: ?Sized> {
    pub cast_box: fn(Box<Any>) -> Result<Box<DynTrait>, Box<Any>>,
    pub cast_mut: fn(&mut dyn Any) -> Option<&mut DynTrait>,
    pub cast_ref: fn(&dyn Any) -> Option<&DynTrait>,
    pub tid: TypeId,
    pub from_name: &'static str,
    pub into_name: &'static str
}

/// Manual `Clone` impl to allow for unsized T.
impl<T: ?Sized> Clone for ImplEntry<T> {
    fn clone(&self) -> Self {
        ImplEntry {
            cast_box: self.cast_box,
            cast_mut: self.cast_mut,
            cast_ref: self.cast_ref,
            tid: self.tid,
            from_name: self.from_name,
            into_name: self.into_name
        }
    }
}

/// Subtraits of `TraitcastFrom` may be cast into `dyn Any`, and thus may be
/// cast into any other castable dynamic trait object, too. This is blanket
/// implemented for all sized types with static lifetimes.
pub trait TraitcastFrom {
    /// Cast to an immutable reference to a trait object.
    fn as_any_ref(&self) -> &dyn Any;

    /// Cast to a mutable reference to a trait object.
    fn as_any_mut(&mut self) -> &mut dyn Any;

    /// Cast to a boxed reference to a trait object.
    fn as_any_box(self: Box<Self>) -> Box<dyn Any>;

    /// Get the trait object's dynamic type id.
    fn type_id(&self) -> std::any::TypeId {
        self.as_any_ref().type_id()
    }
}

/// Blanket implementation that automatically implements TraitcastFrom for most
/// user-defined types.
impl<T> TraitcastFrom for T
where
    T: Sized + 'static,
{
    fn as_any_ref(&self) -> &dyn Any {
        self
    }

    fn as_any_mut(&mut self) -> &mut dyn Any {
        self
    }

    fn as_any_box(self: Box<Self>) -> Box<dyn Any> {
        self
    }
}

impl TraitcastFrom for dyn Any {
    fn as_any_ref(&self) -> &dyn Any {
        self
    }

    fn as_any_mut(&mut self) -> &mut dyn Any {
        self
    }

    fn as_any_box(self: Box<Self>) -> Box<dyn Any> {
        self
    }
}

/// Constructs a `ImplEntry` for a trait and a concrete struct implementing
/// that trait.
///
/// # Example
/// ```
/// # use traitcast_core::impl_entry;
/// # use traitcast_core::ImplEntry;
/// use std::fmt::Display;
/// let x: ImplEntry<Display> = impl_entry!(dyn Display, i32);
/// ```
#[macro_export]
macro_rules! impl_entry {
    ($source:ty, $target:ty) => {
        $crate::ImplEntry::<$source> {
            cast_box: |x| {
                let x: Box<$target> = x.downcast()?;
                let x: Box<$source> = x;
                Ok(x)
            },
            cast_mut: |x| {
                let x: &mut $target = x.downcast_mut()?;
                let x: &mut $source = x;
                Some(x)
            },
            cast_ref: |x| {
                let x: &$target = x.downcast_ref()?;
                let x: &$source = x;
                Some(x)
            },
            tid: std::any::TypeId::of::<$target>(),
            from_name: stringify!($source),
            into_name: stringify!($target)
        }
    };
}

/// Creates a struct named `$wrapper` which wraps `ImplEntry<dyn $trait>` for
/// the given `$trait`. This is useful because it allows implementing traits on
/// the `ImplEntry<dyn $trait>` from external modules. This is an
/// implementation detail of `traitcast_to_trait!`.
#[macro_export]
macro_rules! defn_impl_entry_wrapper {
    ($type:ty, $vis:vis $wrapper:ident) => {
        #[allow(non_camel_case_types)]
        $vis struct $wrapper(pub $crate::ImplEntry<$type>);

        impl std::convert::From<$crate::ImplEntry<$type>> for $wrapper {
            fn from(x: $crate::ImplEntry<$type>) -> Self {
                $wrapper(x)
            }
        }

        impl std::convert::AsRef<$crate::ImplEntry<$type>> for $wrapper {
            fn as_ref(&self) -> &$crate::ImplEntry<$type> {
                &self.0
            }
        }
    };
}