parity-common icon indicating copy to clipboard operation
parity-common copied to clipboard

[uint] conversion between uint types

Open wojciech-cichocki opened this issue 7 months ago • 2 comments

Is there an existing issue?

  • [x] I have searched the existing issues. There is no such request yet, but here's a request with the most similar vibe: #691

Experiencing problems? Have you tried our Stack Exchange first?

  • [x] This is not a support question.

Question: What is recommended way to convert one type of uint to another?

Background: I've developed a high-level lib for creating custom DeFi-oriented types that are implemented in pure Rust, where uint types serve as underlying types.

Details: In certain scenarios, I need to expand the type to prevent overflow in intermediate calculations. For instance, there are cases where I must extend the type from U256 to U512. I'm exploring the best approach to convert between different uint types.

Based on my observations, it seems that try_from is only implemented for primitive types. One option is to manually rewrite the u64 values, but I believe there might be a more elegant solution. Perhaps it's worth considering the addition of a try_from implementation for converting between types at the uint library level.

As an illustration, consider the following two types:

construct_uint! {
    pub struct U256(4);
}

construct_uint! {
    pub struct U512(8);
}

In this context, creating a U512 type based on a U256 instance could look like this:

U512::try_from(U256::MAX)

Are you willing to help with this request? I am willing to create a proposal for implementation if the feature is deemed useful.

wojciech-cichocki avatar Nov 10 '23 15:11 wojciech-cichocki