Skip to content

Commit

Permalink
Feature-gated serde impls for Triple (#86)
Browse files Browse the repository at this point in the history
* Feature-gated serde impls for Triple
  • Loading branch information
akesson authored Feb 10, 2023
1 parent 3a4fc54 commit 13e7ae8
Show file tree
Hide file tree
Showing 2 changed files with 54 additions and 0 deletions.
7 changes: 7 additions & 0 deletions Cargo.toml
Original file line number Diff line number Diff line change
Expand Up @@ -11,8 +11,15 @@ license = "Apache-2.0 WITH LLVM-exception"
repository = "https://github.com/bytecodealliance/target-lexicon"
edition = "2018"

[dependencies]
serde = { version = "1.0", optional = true }

[dev-dependencies]
serde_json = "1.0"

[features]
default = []
serde_support = ["serde", "std"]
std = []

[badges]
Expand Down
47 changes: 47 additions & 0 deletions src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -59,3 +59,50 @@ impl Default for DefaultToUnknown {
Self(Triple::unknown())
}
}

// For some reason, the below `serde` impls don't work when they're in the
// `triple` module.

#[cfg(feature = "serde_support")]
impl serde::Serialize for Triple {
fn serialize<S: serde::Serializer>(&self, serializer: S) -> Result<S::Ok, S::Error> {
serializer.serialize_str(&self.to_string())
}
}

#[cfg(feature = "serde_support")]
impl<'de> serde::de::Deserialize<'de> for Triple {
fn deserialize<D: serde::de::Deserializer<'de>>(deserializer: D) -> Result<Self, D::Error> {
let s = String::deserialize(deserializer)?;
s.parse().map_err(serde::de::Error::custom)
}
}

#[cfg(feature = "serde_support")]
#[test]
fn test_serialize() {
let triples: Vec<Triple> = vec![
"x86_64-unknown-linux-gnu".parse().unwrap(),
"i686-pc-windows-gnu".parse().unwrap(),
];

let json = serde_json::to_string(&triples).unwrap();
assert_eq!(
json,
r#"["x86_64-unknown-linux-gnu","i686-pc-windows-gnu"]"#
);
}

#[cfg(feature = "serde_support")]
#[test]
fn test_deserialize() {
let triples: Vec<Triple> = vec![
"x86_64-unknown-linux-gnu".parse().unwrap(),
"i686-pc-windows-gnu".parse().unwrap(),
];

let vals: Vec<Triple> =
serde_json::from_str(r#"["x86_64-unknown-linux-gnu","i686-pc-windows-gnu"]"#).unwrap();

assert_eq!(vals, triples);
}

0 comments on commit 13e7ae8

Please sign in to comment.