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

Add documentations about Integer overflows #7

Open
lizhuohua opened this issue Feb 2, 2021 · 1 comment
Open

Add documentations about Integer overflows #7

lizhuohua opened this issue Feb 2, 2021 · 1 comment

Comments

@lizhuohua
Copy link

Hi, first of all, thanks for the great crate.

However, dealing with large numbers can easily cause integer overflows. For example, the following code would cause a runtime panic for debug build and return a wrong answer for release build:

use byte_unit;
fn main() {
    println!("{}", byte_unit::n_zb_bytes(std::u128::MAX));  // integer overflow
}

Prabably it is better to add more documentations to illustrate under what conditions these functions would not work properly.

@magiclen
Copy link
Owner

After version 5.0, every calculation is checked.

use byte_unit::{Byte, Unit};

fn main() {
    println!("{:?}", Byte::from_u128(1 << 80)); // returns `None` if the `u128` feature is not enabled
    println!("{:?}", Byte::from_u128(u128::MAX)); // returns `None` even if the `u128` feature is enabled
    println!("{:?}", Byte::from_u64_with_unit(1_000_000_000, Unit::TB)); // returns `None` if the `u128` feature is not enabled
    println!("{:?}", Byte::from_u64(u64::MAX).multiply(2)); // returns `None` if the `u128` feature is not enabled
}

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