Skip to content

Commit

Permalink
Serde impls for Comparator
Browse files Browse the repository at this point in the history
  • Loading branch information
dtolnay committed Jun 29, 2022
1 parent ce0ab4d commit d0b6c7e
Showing 1 changed file with 36 additions and 1 deletion.
37 changes: 36 additions & 1 deletion src/serde.rs
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
use crate::{Version, VersionReq};
use crate::{Comparator, Version, VersionReq};
use core::fmt;
use serde::de::{Deserialize, Deserializer, Error, Visitor};
use serde::ser::{Serialize, Serializer};
Expand All @@ -21,6 +21,15 @@ impl Serialize for VersionReq {
}
}

impl Serialize for Comparator {
fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error>
where
S: Serializer,
{
serializer.collect_str(self)
}
}

impl<'de> Deserialize<'de> for Version {
fn deserialize<D>(deserializer: D) -> Result<Self, D::Error>
where
Expand Down Expand Up @@ -72,3 +81,29 @@ impl<'de> Deserialize<'de> for VersionReq {
deserializer.deserialize_str(VersionReqVisitor)
}
}

impl<'de> Deserialize<'de> for Comparator {
fn deserialize<D>(deserializer: D) -> Result<Self, D::Error>
where
D: Deserializer<'de>,
{
struct ComparatorVisitor;

impl<'de> Visitor<'de> for ComparatorVisitor {
type Value = Comparator;

fn expecting(&self, formatter: &mut fmt::Formatter) -> fmt::Result {
formatter.write_str("semver comparator")
}

fn visit_str<E>(self, string: &str) -> Result<Self::Value, E>
where
E: Error,
{
string.parse().map_err(Error::custom)
}
}

deserializer.deserialize_str(ComparatorVisitor)
}
}

0 comments on commit d0b6c7e

Please sign in to comment.