Byte-Unit icon indicating copy to clipboard operation
Byte-Unit copied to clipboard

Add documentations about Integer overflows

Open lizhuohua opened this issue 4 years ago • 1 comments

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.

lizhuohua avatar Feb 02 '21 15:02 lizhuohua

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
}

magiclen avatar Nov 26 '23 02:11 magiclen