uint icon indicating copy to clipboard operation
uint copied to clipboard

Feature request: "into"

Open PaulRBerg opened this issue 9 months ago • 2 comments

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>`

PaulRBerg avatar Sep 27 '23 09:09 PaulRBerg

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

prestwich avatar Oct 02 '23 15:10 prestwich

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).

ckoopmann avatar Nov 05 '23 09:11 ckoopmann