Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

[uint] conversion between uint types #799

Open
2 tasks done
wojciech-cichocki opened this issue Nov 10, 2023 · 2 comments
Open
2 tasks done

[uint] conversion between uint types #799

wojciech-cichocki opened this issue Nov 10, 2023 · 2 comments

Comments

@wojciech-cichocki
Copy link

wojciech-cichocki commented Nov 10, 2023

Is there an existing issue?

Experiencing problems? Have you tried our Stack Exchange first?

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

@ggwpez
Copy link
Member

ggwpez commented Nov 13, 2023

U512::try_from(U256::MAX)

In this case the the conversion is always infallible, so why the try?
I am not sure what exactly you need, but if its just conversion methods then sure we can use those 😄

Just FYI we also have fixed point math in Substrate: https://paritytech.github.io/polkadot-sdk/master/sp_arithmetic/index.html

@wojciech-cichocki
Copy link
Author

I meant a generic conversion between any types of uints, so try can be useful if the value doesn't fit. What's more, uint dependency is required in my case.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

2 participants