From d6f01bd571753dc2e9628418f94f66139438bcb3 Mon Sep 17 00:00:00 2001 From: HampusM Date: Tue, 30 Aug 2022 18:53:23 +0200 Subject: refactor: replace arc cast panic with an error --- src/libs/intertrait/mod.rs | 25 ++++++++----------------- 1 file changed, 8 insertions(+), 17 deletions(-) (limited to 'src/libs/intertrait/mod.rs') diff --git a/src/libs/intertrait/mod.rs b/src/libs/intertrait/mod.rs index bdae4c7..3b3e9ba 100644 --- a/src/libs/intertrait/mod.rs +++ b/src/libs/intertrait/mod.rs @@ -23,7 +23,7 @@ //! MIT license (LICENSE-MIT or ) //! //! at your option. -use std::any::{type_name, Any, TypeId}; +use std::any::{Any, TypeId}; use std::rc::Rc; use std::sync::Arc; @@ -58,22 +58,12 @@ static CASTER_MAP: Lazy> = Lazy::new(|| .collect() }); -fn cast_arc_panic(_: Arc) -> Arc -{ - panic!( - "Interface trait '{}' has not been marked async", - type_name::() - ) -} +type CastArcFn = fn(from: Arc) -> Arc; /// A `Caster` knows how to cast a reference to or `Box` of a trait object for `Any` /// to a trait object of trait `Trait`. Each `Caster` instance is specific to a concrete /// type. That is, it knows how to cast to single specific trait implemented by single /// specific type. -/// -/// An implementation of a trait for a concrete type doesn't need to manually provide -/// a `Caster`. Instead attach `#[cast_to]` to the `impl` block. -#[doc(hidden)] pub struct Caster { /// Casts a `Box` holding a trait object for `Any` to another `Box` holding a trait @@ -86,7 +76,7 @@ pub struct Caster /// Casts an `Arc` holding a trait object for `Any + Sync + Send + 'static` /// to another `Arc` holding a trait object for trait `Trait`. - pub cast_arc: fn(from: Arc) -> Arc, + pub opt_cast_arc: Option>, } impl Caster @@ -99,7 +89,7 @@ impl Caster Caster:: { cast_box, cast_rc, - cast_arc: cast_arc_panic, + opt_cast_arc: None, } } @@ -113,14 +103,15 @@ impl Caster Caster:: { cast_box, cast_rc, - cast_arc, + opt_cast_arc: Some(cast_arc), } } } /// Returns a `Caster` from a concrete type `S` to a trait `Trait` implemented /// by it. -fn caster(type_id: TypeId) -> Option<&'static Caster> +fn get_caster(type_id: TypeId) + -> Option<&'static Caster> { CASTER_MAP .get(&(type_id, TypeId::of::>())) @@ -250,7 +241,7 @@ mod tests let caster = Box::new(Caster:: { cast_box: |from| from.downcast::().unwrap(), cast_rc: |from| from.downcast::().unwrap(), - cast_arc: |from| from.downcast::().unwrap(), + opt_cast_arc: Some(|from| from.downcast::().unwrap()), }); (type_id, caster) } -- cgit v1.2.3-18-g5258