alloy_serde/displayfromstr.rs
1//! Serde functions for (de)serializing using FromStr and Display
2//!
3//! Useful for example in encoding SSZ `uintN` primitives using the "canonical JSON mapping"
4//! described in the consensus-specs here: <https://github.com/ethereum/consensus-specs/blob/dev/ssz/simple-serialize.md#json-mapping>
5//!
6//! # Example
7//! ```
8//! use alloy_serde;
9//! use serde::{Deserialize, Serialize};
10//!
11//! #[derive(Debug, PartialEq, Eq, Serialize, Deserialize)]
12//! pub struct Container {
13//! #[serde(with = "alloy_serde::displayfromstr")]
14//! value: u64,
15//! }
16//!
17//! let val = Container { value: 18112749083033600 };
18//! let s = serde_json::to_string(&val).unwrap();
19//! assert_eq!(s, "{\"value\":\"18112749083033600\"}");
20//!
21//! let deserialized: Container = serde_json::from_str(&s).unwrap();
22//! assert_eq!(val, deserialized);
23//! ```
24
25use crate::alloc::string::{String, ToString};
26use core::{fmt, str::FromStr};
27use serde::{Deserialize, Deserializer, Serializer};
28
29/// Serialize a type `T` that implements [fmt::Display] as a quoted string.
30pub fn serialize<T, S>(value: &T, serializer: S) -> Result<S::Ok, S::Error>
31where
32 T: fmt::Display,
33 S: Serializer,
34{
35 serializer.collect_str(&value.to_string())
36}
37
38/// Deserialize a quoted string to a type `T` using [FromStr].
39pub fn deserialize<'de, T, D>(deserializer: D) -> Result<T, D::Error>
40where
41 D: Deserializer<'de>,
42 T: FromStr,
43 T::Err: fmt::Display,
44{
45 String::deserialize(deserializer)?.parse().map_err(serde::de::Error::custom)
46}