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
//! Set-union compound lattice.
//!
//! Merging set-union lattices is done by unioning the keys.

use std::cmp::Ordering;

use crate::{collections::Collection, tag};

use super::{Compare, ConvertFrom, Merge};

/// A set-union lattice.
///
/// `Tag` specifies what datastructure to use, allowing us to deal with different datastructures
/// generically.
#[repr(transparent)]
pub struct SetUnion<Tag, T>(Tag::Bind)
where
    Tag: tag::Tag1<T>;
impl<Tag, T> SetUnion<Tag, T>
where
    Tag: tag::Tag1<T>,
{
    /// Create a new `SetUnion` from a `Set`.
    pub fn new(val: Tag::Bind) -> Self {
        Self(val)
    }

    /// Create a new `SetUnion` from an `Into<Set>`.
    pub fn new_from(val: impl Into<Tag::Bind>) -> Self {
        Self::new(val.into())
    }
}

impl<TagSelf, TagOther, T> Merge<SetUnion<TagOther, T>> for SetUnion<TagSelf, T>
where
    TagSelf: tag::Tag1<T>,
    TagOther: tag::Tag1<T>,
    TagSelf::Bind: Collection<T, ()> + Extend<T>,
    TagOther::Bind: IntoIterator<Item = T>,
{
    fn merge(&mut self, other: SetUnion<TagOther, T>) -> bool {
        let old_len = self.0.len();
        self.0.extend(other.0);
        self.0.len() > old_len
    }
}

impl<TagSelf, TagOther, T> ConvertFrom<SetUnion<TagOther, T>> for SetUnion<TagSelf, T>
where
    TagSelf: tag::Tag1<T>,
    TagOther: tag::Tag1<T>,
    TagSelf::Bind: FromIterator<T>,
    TagOther::Bind: Collection<T, ()>,
{
    fn from(other: SetUnion<TagOther, T>) -> Self {
        Self(
            other
                .0
                .into_entries()
                .map(|(t_other, ())| t_other)
                .collect(),
        )
    }
}

impl<Tag, T> Default for SetUnion<Tag, T>
where
    Tag: tag::Tag1<T>,
    Tag::Bind: Default,
{
    fn default() -> Self {
        Self(Default::default())
    }
}

impl<TagSelf, TagOther, T> Compare<SetUnion<TagOther, T>> for SetUnion<TagSelf, T>
where
    TagSelf: tag::Tag1<T>,
    TagOther: tag::Tag1<T>,
    TagSelf::Bind: Collection<T, ()>,
    TagOther::Bind: Collection<T, ()>,
{
    fn compare(&self, other: &SetUnion<TagOther, T>) -> Option<Ordering> {
        match self.0.len().cmp(&other.0.len()) {
            Ordering::Greater => {
                if other.0.keys().all(|key| self.0.get(key).is_some()) {
                    Some(Ordering::Greater)
                } else {
                    None
                }
            }
            Ordering::Equal => {
                if self.0.keys().all(|key| other.0.get(key).is_some()) {
                    Some(Ordering::Equal)
                } else {
                    None
                }
            }
            Ordering::Less => {
                if self.0.keys().all(|key| other.0.get(key).is_some()) {
                    Some(Ordering::Less)
                } else {
                    None
                }
            }
        }
    }
}

/// [`std::collections::HashSet`]-backed [`SetUnion`] lattice.
pub type SetUnionHashSet<T> = SetUnion<tag::HASH_SET, T>;

/// [`std::collections::BTreeSet`]-backed [`SetUnion`] lattice.
pub type SetUnionBTreeSet<T> = SetUnion<tag::BTREE_SET, T>;

/// [`Vec`]-backed [`SetUnion`] lattice.
pub type SetUnionVec<T> = SetUnion<tag::VEC, T>;

/// Array-backed [`SetUnion`] lattice.
pub type SetUnionArray<T, const N: usize> = SetUnion<tag::ARRAY<N>, T>;

/// [`crate::collections::MaskedArray`]-backed [`SetUnion`] lattice.
pub type SetUnionMaskedArray<T, const N: usize> = SetUnion<tag::MASKED_ARRAY<N>, T>;

/// [`crate::collections::Single`]-backed [`SetUnion`] lattice.
pub type SetUnionSingle<T> = SetUnion<tag::SINGLE, T>;

/// [`Option`]-backed [`SetUnion`] lattice.
pub type SetUnionOption<T> = SetUnion<tag::OPTION, T>;

#[cfg(test)]
mod test {
    use super::*;

    use crate::collections::Single;

    #[test]
    fn test_set_union() {
        let mut my_set_a = SetUnion::<tag::HASH_SET, &str>(Default::default());
        let my_set_b = SetUnion::<tag::BTREE_SET, &str>(Default::default());
        let my_set_c = SetUnion::<tag::SINGLE, _>(Single("hello world"));

        assert_eq!(Some(Ordering::Equal), my_set_a.compare(&my_set_a));
        assert_eq!(Some(Ordering::Equal), my_set_a.compare(&my_set_b));
        assert_eq!(Some(Ordering::Less), my_set_a.compare(&my_set_c));
        assert_eq!(Some(Ordering::Equal), my_set_b.compare(&my_set_a));
        assert_eq!(Some(Ordering::Equal), my_set_b.compare(&my_set_b));
        assert_eq!(Some(Ordering::Less), my_set_b.compare(&my_set_c));
        assert_eq!(Some(Ordering::Greater), my_set_c.compare(&my_set_a));
        assert_eq!(Some(Ordering::Greater), my_set_c.compare(&my_set_b));
        assert_eq!(Some(Ordering::Equal), my_set_c.compare(&my_set_c));

        my_set_a.merge(my_set_b);
        my_set_a.merge(my_set_c);
    }

    #[test]
    fn test_singleton_example() {
        let mut my_hash_set = SetUnionHashSet::<&str>::default();
        let my_delta_set = SetUnionSingle::new_from("hello world");
        let my_array_set = SetUnionArray::new_from(["hello world", "b", "c", "d"]);

        assert_eq!(Some(Ordering::Equal), my_delta_set.compare(&my_delta_set));
        assert_eq!(Some(Ordering::Less), my_delta_set.compare(&my_array_set));
        assert_eq!(Some(Ordering::Greater), my_array_set.compare(&my_delta_set));
        assert_eq!(Some(Ordering::Equal), my_array_set.compare(&my_array_set));

        assert!(my_hash_set.merge(my_array_set)); // Changes
        assert!(!my_hash_set.merge(my_delta_set)); // No changes

        println!("{:?}", my_hash_set.0);
    }
}