Skip to content

Commit

Permalink
Merge pull request #25 from okx/yz/fix_tou128
Browse files Browse the repository at this point in the history
fix to_u128
  • Loading branch information
wanyvic authored May 10, 2023
2 parents cb939fb + 3d8d778 commit 3004aa8
Showing 1 changed file with 19 additions and 6 deletions.
25 changes: 19 additions & 6 deletions src/brc20/num.rs
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
use crate::brc20::error::BRC20Error;
use crate::brc20::params::MAX_DECIMAL_WIDTH;
use bigdecimal::num_bigint::{BigInt, Sign};
use bigdecimal::num_bigint::{BigInt, Sign, ToBigInt};
use bigdecimal::{BigDecimal, FromPrimitive, ToPrimitive, Zero};
use serde::{Deserialize, Deserializer, Serialize, Serializer};
use std::fmt::{Display, Formatter};
Expand Down Expand Up @@ -59,11 +59,18 @@ impl Num {
}

pub fn checked_to_u128(&self) -> Result<u128, BRC20Error> {
Ok(self.0.clone().to_u128().ok_or(BRC20Error::Overflow {
op: String::from("to_u128"),
org: self.clone(),
other: Self(BigDecimal::from(BigInt::from(u128::MAX))), // TODO: change overflow error to others
})?)
Ok(
self
.0
.to_bigint()
.unwrap()
.to_u128()
.ok_or(BRC20Error::Overflow {
op: String::from("to_u128"),
org: self.clone(),
other: Self(BigDecimal::from(BigInt::from(u128::MAX))), // TODO: change overflow error to others
})?,
)
}
}

Expand Down Expand Up @@ -276,4 +283,10 @@ mod tests {
Num::from_str("1000000000000000000").unwrap()
);
}

#[test]
fn test_checked_to_u128() {
let n = Num::from_str(&format!("{}", u128::MAX)).unwrap();
assert_eq!(n.checked_to_u128().unwrap(), u128::MAX);
}
}

0 comments on commit 3004aa8

Please sign in to comment.