Skip to content

Commit

Permalink
core: remove suffix n in serde u64 serialization & deserialization
Browse files Browse the repository at this point in the history
  • Loading branch information
d-sonuga committed Jan 2, 2025
1 parent 44ded36 commit b253cd9
Show file tree
Hide file tree
Showing 2 changed files with 38 additions and 10 deletions.
2 changes: 2 additions & 0 deletions core/CHANGELOG.md
Original file line number Diff line number Diff line change
Expand Up @@ -7,6 +7,8 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0

## [Unreleased]

- Removed suffix 'n' in serde serialization & deserialization of `u64`

## [0.33.1] - 2024-12-20

### Changed
Expand Down
46 changes: 36 additions & 10 deletions core/src/serde_support.rs
Original file line number Diff line number Diff line change
Expand Up @@ -166,14 +166,15 @@ impl<'de> Deserialize<'de> for StealthAddress {

// To serialize and deserialize u64s as big ints:
// https://github.com/dusk-network/rusk/issues/2773#issuecomment-2519791322.
#[derive(Debug)]
struct Bigint(u64);

impl Serialize for Bigint {
fn serialize<S: Serializer>(
&self,
serializer: S,
) -> Result<S::Ok, S::Error> {
let s: String = format!("{}n", self.0);
let s: String = format!("{}", self.0);
s.serialize(serializer)
}
}
Expand All @@ -182,17 +183,11 @@ impl<'de> Deserialize<'de> for Bigint {
fn deserialize<D: Deserializer<'de>>(
deserializer: D,
) -> Result<Self, D::Error> {
let mut s = String::deserialize(deserializer)?;
let last_char = s.pop().ok_or_else(|| {
SerdeError::invalid_value(
Unexpected::Str(&s),
&"a non-empty string",
)
})?;
if last_char != 'n' {
let s = String::deserialize(deserializer)?;
if s.is_empty() {
return Err(SerdeError::invalid_value(
Unexpected::Str(&s),
&"a bigint ending with character 'n'",
&"a non-empty string",
));
}
let parsed_number = u64::from_str_radix(&s, 10).map_err(|e| {
Expand Down Expand Up @@ -587,3 +582,34 @@ impl<'de> Deserialize<'de> for TxSkeleton {
)
}
}

#[cfg(test)]
mod tests {
use rand::rngs::StdRng;
use rand::{RngCore, SeedableRng};

use super::*;

#[test]
fn serde_bigint() {
let mut rng = StdRng::seed_from_u64(0xc0b);
let n = Bigint(rng.next_u64());
let ser = serde_json::to_string(&n).unwrap();
let deser: Bigint = serde_json::from_str(&ser).unwrap();
assert_eq!(n.0, deser.0);
}

#[test]
fn serde_bigint_max() {
let n = Bigint(u64::MAX);
let ser = serde_json::to_string(&n).unwrap();
let deser: Bigint = serde_json::from_str(&ser).unwrap();
assert_eq!(n.0, deser.0);
}

#[test]
fn serde_bigint_empty() {
let deser: Result<Bigint, _> = serde_json::from_str("\"\"");
assert!(deser.is_err());
}
}

0 comments on commit b253cd9

Please sign in to comment.