1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
|
use crate::LanguageIdentifier;
use serde::{Deserialize, Deserializer, Serialize, Serializer};
impl Serialize for LanguageIdentifier {
fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error>
where
S: Serializer,
{
serializer.serialize_str(&self.to_string())
}
}
impl<'de> Deserialize<'de> for LanguageIdentifier {
fn deserialize<D>(deserializer: D) -> Result<Self, D::Error>
where
D: Deserializer<'de>,
{
struct LanguageIdentifierVisitor;
impl<'de> serde::de::Visitor<'de> for LanguageIdentifierVisitor {
type Value = LanguageIdentifier;
fn expecting(&self, formatter: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
write!(formatter, "A valid Unicode Language Identifier")
}
fn visit_str<E>(self, s: &str) -> Result<Self::Value, E>
where
E: serde::de::Error,
{
s.parse::<LanguageIdentifier>()
.map_err(serde::de::Error::custom)
}
}
deserializer.deserialize_string(LanguageIdentifierVisitor)
}
}
#[test]
fn serialize() -> Result<(), Box<dyn std::error::Error>> {
let fr = serde_json::json!("fr".parse::<LanguageIdentifier>()?);
let en = serde_json::json!("en-US".parse::<LanguageIdentifier>()?);
assert_eq!(serde_json::to_string(&fr)?, r#""fr""#);
assert_eq!(serde_json::to_string(&en)?, r#""en-US""#);
Ok(())
}
#[test]
fn deserialize() -> Result<(), Box<dyn std::error::Error>> {
let fr = serde_json::from_str::<LanguageIdentifier>(r#""fr""#)?;
let en = serde_json::from_str::<LanguageIdentifier>(r#""en-US""#)?;
assert_eq!(fr, "fr".parse::<LanguageIdentifier>()?);
assert_eq!(en, "en-US".parse::<LanguageIdentifier>()?);
Ok(())
}
|