Skip to content

Commit

Permalink
Fix the deserialization from JSON for I256 and U256 types with custom…
Browse files Browse the repository at this point in the history
… endianness (#28)
  • Loading branch information
stanislav-tkach committed Aug 29, 2023
1 parent 5bf8548 commit e072b41
Show file tree
Hide file tree
Showing 3 changed files with 52 additions and 0 deletions.
5 changes: 5 additions & 0 deletions Cargo.toml
Original file line number Diff line number Diff line change
Expand Up @@ -31,3 +31,8 @@ macros = ["ethnum-macros"]
ethnum-intrinsics = { version = "=1.1.0", path = "intrinsics", optional = true }
ethnum-macros = { version = "=1.1.0", path = "macros", optional = true }
serde = { version = "1", default-features = false, optional = true }

[dev-dependencies]
serde = { version = "1", features = ["derive"] }
serde_json = "1"
bincode = "1"
13 changes: 13 additions & 0 deletions src/serde.rs
Original file line number Diff line number Diff line change
Expand Up @@ -392,6 +392,19 @@ pub mod bytes {

Ok(T::from_bytes(bytes))
}

fn visit_seq<S>(self, mut seq: S) -> Result<Self::Value, S::Error>
where
S: de::SeqAccess<'de>,
{
let mut bytes: [u8; 32] = [0; 32];
for i in 0..32 {
bytes[i] = seq
.next_element()?
.ok_or(de::Error::invalid_length(i, &self))?;
}
Ok(T::from_bytes(bytes))
}
}

#[doc(hidden)]
Expand Down
34 changes: 34 additions & 0 deletions tests/serialize_deserialize.rs
Original file line number Diff line number Diff line change
@@ -0,0 +1,34 @@
#[cfg(feature = "serde")]
#[test]
fn roundtrip() {
use ethnum::{I256, U256};
use serde::{Deserialize, Serialize};

#[derive(Debug, Serialize, Deserialize, PartialEq, Eq)]
struct Test {
#[serde(with = "ethnum::serde::bytes::le")]
a: U256,
#[serde(with = "ethnum::serde::bytes::be")]
b: U256,
#[serde(with = "ethnum::serde::bytes::ne")]
c: U256,
#[serde(with = "ethnum::serde::bytes::le")]
d: I256,
#[serde(with = "ethnum::serde::bytes::be")]
e: I256,
#[serde(with = "ethnum::serde::bytes::ne")]
f: I256,
}

let original = Test {
a: U256::new(1),
b: U256::new(2),
c: U256::new(3),
d: I256::new(4),
e: I256::new(5),
f: I256::new(6),
};
let serialized = serde_json::to_string(&original).unwrap();
let deserialized: Test = serde_json::from_str(&serialized).unwrap();
assert_eq!(original, deserialized);
}

0 comments on commit e072b41

Please sign in to comment.