Reputation: 8481
I want to do the following operation on Balance
(u128
) numbers in NEAR smart contract using Rust:
a*b / (a+b)
To avoid overflow I need to convert the type to a type that supports bigger numbers. What's the proper way to do it?
I found a construct_uint!
macro. Is this a proper way to do or there is a better way?
construct_uint! {
/// 256-bit unsigned integer.
pub struct u256(4);
}
...
let aB = u256::from(a);
let bB = u256::from(b);
return (aB*bB / (aB+bB)).as_u128();
Upvotes: 4
Views: 164
Reputation: 487
For the underflow part, please see saturating_sub
:
https://doc.rust-lang.org/std/primitive.u128.html#method.saturating_sub
Upvotes: 1