'How to make aritmetic operations on Balance numbers to avoid overflow in NEAR smart contracts?

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();


Solution 1:[1]

For the underflow part, please see saturating_sub: https://doc.rust-lang.org/std/primitive.u128.html#method.saturating_sub

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 mikeDOTexe