Skip to main content

wp_specs/
pattern.rs

1use serde::de::SeqAccess;
2use serde::ser::SerializeSeq;
3use serde::{Deserialize, Deserializer, Serialize, Serializer};
4use std::fmt;
5use std::fmt::{Debug, Display, Formatter};
6use wildmatch::WildMatch;
7
8/// Wildcard pattern array, serialized as array of strings.
9/// This type is used in spec/config layers to express match lists
10/// without depending on the language/runtime crates.
11#[derive(PartialEq, Default, Clone)]
12pub struct WildArray(pub Vec<WildMatch>);
13
14impl AsRef<Vec<WildMatch>> for WildArray {
15    fn as_ref(&self) -> &Vec<WildMatch> {
16        &self.0
17    }
18}
19
20impl Debug for WildArray {
21    fn fmt(&self, f: &mut Formatter<'_>) -> fmt::Result {
22        write!(f, "{:?}", self.0)
23    }
24}
25
26impl Display for WildArray {
27    fn fmt(&self, f: &mut Formatter<'_>) -> fmt::Result {
28        for val in &self.0 {
29            write!(f, "{}", val)?;
30        }
31        Ok(())
32    }
33}
34
35impl WildArray {
36    pub fn new(val: &str) -> WildArray {
37        WildArray(vec![WildMatch::new(val)])
38    }
39
40    pub fn new1<T: Into<String>>(val: Vec<T>) -> WildArray {
41        let val: Vec<WildMatch> = val.into_iter().map(|v| WildMatch::new(&v.into())).collect();
42        WildArray(val)
43    }
44
45    pub fn is_empty(&self) -> bool {
46        self.0.is_empty()
47    }
48}
49
50impl Serialize for WildArray {
51    fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error>
52    where
53        S: Serializer,
54    {
55        let mut seq = serializer.serialize_seq(Some(self.0.len()))?;
56        for e in &self.0 {
57            seq.serialize_element(&e.to_string())?;
58        }
59        seq.end()
60    }
61}
62
63impl<'de> Deserialize<'de> for WildArray {
64    fn deserialize<D>(deserializer: D) -> Result<Self, D::Error>
65    where
66        D: Deserializer<'de>,
67    {
68        struct WildMatchArray;
69
70        impl<'de> serde::de::Visitor<'de> for WildMatchArray {
71            type Value = WildArray;
72
73            fn expecting(&self, formatter: &mut Formatter) -> fmt::Result {
74                formatter.write_str("a sequence of wildcard patterns")
75            }
76
77            fn visit_seq<A>(self, mut seq: A) -> Result<Self::Value, A::Error>
78            where
79                A: SeqAccess<'de>,
80            {
81                let mut vec = Vec::new();
82                while let Ok(Some(element)) = seq.next_element::<String>() {
83                    vec.push(WildMatch::new(&element));
84                }
85                Ok(WildArray(vec))
86            }
87        }
88
89        deserializer.deserialize_seq(WildMatchArray)
90    }
91}