Skip to content

Commit

Permalink
feat: add serialize feature with serde
Browse files Browse the repository at this point in the history
Signed-off-by: Jérémie Drouet <[email protected]>
  • Loading branch information
jdrouet committed Jul 22, 2021
1 parent f422521 commit e71cec4
Show file tree
Hide file tree
Showing 3 changed files with 139 additions and 1 deletion.
80 changes: 80 additions & 0 deletions Cargo.lock

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

8 changes: 8 additions & 0 deletions Cargo.toml
Original file line number Diff line number Diff line change
Expand Up @@ -10,5 +10,13 @@ readme = "readme.md"

# See more keys and their definitions at https://doc.rust-lang.org/cargo/reference/manifest.html

[features]
default = ["serialize"]
serialize = ["serde"]

[dependencies]
cidr-utils = "^0.5"
serde = { version = "^1.0", features = ["derive"], optional = true }

[dev-dependencies]
serde_json = "^1.0"
52 changes: 51 additions & 1 deletion src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -11,6 +11,17 @@ pub enum NoProxyItem {
Plain(String),
}

impl ToString for NoProxyItem {
fn to_string(&self) -> String {
match self {
Self::Wildcard => "*".into(),
Self::IpCidr(value, _) => value.clone(),
Self::WithDot(value, _, _) => value.clone(),
Self::Plain(value) => value.clone(),
}
}
}

impl From<String> for NoProxyItem {
fn from(value: String) -> Self {
if value == "*" {
Expand Down Expand Up @@ -68,7 +79,7 @@ impl NoProxyItem {
}
}

#[derive(Clone, Debug, Default)]
#[derive(Clone, Debug, Default, PartialEq)]
pub struct NoProxy {
content: HashSet<NoProxyItem>,
has_wildcard: bool,
Expand Down Expand Up @@ -119,6 +130,36 @@ impl NoProxy {
}
}

impl ToString for NoProxy {
fn to_string(&self) -> String {
self.content
.iter()
.map(ToString::to_string)
.collect::<Vec<_>>()
.join(",")
}
}

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

#[cfg(feature = "serialize")]
impl<'de> serde::Deserialize<'de> for NoProxy {
fn deserialize<D>(deserializer: D) -> Result<Self, D::Error>
where
D: serde::Deserializer<'de>,
{
String::deserialize(deserializer).map(Self::from)
}
}

#[cfg(test)]
mod tests {
use super::*;
Expand Down Expand Up @@ -200,4 +241,13 @@ mod tests {
should_match(pattern, "[2001:db8:a0b:12f0::1]");
should_match(pattern, "10.124.7.8");
}

#[cfg(feature = "serialize")]
#[test]
fn serialization() {
let proxy = NoProxy::from("foo.bar,1.2.3.4");
let json = serde_json::to_string(&proxy).unwrap();
let result: NoProxy = serde_json::from_str(&json).unwrap();
assert_eq!(proxy, result);
}
}

0 comments on commit e71cec4

Please sign in to comment.