big_num_manager/
lib.rs

1pub mod serde_format;
2
3use std::io::{self, Error, ErrorKind};
4
5use num_bigint::BigInt;
6
7/// Parses the big.Int encoded in hex.
8/// "0x52B7D2DCC80CD2E4000000" is "100000000000000000000000000" (100,000,000 AVAX).
9/// "0x5f5e100" or "0x5F5E100" is "100000000".
10/// "0x1312D00" is "20000000".
11/// ref. https://www.rapidtables.com/convert/number/hex-to-decimal.html
12pub fn from_hex_to_big_int(s: &str) -> io::Result<BigInt> {
13    let sb = s.trim_start_matches("0x").as_bytes();
14
15    // ref. https://docs.rs/num-bigint/latest/num_bigint/struct.BigInt.html
16    let b = match BigInt::parse_bytes(sb, 16) {
17        Some(v) => v,
18        None => {
19            return Err(Error::new(
20                ErrorKind::Other,
21                format!("failed to parse hex big int {} (parse returned None)", s),
22            ));
23        }
24    };
25    Ok(b)
26}
27
28/// ref. https://doc.rust-lang.org/nightly/core/fmt/trait.UpperHex.html
29pub fn big_int_to_upper_hex(v: &BigInt) -> String {
30    format!("{:#X}", v)
31}
32
33/// ref. https://doc.rust-lang.org/nightly/core/fmt/trait.LowerHex.html
34pub fn big_int_to_lower_hex(v: &BigInt) -> String {
35    format!("{:#x}", v)
36}
37
38/// RUST_LOG=debug cargo test --all-features --package big-num-manager --lib -- test_hex --exact --show-output
39#[test]
40fn test_hex() {
41    use num_bigint::ToBigInt;
42
43    let big_num = BigInt::default();
44    assert_eq!(from_hex_to_big_int("0x0").unwrap(), big_num);
45
46    let big_num = ToBigInt::to_bigint(&100000000000000000000000000_i128).unwrap();
47    assert_eq!(
48        from_hex_to_big_int("0x52B7D2DCC80CD2E4000000").unwrap(),
49        big_num
50    );
51    assert_eq!(big_int_to_upper_hex(&big_num), "0x52B7D2DCC80CD2E4000000",);
52
53    let big_num = ToBigInt::to_bigint(&100000000_i128).unwrap();
54    assert_eq!(from_hex_to_big_int("0x5F5E100").unwrap(), big_num);
55    assert_eq!(big_int_to_lower_hex(&big_num), "0x5f5e100",);
56    assert_eq!(big_int_to_upper_hex(&big_num), "0x5F5E100",);
57
58    let big_num = ToBigInt::to_bigint(&20000000_i128).unwrap();
59    assert_eq!(from_hex_to_big_int("0x1312D00").unwrap(), big_num);
60    assert_eq!(big_int_to_lower_hex(&big_num), "0x1312d00",);
61    assert_eq!(big_int_to_upper_hex(&big_num), "0x1312D00",);
62}