capgrok/
set.rs

1use serde::{Deserialize, Deserializer, Serialize, Serializer};
2
3#[derive(Clone, Debug, Default)]
4/// A simple Set implementation that de-duplicates elements by [`Eq`].
5///
6/// Set is a glorified Vec with insertion checks, so to perform any read actions on a Set you
7/// should use the [`AsRef`] implementation to convert to a slice.
8pub struct Set<T: Eq>(Vec<T>);
9
10impl<T: Eq, S: Into<T>> FromIterator<S> for Set<T> {
11    fn from_iter<I>(i: I) -> Self
12    where
13        I: IntoIterator<Item = S>,
14    {
15        let iter = i.into_iter();
16        let inner = Vec::with_capacity(iter.size_hint().0);
17        let mut this = Self(inner);
18        this.insert_all(iter);
19        this
20    }
21}
22
23impl<T: Eq> IntoIterator for Set<T> {
24    type Item = T;
25    type IntoIter = std::vec::IntoIter<T>;
26
27    fn into_iter(self) -> Self::IntoIter {
28        self.0.into_iter()
29    }
30}
31
32impl<T: Eq> AsRef<[T]> for Set<T> {
33    fn as_ref(&self) -> &[T] {
34        &self.0
35    }
36}
37
38impl<T: Eq> Set<T> {
39    /// Insert a new element.
40    ///
41    /// Returns true if inserted, false if the element already exists in the set.
42    pub fn insert<S: Into<T>>(&mut self, s: S) -> bool {
43        let t = s.into();
44        if !self.0.contains(&t) {
45            self.0.push(t);
46            return true;
47        }
48        false
49    }
50
51    /// Insert multiple new elements.
52    pub fn insert_all<I, S>(&mut self, ts: I)
53    where
54        I: IntoIterator<Item = S>,
55        S: Into<T>,
56    {
57        ts.into_iter().for_each(|t| {
58            self.insert(t);
59        })
60    }
61}
62
63impl<T: Eq + Serialize> Serialize for Set<T> {
64    fn serialize<S>(&self, s: S) -> Result<S::Ok, S::Error>
65    where
66        S: Serializer,
67    {
68        self.0.serialize(s)
69    }
70}
71
72impl<'de, T: Eq + Deserialize<'de>> Deserialize<'de> for Set<T> {
73    fn deserialize<D>(d: D) -> Result<Self, D::Error>
74    where
75        D: Deserializer<'de>,
76    {
77        Ok(Self(Deserialize::deserialize(d)?))
78    }
79}