Skip to content

Commit

Permalink
Merge 1450d0a into 9886b73
Browse files Browse the repository at this point in the history
  • Loading branch information
XAMPPRocky authored May 5, 2020
2 parents 9886b73 + 1450d0a commit 4bfbff0
Show file tree
Hide file tree
Showing 3 changed files with 64 additions and 0 deletions.
2 changes: 2 additions & 0 deletions unic-langid-impl/src/lib.rs
Original file line number Diff line number Diff line change
@@ -1,3 +1,5 @@
#[cfg(feature = "serde")]
mod serde;
mod errors;
mod layout_table;
#[cfg(feature = "likelysubtags")]
Expand Down
61 changes: 61 additions & 0 deletions unic-langid-impl/src/serde.rs
Original file line number Diff line number Diff line change
@@ -0,0 +1,61 @@
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(())
}

1 change: 1 addition & 0 deletions unic-langid/Cargo.toml
Original file line number Diff line number Diff line change
Expand Up @@ -24,6 +24,7 @@ unic-langid-macros = { version = "0.8", path = "../unic-langid-macros" }

[features]
default = []
serde = ["unic-langid-impl/serde"]

# Provide macros.
macros = ["unic-langid-macros"]
Expand Down

0 comments on commit 4bfbff0

Please sign in to comment.