Skip to content

Commit

Permalink
move away from BigInt::try_into (#458)
Browse files Browse the repository at this point in the history
  • Loading branch information
chenyan-dfinity authored Aug 3, 2023
1 parent 6188ebb commit 2c3f8a3
Show file tree
Hide file tree
Showing 4 changed files with 18 additions and 8 deletions.
2 changes: 1 addition & 1 deletion Cargo.lock

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

2 changes: 1 addition & 1 deletion rust/candid/Cargo.toml
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
[package]
name = "candid"
version = "0.9.2"
version = "0.9.3"
edition = "2021"
authors = ["DFINITY Team"]
description = "Candid is an interface description language (IDL) for interacting with canisters running on the Internet Computer."
Expand Down
15 changes: 12 additions & 3 deletions rust/candid/src/de.rs
Original file line number Diff line number Diff line change
Expand Up @@ -505,16 +505,21 @@ impl<'de, 'a> de::Deserializer<'de> for &'a mut Deserializer<'de> {
where
V: Visitor<'de>,
{
use num_traits::ToPrimitive;
self.unroll_type()?;
assert!(*self.expect_type == TypeInner::Int);
let value: i128 = match self.wire_type.as_ref() {
TypeInner::Int => {
let int = Int::decode(&mut self.input).map_err(Error::msg)?;
int.0.try_into().map_err(Error::msg)?
int.0
.to_i128()
.ok_or_else(|| Error::msg("Cannot convert int to i128"))?
}
TypeInner::Nat => {
let nat = Nat::decode(&mut self.input).map_err(Error::msg)?;
nat.0.try_into().map_err(Error::msg)?
nat.0
.to_i128()
.ok_or_else(|| Error::msg("Cannot convert nat to i128"))?
}
t => return Err(Error::subtype(format!("{t} cannot be deserialized to int"))),
};
Expand All @@ -524,13 +529,17 @@ impl<'de, 'a> de::Deserializer<'de> for &'a mut Deserializer<'de> {
where
V: Visitor<'de>,
{
use num_traits::ToPrimitive;
self.unroll_type()?;
check!(
*self.expect_type == TypeInner::Nat && *self.wire_type == TypeInner::Nat,
"nat"
);
let nat = Nat::decode(&mut self.input).map_err(Error::msg)?;
let value: u128 = nat.0.try_into().map_err(Error::msg)?;
let value = nat
.0
.to_u128()
.ok_or_else(|| Error::msg("Cannot convert nat to u128"))?;
visitor.visit_u128(value)
}
fn deserialize_unit<V>(self, visitor: V) -> Result<V::Value>
Expand Down
7 changes: 4 additions & 3 deletions rust/candid/src/types/number.rs
Original file line number Diff line number Diff line change
Expand Up @@ -188,9 +188,10 @@ impl<'de> Deserialize<'de> for Nat {
formatter.write_str("Nat value")
}
fn visit_i64<E: de::Error>(self, v: i64) -> Result<Nat, E> {
Ok(Nat(BigUint::try_from(v).map_err(|_| {
de::Error::custom("int cannot be converted to nat")
})?))
use num_bigint::ToBigUint;
v.to_biguint()
.ok_or_else(|| de::Error::custom("i64 cannot be converted to nat"))
.map(Nat)
}
fn visit_u64<E>(self, v: u64) -> Result<Nat, E> {
Ok(Nat::from(v))
Expand Down

0 comments on commit 2c3f8a3

Please sign in to comment.