kvark / mint

Math Interoperability Types
MIT License
256 stars 20 forks source link

casting between generic number types #63

Closed luiswirth closed 3 years ago

luiswirth commented 3 years ago

It would be nice to have a method for casting between the generic number types (e.g. T in Point2<T>).

Maybe something similiar to winit::dpi::PhysicalPosition::cast.

kvark commented 3 years ago

So basically impl<U, T: TryFrom<U>> TryFrom<Pointer2<U>> for Point2<T> ? It's an interesting idea. What is the use case for this? Mint is generally expected to be present only on API boundary, so the only conversion happening is to/from real match library types.

luiswirth commented 3 years ago

Hmm, yes I think your proposal should work.

The situation, I'm thinking of is the following:

Crate A provides A::Vec2 { x: f32, y: f32 }, while Crate B provides B::Vec2 { x: f64, y: f64 }. Now both would only implement mint conversions into and from the correspondingly parameterized mint type: A::Vec2 converts with Vector2<f32> and B::Vec2 converts with Vector2<f64>. Currently these are incompatible, because they have different inner types. I would like for the conversion to still be conveniently possible. This is arguably a real match, because the crates only chose different precision.

Originally I only thought of floating point numbers, but your proposal generalizes well, I think. This also works with integers and even with newtypes if the conversions are implemented.

So should impl<U, T: From<U>> From<Pointer2<U>> for Point2<T> maybe also be a thing? Or is it already (kinda hard to parse all the macros 😅 )?

kvark commented 3 years ago

Ok, sounds like you have a case for it. Let's see how it looks in code, and whether Rust isn't going to yell at us :)

luiswirth commented 3 years ago

Okay, sounds good. I'll try to implement it :).

luiswirth commented 3 years ago

Unfortunately this isn't possible currently. Because impl<T, U> TryFrom<Point2<U>> for Point2<T> with T == U conflicts with impl<T> From<T> for T.

This is a related discussion from the rust forum.

kvark commented 3 years ago

Ok, in this case we'll probably not offer it. Mint doesn't have any methods or traits. It focuses on types, and at most it has some of the standard traits implemented.

luiswirth commented 3 years ago

Okay, I agree.

I think the way to go for such convenience conversions, or making the usage of mint easier in general, is to make a dedicated crate like mint-use.

This way crates which provide mint support only have the minimal mint crate as dependency, which should only define the structs.

mint-use is for the users.