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
159436
    pub fn new() -> Self {
38
159436
        Self {
39
159436
            sorted_array: Vec::new(),
40
159436
        }
41
159436
    }
42

            
43
    /// Returns the capacity of the set.
44
    pub fn capacity(&self) -> usize {
45
        self.sorted_array.capacity()
46
    }
47

            
48
    /// Returns true iff the set contains the given element.
49
    pub fn contains(&self, element: &T) -> bool {
50
        self.sorted_array.binary_search(element).is_ok()
51
    }
52

            
53
    /// Clears the set, removing all elements.
54
    pub fn clear(&mut self) {
55
        self.sorted_array.clear();
56
    }
57

            
58
    /// Retains only the elements specified by the predicate.
59
144519
    pub fn retain<F>(&mut self, mut f: F)
60
144519
    where
61
144519
        F: FnMut(&T) -> bool,
62
    {
63
        // Removing elements does not change the order.
64
216628
        self.sorted_array.retain(|e| f(e));
65
144519
    }
66

            
67
    /// Returns true iff this set is a subset of the other set.
68
339138
    pub fn is_subset(&self, other: &VecSet<T>) -> bool {
69
339138
        let mut self_iter = self.sorted_array.iter();
70
339138
        let mut other_iter = other.sorted_array.iter();
71

            
72
        // Traverse both sets in order, checking that all elements of self are in other.
73
339138
        let mut self_next = self_iter.next();
74
339138
        let mut other_next = other_iter.next();
75

            
76
744484
        while let Some(self_val) = self_next {
77
605756
            match other_next {
78
546550
                Some(other_val) => {
79
546550
                    if self_val == other_val {
80
203013
                        self_next = self_iter.next();
81
203013
                        other_next = other_iter.next();
82
343537
                    } else if self_val > other_val {
83
202333
                        other_next = other_iter.next();
84
202333
                    } else {
85
141204
                        return false; // self_val < other_val
86
                    }
87
                }
88
59206
                None => return false, // other is exhausted
89
            }
90
        }
91

            
92
138728
        true
93
339138
    }
94

            
95
    /// Returns a new set only containing the given element.
96
14495
    pub fn singleton(element: T) -> Self {
97
14495
        Self {
98
14495
            sorted_array: vec![element],
99
14495
        }
100
14495
    }
101

            
102
    /// Returns true iff the set is empty.
103
153810
    pub fn is_empty(&self) -> bool {
104
153810
        self.sorted_array.is_empty()
105
153810
    }
106

            
107
    /// Inserts the given element into the set, returns true iff the element was
108
    /// inserted.
109
348581
    pub fn insert(&mut self, element: T) -> bool {
110
        // Finds the location where to insert the element to keep the array sorted.
111
348581
        if let Err(position) = self.sorted_array.binary_search(&element) {
112
329662
            self.sorted_array.insert(position, element);
113
329662
            return true;
114
18919
        }
115

            
116
18919
        false
117
348581
    }
118

            
119
    /// Returns an iterator over the elements in the set, they are yielded in sorted order.
120
5588
    pub fn iter(&self) -> impl Iterator<Item = &T> {
121
5588
        self.sorted_array.iter()
122
5588
    }
123

            
124
    /// Returns the number of elements in the set.
125
1
    pub fn len(&self) -> usize {
126
1
        self.sorted_array.len()
127
1
    }
128
}
129

            
130
impl<T: Ord> Default for VecSet<T> {
131
    fn default() -> Self {
132
        Self::new()
133
    }
134
}
135

            
136
impl<'a, T> IntoIterator for &'a VecSet<T> {
137
    type Item = &'a T;
138
    type IntoIter = Iter<'a, T>;
139

            
140
153710
    fn into_iter(self) -> Self::IntoIter {
141
153710
        self.sorted_array.iter()
142
153710
    }
143
}
144

            
145
impl<T: fmt::Debug> fmt::Debug for VecSet<T> {
146
2
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
147
2
        write!(f, "{{{:?}}}", self.sorted_array.iter().format(", "))
148
2
    }
149
}