Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Serde impls for Comparator #282

Merged
merged 1 commit into from Jun 29, 2022
Merged
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Jump to
Jump to file
Failed to load files.
Diff view
Diff view
37 changes: 36 additions & 1 deletion src/serde.rs
@@ -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)
}
}