2

I have an enum called Magnitude:

pub enum Magnitude<T> {
    /// A finite value
    Finite(T),

    /// Positive infinity
    PosInfinite,

    /// Negative infinity
    NegInfinite,
}

and I want to implement From trait to be able to construct Magnitude from different types:

impl<T: Any> From<T> for Magnitude<T> {
    fn from(value: T) -> Self {
        if value.type_id() == TypeId::of::<f64>() {
            unsafe {
                let value_f64 = (&value as *const T).cast::<f64>().as_ref().unwrap().clone();
                if  value_f64 == f64::INFINITY {
                    Magnitude::PosInfinite
                } else if value_f64 == f64::NEG_INFINITY {
                    Magnitude::NegInfinite
                } else {
                    Magnitude::Finite(value)
                }
            }
        } else if value.type_id() == TypeId::of::<f32>() {
            unsafe {
                let value_f32 = (&value as *const T).cast::<f32>().as_ref().unwrap().clone();
                if  value_f32 == f32::INFINITY {
                    Magnitude::PosInfinite
                } else if value_f32 == f32::NEG_INFINITY {
                    Magnitude::NegInfinite
                } else {
                    Magnitude::Finite(value)
                }
            }
        } else {
            Magnitude::Finite(value)
        }
    }
}

if value is checked to be of type f64 using type_id, how unsafe is it to cast it to f64?

it passes the test below but I don't know if it will work correctly all the time:

#[test]
fn f64_infinity() {
    let pos_inf: Magnitude<f64> = f64::INFINITY.into();
    let neg_inf: Magnitude<f64> = f64::NEG_INFINITY.into();

    assert!(pos_inf.is_pos_infinite());
    assert!(neg_inf.is_neg_infinite());
}
5
  • This doesn't answer your question, but can't you use the downcast_ref method from Any? It seems more appropriate and does not need unsafe. Oct 12, 2020 at 11:04
  • @NiklasMohrin The downcast_ref() and downcast_mut() methods are for dynamic downcasting at runtime. They are only implemented for trait objects of type dyn Any + 'static and similar, but not for concrete types implenting the Any trait. Oct 12, 2020 at 11:17
  • @NiklasMohrin If I'm not mistaken, downcast_ref is implemented for dyn Any which means I have to implement From<dyn Any> instead of From<T>. but From is bounded by Sized trait which dyn Any does not implement because its size can not be known at compile time.
    – Amin Rayej
    Oct 12, 2020 at 11:18
  • Right, that checks out! Coming back to your question: I looked at the source of downcast_ref and there they are casting pointers after comparing type ids as well (doc.rust-lang.org/src/core/any.rs.html#195-204). You should be good Oct 12, 2020 at 11:32
  • @NiklasMohrin that looks promising! I wonder if this if type_check then cast is correct, can rust have something like smart cast in kotlin...
    – Amin Rayej
    Oct 12, 2020 at 12:16

1 Answer 1

3

A more natural way of implementing what you want would be to write different implementations for different types:

impl From<f32> for Magnitude<f32> {
    fn from(value: f32) -> Self {
        if value == f32::INFINITY {
            Magnitude::PosInfinite
        } else if value == f32::NEG_INFINITY {
            Magnitude::NegInfinite
        } else {
            Magnitude::Finite(value)
        }
    }
}

However, it would be difficult to implement a blanket implementation if you already have concrete implementations

impl<T> From<T> for Magnitude<T> {
    fn from(value: T) -> Self {
        Magnitude::Finite(value)
    }
}

results in

conflicting implementations of trait `std::convert::From<f32>` for type `Magnitude<f32>`:
  --> src/lib.rs:22:1
   |
10 | impl From<f32> for Magnitude<f32> {
   | --------------------------------- first implementation here
...
22 | impl<T> From<T> for Magnitude<T> {
   | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ conflicting implementation for `Magnitude<f32>`

While there is an accepted RFC to support specialization in Rust, this has not yet been fully implemented. For the time being, I suggest a slightly less general approach:

macro_rules! magnitude_from_float_impl {
    ($t:ty) => {
        impl From<$t> for Magnitude<$t> {
            fn from(value: $t) -> Self {
                if value.is_infinite() {
                    if value.is_sign_positive() {
                        Magnitude::PosInfinite
                    } else {
                        Magnitude::NegInfinite
                    }
                } else {
                    Magnitude::Finite(value)
                }
            }
        }
    }
}

macro_rules! magnitude_from_impl {
    ($t:ty) => {
        impl From<$t> for Magnitude<$t> {
            fn from(value: $t) -> Self {
                Magnitude::Finite(value)
            }
        }
    }
}


magnitude_from_float_impl!(f32);
magnitude_from_float_impl!(f64);
magnitude_from_impl!(i64);
magnitude_from_impl!(i32);

This does not provide a blanket implementation, but it's easy to add further types to the list of supported types.

3
  • It's a good solution but it's more complicated and hefty than one block of the unsafe cast. Of course, all that is true if that type of cast I mentioned is safe. if it's not safe, your solution is the way to go. That's why I'm curious and worried! about the safety of the mentioned cast
    – Amin Rayej
    Oct 12, 2020 at 12:44
  • Your cast is fine – it's just more complex than it needs to be. let value_f64 = *(&value as *const T as *const f64); is more concise and readable in my opinion. Oct 12, 2020 at 12:54
  • Thanks @SvenMarnach for your help :). Yes, yours is much more readable! I will use it instead
    – Amin Rayej
    Oct 12, 2020 at 13:07

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.