summaryrefslogtreecommitdiffstats
path: root/third_party/rust/unic-langid-impl/src/serde.rs
diff options
context:
space:
mode:
authorDaniel Baumann <daniel.baumann@progress-linux.org>2024-04-19 00:47:55 +0000
committerDaniel Baumann <daniel.baumann@progress-linux.org>2024-04-19 00:47:55 +0000
commit26a029d407be480d791972afb5975cf62c9360a6 (patch)
treef435a8308119effd964b339f76abb83a57c29483 /third_party/rust/unic-langid-impl/src/serde.rs
parentInitial commit. (diff)
downloadfirefox-26a029d407be480d791972afb5975cf62c9360a6.tar.xz
firefox-26a029d407be480d791972afb5975cf62c9360a6.zip
Adding upstream version 124.0.1.upstream/124.0.1
Signed-off-by: Daniel Baumann <daniel.baumann@progress-linux.org>
Diffstat (limited to 'third_party/rust/unic-langid-impl/src/serde.rs')
-rw-r--r--third_party/rust/unic-langid-impl/src/serde.rs60
1 files changed, 60 insertions, 0 deletions
diff --git a/third_party/rust/unic-langid-impl/src/serde.rs b/third_party/rust/unic-langid-impl/src/serde.rs
new file mode 100644
index 0000000000..faac0b0288
--- /dev/null
+++ b/third_party/rust/unic-langid-impl/src/serde.rs
@@ -0,0 +1,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(())
+}