From f600e59401dd97a619d70aec207e16ad7f0732f7 Mon Sep 17 00:00:00 2001 From: Stephen Chung Date: Mon, 13 Apr 2020 23:31:05 +0800 Subject: [PATCH] Fix bug with casting from float. --- src/any.rs | 49 +++++++++++++++++++++---------------------------- 1 file changed, 21 insertions(+), 28 deletions(-) diff --git a/src/any.rs b/src/any.rs index 65f68cbd..a056179b 100644 --- a/src/any.rs +++ b/src/any.rs @@ -279,39 +279,21 @@ impl Dynamic { /// assert_eq!(new_result.to_string(), "hello"); /// ``` pub fn from(value: T) -> Self { - if let Some(result) = (&value as &dyn Variant) - .downcast_ref::<()>() - .cloned() - .map(Union::Unit) - .or_else(|| { - (&value as &dyn Variant) - .downcast_ref::() - .cloned() - .map(Union::Bool) - .or_else(|| { - (&value as &dyn Variant) - .downcast_ref::() - .cloned() - .map(Union::Int) - .or_else(|| { - (&value as &dyn Variant) - .downcast_ref::() - .cloned() - .map(Union::Char) - }) - }) - }) - { + let dyn_value = &value as &dyn Variant; + + if let Some(result) = dyn_value.downcast_ref::<()>().cloned().map(Union::Unit) { + return Self(result); + } else if let Some(result) = dyn_value.downcast_ref::().cloned().map(Union::Bool) { + return Self(result); + } else if let Some(result) = dyn_value.downcast_ref::().cloned().map(Union::Int) { + return Self(result); + } else if let Some(result) = dyn_value.downcast_ref::().cloned().map(Union::Char) { return Self(result); } #[cfg(not(feature = "no_float"))] { - if let Some(result) = (&value as &dyn Variant) - .downcast_ref::() - .cloned() - .map(Union::Char) - { + if let Some(result) = dyn_value.downcast_ref::().cloned().map(Union::Float) { return Self(result); } } @@ -372,6 +354,7 @@ impl Dynamic { } /// Get a copy of the `Dynamic` value as a specific type. + /// Casting to a `Dynamic` just returns as is. /// /// # Panics /// @@ -391,8 +374,13 @@ impl Dynamic { } /// Get a reference of a specific type to the `Dynamic`. + /// Casting to `Dynamic` just returns a reference to it. /// Returns `None` if the cast fails. pub fn downcast_ref(&self) -> Option<&T> { + if TypeId::of::() == TypeId::of::() { + return (self as &dyn Variant).downcast_ref::(); + } + match &self.0 { Union::Unit(value) => (value as &dyn Variant).downcast_ref::(), Union::Bool(value) => (value as &dyn Variant).downcast_ref::(), @@ -408,8 +396,13 @@ impl Dynamic { } /// Get a mutable reference of a specific type to the `Dynamic`. + /// Casting to `Dynamic` just returns a mutable reference to it. /// Returns `None` if the cast fails. pub fn downcast_mut(&mut self) -> Option<&mut T> { + if TypeId::of::() == TypeId::of::() { + return (self as &mut dyn Variant).downcast_mut::(); + } + match &mut self.0 { Union::Unit(value) => (value as &mut dyn Variant).downcast_mut::(), Union::Bool(value) => (value as &mut dyn Variant).downcast_mut::(),