use std::{fmt, marker::PhantomData};
use serde::{de, Deserialize, Deserializer};
#[inline]
pub fn is_default<E: Default + PartialEq>(e: &E) -> bool {
e == &E::default()
}
pub fn bool_or_struct<'de, T, D>(deserializer: D) -> Result<T, D::Error>
where
T: Deserialize<'de> + From<bool>,
D: Deserializer<'de>,
{
struct BoolOrStruct<T>(PhantomData<fn() -> T>);
impl<'de, T> de::Visitor<'de> for BoolOrStruct<T>
where
T: Deserialize<'de> + From<bool>,
{
type Value = T;
fn expecting(&self, formatter: &mut fmt::Formatter) -> fmt::Result {
formatter.write_str("bool or map")
}
fn visit_bool<E>(self, value: bool) -> Result<T, E>
where
E: de::Error,
{
Ok(value.into())
}
fn visit_map<M>(self, map: M) -> Result<T, M::Error>
where
M: de::MapAccess<'de>,
{
Deserialize::deserialize(de::value::MapAccessDeserializer::new(map))
}
}
deserializer.deserialize_any(BoolOrStruct(PhantomData))
}
pub mod ascii_char {
use serde::{de, Deserialize, Deserializer, Serializer};
pub fn deserialize<'de, D>(deserializer: D) -> Result<u8, D::Error>
where
D: Deserializer<'de>,
{
let character = char::deserialize(deserializer)?;
if character.is_ascii() {
Ok(character as u8)
} else {
Err(de::Error::custom(format!(
"invalid character: {character}, expected character in ASCII range"
)))
}
}
pub fn serialize<S>(character: &u8, serializer: S) -> Result<S::Ok, S::Error>
where
S: Serializer,
{
serializer.serialize_char(*character as char)
}
#[cfg(test)]
mod tests {
use serde::{Deserialize, Serialize};
#[derive(Deserialize, Serialize)]
struct Foo {
#[serde(with = "super")]
character: u8,
}
#[test]
fn test_deserialize_ascii_valid() {
let foo = serde_json::from_str::<Foo>(r#"{ "character": "\n" }"#).unwrap();
assert_eq!(foo.character, b'\n');
}
#[test]
fn test_deserialize_ascii_invalid_range() {
assert!(serde_json::from_str::<Foo>(r#"{ "character": "ß" }"#).is_err());
}
#[test]
fn test_deserialize_ascii_invalid_character() {
assert!(serde_json::from_str::<Foo>(r#"{ "character": 0 }"#).is_err());
}
#[test]
fn test_serialize_ascii() {
let foo = Foo { character: b'\n' };
assert_eq!(
serde_json::to_string(&foo).unwrap(),
r#"{"character":"\n"}"#
);
}
}
}