no_proxy/
serialize.rs

1use crate::NoProxy;
2use serde::{de, Deserialize, Deserializer};
3use serde::{ser::SerializeSeq, Serialize, Serializer};
4
5impl Serialize for NoProxy {
6    fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error>
7    where
8        S: Serializer,
9    {
10        let mut seq = serializer.serialize_seq(Some(self.content.len()))?;
11        for elt in self.content.iter() {
12            seq.serialize_element(elt.as_str())?;
13        }
14        seq.end()
15    }
16}
17
18struct NoProxyVisitor;
19
20impl<'de> de::Visitor<'de> for NoProxyVisitor {
21    type Value = Vec<String>;
22
23    fn expecting(&self, formatter: &mut std::fmt::Formatter) -> std::fmt::Result {
24        formatter.write_str("string or list of strings")
25    }
26
27    fn visit_str<E>(self, value: &str) -> Result<Self::Value, E>
28    where
29        E: de::Error,
30    {
31        Ok(value
32            .split(',')
33            .map(|item| item.trim().to_string())
34            .collect())
35    }
36
37    fn visit_seq<S>(self, visitor: S) -> Result<Self::Value, S::Error>
38    where
39        S: de::SeqAccess<'de>,
40    {
41        Deserialize::deserialize(de::value::SeqAccessDeserializer::new(visitor))
42    }
43}
44
45impl<'de> Deserialize<'de> for NoProxy {
46    fn deserialize<D>(deserializer: D) -> Result<Self, D::Error>
47    where
48        D: Deserializer<'de>,
49    {
50        deserializer
51            .deserialize_any(NoProxyVisitor)
52            .map(|list| NoProxy::from_iterator(list.into_iter()))
53    }
54}
55
56#[cfg(test)]
57mod tests {
58    use super::*;
59
60    #[cfg(feature = "serialize")]
61    #[test]
62    fn serialization() {
63        let proxy = NoProxy::from("foo.bar,1.2.3.4");
64        let json = serde_json::to_string(&proxy).unwrap();
65        // parsing a comma separated string
66        let result: NoProxy = serde_json::from_str(&json).unwrap();
67        assert_eq!(proxy, result);
68        assert_eq!(result.content.len(), 2);
69        // parsing an array of strings
70        let result: NoProxy = serde_json::from_str(r#"["foo.bar", "1.2.3.4"]"#).unwrap();
71        assert_eq!(proxy, result);
72        assert_eq!(result.content.len(), 2);
73    }
74}