1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
use std::fmt;

use index_vec::Idx;

use crate::{
    bitset::BitSet, pointer::PointerFamily, Captures, FromIndexicalIterator, IndexedDomain,
    IndexedValue, ToIndex,
};

/// An unordered collections of `T`s, implemented with a bit-set.
pub struct IndexSet<'a, T: IndexedValue + 'a, S: BitSet, P: PointerFamily<'a>> {
    set: S,
    domain: P::Pointer<IndexedDomain<T>>,
}

impl<'a, T, S, P> IndexSet<'a, T, S, P>
where
    T: IndexedValue + 'a,
    S: BitSet,
    P: PointerFamily<'a>,
{
    /// Creates an empty index set.
    pub fn new(domain: &P::Pointer<IndexedDomain<T>>) -> Self {
        IndexSet {
            set: S::empty(domain.len()),
            domain: domain.clone(),
        }
    }

    /// Returns an iterator over all the indices contained in `self`.
    #[inline]
    pub fn indices(&self) -> impl Iterator<Item = T::Index> + '_ {
        self.set.iter().map(T::Index::from_usize)
    }

    /// Returns an iterator over all the objects contained in `self`.
    #[inline]
    pub fn iter(&self) -> impl Iterator<Item = &T> + Captures<'a> + '_ {
        self.indices().map(move |idx| self.domain.value(idx))
    }

    /// Returns an iterator over the pairs of indices and objects contained in `self`.
    #[inline]
    pub fn iter_enumerated(&self) -> impl Iterator<Item = (T::Index, &T)> + Captures<'a> + '_ {
        self.indices().map(move |idx| (idx, self.domain.value(idx)))
    }

    /// Returns true if `index` is contained in `self`.
    #[inline]
    pub fn contains<M>(&self, index: impl ToIndex<T, M>) -> bool {
        let elem = index.to_index(&self.domain);
        self.set.contains(elem.index())
    }

    /// Returns the number of elements in `self`.
    #[inline]
    pub fn len(&self) -> usize {
        self.set.len()
    }

    /// Return true if `self` has no elements.
    #[inline]
    pub fn is_empty(&self) -> bool {
        self.len() == 0
    }

    /// Returns true if every element in `other` is also in `self`.
    #[inline]
    pub fn is_superset(&self, other: &IndexSet<'a, T, S, P>) -> bool {
        self.set.superset(&other.set)
    }

    /// Adds the element `elt` to `self`, returning true if `self` changed.
    #[inline]
    pub fn insert<M>(&mut self, elt: impl ToIndex<T, M>) -> bool {
        let elt = elt.to_index(&self.domain);
        self.set.insert(elt.index())
    }

    /// Adds each element of `other` to `self`.
    #[inline]
    pub fn union(&mut self, other: &IndexSet<'a, T, S, P>) {
        self.set.union(&other.set);
    }

    /// Adds each element of `other` to `self`, returning true if `self` changed.
    #[inline]
    pub fn union_changed(&mut self, other: &IndexSet<'a, T, S, P>) -> bool {
        self.set.union_changed(&other.set)
    }

    /// Removes every element of `other` from `self`.
    #[inline]
    pub fn subtract(&mut self, other: &IndexSet<'a, T, S, P>) {
        self.set.subtract(&other.set)
    }

    /// Removes every element of `other` from `self`, returning true if `self` changed.
    #[inline]
    pub fn subtract_changed(&mut self, other: &IndexSet<'a, T, S, P>) -> bool {
        self.set.subtract_changed(&other.set)
    }

    /// Removes every element of `self` not in `other`.
    #[inline]
    pub fn intersect(&mut self, other: &IndexSet<'a, T, S, P>) {
        self.set.intersect(&other.set)
    }

    /// Removes every element of `self` not in `other`, returning true if `self` changed.
    #[inline]
    pub fn intersect_changed(&mut self, other: &IndexSet<'a, T, S, P>) -> bool {
        self.set.intersect_changed(&other.set)
    }

    /// Adds every element of the domain to `self`.
    #[inline]
    pub fn insert_all(&mut self) {
        self.set.insert_all()
    }

    /// Removes every element from `self`.
    #[inline]
    pub fn clear(&mut self) {
        self.set.clear();
    }

    /// Returns a reference to the inner set.
    #[inline]
    pub fn inner(&self) -> &S {
        &self.set
    }
}

impl<'a, T, S, P> fmt::Debug for IndexSet<'a, T, S, P>
where
    T: IndexedValue + fmt::Debug + 'a,
    S: BitSet,
    P: PointerFamily<'a>,
{
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        f.debug_set().entries(self.iter()).finish()
    }
}

impl<'a, T, S, P> PartialEq for IndexSet<'a, T, S, P>
where
    T: IndexedValue + 'a,
    S: BitSet,
    P: PointerFamily<'a>,
{
    fn eq(&self, other: &Self) -> bool {
        self.set == other.set
    }
}

impl<'a, T, S, P> Eq for IndexSet<'a, T, S, P>
where
    T: IndexedValue + 'a,
    S: BitSet,
    P: PointerFamily<'a>,
{
}

impl<'a, T, S, P> Clone for IndexSet<'a, T, S, P>
where
    T: IndexedValue + 'a,
    S: BitSet,
    P: PointerFamily<'a>,
{
    fn clone(&self) -> Self {
        IndexSet {
            set: self.set.clone(),
            domain: self.domain.clone(),
        }
    }

    fn clone_from(&mut self, source: &Self) {
        self.set.copy_from(&source.set);
        self.domain = source.domain.clone();
    }
}

impl<'a, T, U, S, M, P> FromIndexicalIterator<'a, T, P, M, U> for IndexSet<'a, T, S, P>
where
    T: IndexedValue + 'a,
    S: BitSet,
    P: PointerFamily<'a>,
    U: ToIndex<T, M>,
{
    fn from_indexical_iter(
        iter: impl Iterator<Item = U>,
        domain: &P::Pointer<IndexedDomain<T>>,
    ) -> Self {
        let mut set = IndexSet::new(domain);
        for s in iter {
            set.insert(s);
        }
        set
    }
}

#[cfg(test)]
mod test {
    use crate::{test_utils::TestIndexSet, IndexedDomain, IndexicalIteratorExt};
    use std::rc::Rc;

    fn mk(s: &str) -> String {
        s.to_string()
    }

    #[test]
    fn test_indexset() {
        let d = Rc::new(IndexedDomain::from_iter([mk("a"), mk("b"), mk("c")]));
        let mut s = TestIndexSet::new(&d);
        s.insert(mk("a"));
        let b = d.index(&mk("b"));
        s.insert(b);
        assert!(s.contains(mk("a")));
        assert!(s.contains(mk("b")));
        assert_eq!(s.len(), 2);

        assert_eq!(
            [mk("a"), mk("b")]
                .into_iter()
                .collect_indexical::<TestIndexSet<_>>(&d),
            s
        );
        assert_eq!(format!("{s:?}"), r#"{"a", "b"}"#)
    }

    #[cfg(feature = "bitvec")]
    #[test]
    fn test_indexset_reffamily() {
        let d = &IndexedDomain::from_iter([mk("a"), mk("b"), mk("c")]);
        let mut s = crate::bitset::bitvec::RefIndexSet::new(&d);
        s.insert(mk("a"));
        assert!(s.contains(mk("a")));

        let s2 = s.clone();
        assert!(std::ptr::eq(s.domain, s2.domain));
    }
}