tendermint_proto/serializers/from_str_allow_null.rs
1//! Combines [`from_str`] and [`allow_null`].
2//!
3//! Use this module to serialize and deserialize any `T` where `T` implements
4//! [`FromStr`] and [`Display`] to convert from or into a string.
5//! The serialized form is that of `Option<String>`,
6//! and a nil is deserialized to the `Default` value. For JSON, this means both
7//! quoted string values and `null` are accepted. A value is always serialized
8//! as `Some<String>`.
9//! Note that this can be used for all primitive data types.
10//!
11//! [`from_str`]: super::from_str
12//! [`allow_null`]: super::allow_null
13
14use core::fmt::Display;
15use core::str::FromStr;
16
17use serde::{de::Error as _, Deserialize, Deserializer, Serializer};
18
19use crate::prelude::*;
20use crate::serializers::cow_str::CowStr;
21
22/// Deserialize a nullable string into T
23pub fn deserialize<'de, D, T>(deserializer: D) -> Result<T, D::Error>
24where
25 D: Deserializer<'de>,
26 T: FromStr + Default,
27 <T as FromStr>::Err: Display,
28{
29 match <Option<CowStr<'_>>>::deserialize(deserializer)? {
30 Some(s) => s.parse::<T>().map_err(D::Error::custom),
31 None => Ok(T::default()),
32 }
33}
34
35/// Serialize from T into string
36pub fn serialize<S, T>(value: &T, serializer: S) -> Result<S::Ok, S::Error>
37where
38 S: Serializer,
39 T: Display,
40{
41 serializer.serialize_some(&value.to_string())
42}