recmo / uint

Rust Uint crate using const-generics
MIT License
171 stars 40 forks source link

Feature request: "into" #315

Open PaulRBerg opened 1 year ago

PaulRBerg commented 1 year ago

I'd like to be able to initialize a U256 like this:

foo(10.into());

Where foo is a function that takes a U256 as an input.

This operation is not currently supported. I am getting the following error:

help: the following other types implement trait `From<T>`:
  <Uint<256, 4> as From<revm_interpreter::revm_primitives::B256>>
  <Uint<256, 4> as From<primitive_types::U256>>
label: the trait `From<{integer}>` is not implemented for `Uint<256, 4>`
prestwich commented 1 year ago

this is also tracked here: https://github.com/alloy-rs/core/issues/40

ckoopmann commented 1 year ago

I was going down a bit of rabbit hole, since I (naively) thought that this should be straight forward to implement. I ran into the wall of the problem of the collision with the autogenerated TryFrom implementation described here.

Imo it would be really neat if we could implement either From or TryFrom based on wether the maximum value of the input type fits into the given Uint variant. i.e. Uint<256, 4> would implement From<u128> (with the autogenerated "Infallible" TryFrom implementation) whereas Uint<64, 1> would implement TryFrom<u128>. Thereby you would only allow people to use .into() when the conversion is safe and .try_into() when it is not.

I am not sure if this is possible at all in rust though. I posted my first attempt to implement this and the problem I ran into here. Basically it boils down to wether it is possible to implement a trait exclusively for "type variants" whose const generic value satisfy a specific condition. ( BITS >= 128 in the above example).