danlehmann / arbitrary-int

A modern and lightweight implementation of arbitrary integers for Rust
MIT License
31 stars 12 forks source link

`From<UnderlyingType>` and `TryFrom<UnderlyingType>` #13

Open hecatia-elegua opened 1 year ago

hecatia-elegua commented 1 year ago

Writing some_num.try_into()? can be useful, I noted this somewhere and forgot about it, so I don't have a direct usecase. Most likely macro generated code would need less typing and casting?

Oh right, it could replace try_new, too. That's actually the point. The ux crate does that as well and it keeps the interface clean. From<UnderlyingType> would replace new then. Of course this would need deprecation notes or if that's too extreme we can use feature gates here again (I hope not)

danlehmann commented 1 year ago

The reason I avoided this for now is because then it's no longer const.

But TryFrom would be possible to add on top of try_new(). The downside then is that you have multiple ways of doing the same thing

hecatia-elegua commented 1 year ago

TryFrom can be used generically, which is a different thing.

Another argument for not providing it would be that users should be nudged in the right direction and since it's not const yet, I agree that we should not provide it unless a usecase crops up.

Edit: less writing for stuff like this maybe:

// generated by macro
const fn set_field3<T: TryInto<u4>>(&mut self, value: T) {
    let field3 = value.try_into().expect("value is not convertible to u4");
    //...
}
lalala.set_field3(6); //maybe 6u8
lalala.set_field3(u2::new(6));