Last active
April 18, 2024 11:43
-
-
Save afpro/e1b6551e82642674099c42ce596df7ec to your computer and use it in GitHub Desktop.
serde_as_text
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
pub mod as_text { | |
use std::{fmt::Display, str::FromStr}; | |
use serde::{de::Error as DeError, Deserialize, Deserializer, Serializer}; | |
#[derive(Deserialize)] | |
#[serde(untagged)] | |
enum OrText<'a, T> { | |
Data(T), | |
Text(&'a str), | |
} | |
pub fn serialize<T, S>(value: &T, ser: S) -> Result<S::Ok, S::Error> | |
where | |
T: Display, | |
S: Serializer, | |
{ | |
let value = format!("{}", value); | |
ser.serialize_str(&value) | |
} | |
pub fn deserialize<'de, T, D>(de: D) -> Result<T, D::Error> | |
where | |
T: Deserialize<'de> + FromStr, | |
T::Err: Display, | |
D: Deserializer<'de>, | |
{ | |
match <OrText<'de, T> as Deserialize<'de>>::deserialize(de)? { | |
OrText::Data(data) => Ok(data), | |
OrText::Text(text) => T::from_str(text) | |
.map_err(|err| DeError::custom(format!("parse text error {}", err))), | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment