1
use std::fmt;
2
use std::slice::Iter;
3

            
4
use itertools::Itertools;
5

            
6
#[macro_export]
7
macro_rules! vecset {
8
    () => {
9
        $crate::VecSet::new()
10
    };
11
    ($elem:expr; $n:expr) => {{
12
        let mut __set = $crate::VecSet::new();
13
        let __count: usize = $n;
14
        if __count > 0 {
15
            __set.insert($elem);
16
        }
17
        __set
18
    }};
19
    ($($x:expr),+ $(,)?) => {{
20
        let mut __set = $crate::VecSet::new();
21
        $( let _ = __set.insert($x); )*
22
        __set
23
    }};
24
}
25

            
26
///
27
/// A set that is internally represented by a sorted vector. Mostly useful for
28
/// a compact representation of sets that are not changed often.
29
///
30
#[derive(Clone, PartialEq, Eq, PartialOrd, Ord, Hash)]
31
pub struct VecSet<T> {
32
    /// The internal storage with the invariant that the array is sorted.
33
    sorted_array: Vec<T>,
34
}
35

            
36
impl<T: Ord> VecSet<T> {
37
    /// Creates a new, empty VecSet.
38
6984
    pub fn new() -> Self {
39
6984
        Self {
40
6984
            sorted_array: Vec::new(),
41
6984
        }
42
6984
    }
43

            
44
    /// Creates a VecSet from the given vector without assuming anything of the given vector.
45
    pub fn from_vec(mut vec: Vec<T>) -> Self {
46
        vec.sort();
47
        vec.dedup();
48
        Self { sorted_array: vec }
49
    }
50

            
51
    /// Returns the capacity of the set.
52
    pub fn capacity(&self) -> usize {
53
        self.sorted_array.capacity()
54
    }
55

            
56
    /// Returns true iff the set contains the given element.
57
    pub fn contains(&self, element: &T) -> bool {
58
        self.sorted_array.binary_search(element).is_ok()
59
    }
60

            
61
    /// Clears the set, removing all elements.
62
    pub fn clear(&mut self) {
63
        self.sorted_array.clear();
64
    }
65

            
66
    /// Retains only the elements specified by the predicate.
67
4015
    pub fn retain<F>(&mut self, mut f: F)
68
4015
    where
69
4015
        F: FnMut(&T) -> bool,
70
    {
71
        // Removing elements does not change the order.
72
11012
        self.sorted_array.retain(|e| f(e));
73
4015
    }
74

            
75
    /// Returns true iff this set is a subset of the other set.
76
55904
    pub fn is_subset(&self, other: &VecSet<T>) -> bool {
77
55904
        let mut self_iter = self.sorted_array.iter();
78
55904
        let mut other_iter = other.sorted_array.iter();
79

            
80
        // Traverse both sets in order, checking that all elements of self are in other.
81
55904
        let mut self_next = self_iter.next();
82
55904
        let mut other_next = other_iter.next();
83

            
84
103086
        while let Some(self_val) = self_next {
85
102366
            match other_next {
86
91414
                Some(other_val) => {
87
91414
                    if self_val == other_val {
88
5330
                        self_next = self_iter.next();
89
5330
                        other_next = other_iter.next();
90
86084
                    } else if self_val > other_val {
91
41852
                        other_next = other_iter.next();
92
41852
                    } else {
93
44232
                        return false; // self_val < other_val
94
                    }
95
                }
96
10952
                None => return false, // other is exhausted
97
            }
98
        }
99

            
100
720
        true
101
55904
    }
102

            
103
    /// Returns a new set only containing the given element.
104
5505
    pub fn singleton(element: T) -> Self {
105
5505
        Self {
106
5505
            sorted_array: vec![element],
107
5505
        }
108
5505
    }
109

            
110
    /// Returns true iff the set is empty.
111
5958
    pub fn is_empty(&self) -> bool {
112
5958
        self.sorted_array.is_empty()
113
5958
    }
114

            
115
    /// Inserts the given element into the set, returns true iff the element was
116
    /// inserted.
117
17472
    pub fn insert(&mut self, element: T) -> bool {
118
        // Finds the location where to insert the element to keep the array sorted.
119
17472
        if let Err(position) = self.sorted_array.binary_search(&element) {
120
16884
            self.sorted_array.insert(position, element);
121
16884
            return true;
122
588
        }
123

            
124
588
        false
125
17472
    }
126

            
127
    /// Returns an iterator over the elements in the set, they are yielded in sorted order.
128
10960
    pub fn iter(&self) -> impl Iterator<Item = &T> {
129
10960
        self.sorted_array.iter()
130
10960
    }
131

            
132
    /// Returns the number of elements in the set.
133
1
    pub fn len(&self) -> usize {
134
1
        self.sorted_array.len()
135
1
    }
136

            
137
    /// Consumes the set and returns a vector with the elements in sorted order.
138
    pub fn to_vec(self) -> Vec<T> {
139
        self.sorted_array
140
    }
141
}
142

            
143
impl<T: Ord> Default for VecSet<T> {
144
    fn default() -> Self {
145
        Self::new()
146
    }
147
}
148

            
149
impl<'a, T> IntoIterator for &'a VecSet<T> {
150
    type Item = &'a T;
151
    type IntoIter = Iter<'a, T>;
152

            
153
294
    fn into_iter(self) -> Self::IntoIter {
154
294
        self.sorted_array.iter()
155
294
    }
156
}
157

            
158
impl<T: fmt::Debug> fmt::Debug for VecSet<T> {
159
2
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
160
2
        write!(f, "{{{:?}}}", self.sorted_array.iter().format(", "))
161
2
    }
162
}