Skip to content

Commit

Permalink
Add a itf::de::from_bigint deserializer function to convert from `B…
Browse files Browse the repository at this point in the history
…igInt` via `#[serde(deserialize_with = "...")]`
  • Loading branch information
romac committed Nov 20, 2023
1 parent b06e4b5 commit a2eef53
Show file tree
Hide file tree
Showing 3 changed files with 34 additions and 0 deletions.
3 changes: 3 additions & 0 deletions itf/src/de.rs
Original file line number Diff line number Diff line change
Expand Up @@ -5,6 +5,9 @@ use crate::Value;
mod error;
pub use error::Error;

mod helpers;
pub use helpers::from_bigint;

mod deserializer;

#[doc(hidden)]
Expand Down
15 changes: 15 additions & 0 deletions itf/src/de/helpers.rs
Original file line number Diff line number Diff line change
@@ -0,0 +1,15 @@
use std::fmt::Display;

use num_bigint::BigInt;
use serde::de::Error;
use serde::{Deserialize, Deserializer};

pub fn from_bigint<'de, A, D>(deserializer: D) -> Result<A, D::Error>
where
D: Deserializer<'de>,
A: TryFrom<BigInt>,
<A as TryFrom<BigInt>>::Error: Display,
{
let bigint = BigInt::deserialize(deserializer).map_err(D::Error::custom)?;
A::try_from(bigint).map_err(D::Error::custom)
}
16 changes: 16 additions & 0 deletions itf/tests/regression.rs
Original file line number Diff line number Diff line change
Expand Up @@ -153,6 +153,22 @@ fn test_enum_deserialization_failure() {

assert!(itf::from_value::<FooBarInt>(itf.clone()).is_err());

#[derive(Deserialize, Debug)]
#[serde(tag = "typ")]
enum FooBarWithInt {
// try to deserialize _foo as i64, via a conversion from BigInt
Foo {
#[serde(deserialize_with = "itf::de::from_bigint")]
_foo: i64,
},
Bar {
_bar: String,
},
}
itf::from_value::<FooBarWithInt>(itf.clone()).unwrap();

assert!(itf::from_value::<FooBarWithInt>(itf.clone()).is_ok());

#[derive(Deserialize, Debug)]
#[serde(tag = "typ")]
enum FooBarBigInt {
Expand Down

0 comments on commit a2eef53

Please sign in to comment.