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
// Copyright (c) The Diem Core Contributors
// SPDX-License-Identifier: Apache-2.0

use super::{unique_map::UniqueMap, *};
use std::{cmp::Ordering, fmt::Debug, iter::IntoIterator};

/// Unique set wrapper around `UniqueMap` where the value of the map is not needed
#[derive(Clone)]
pub struct UniqueSet<T: TName>(UniqueMap<T, ()>);

impl<T: TName> UniqueSet<T> {
    pub fn new() -> Self {
        Self(UniqueMap::new())
    }

    pub fn is_empty(&self) -> bool {
        self.0.is_empty()
    }

    pub fn len(&self) -> usize {
        self.0.len()
    }

    pub fn add(&mut self, x: T) -> Result<(), (T, T::Loc)> {
        self.0.add(x, ())
    }

    pub fn remove(&mut self, x: &T) -> bool {
        self.0.remove(x).is_some()
    }

    pub fn remove_(&mut self, x: &T::Key) -> bool {
        self.0.remove_(x).is_some()
    }

    pub fn contains(&self, x: &T) -> bool {
        self.0.contains_key(x)
    }

    pub fn contains_(&self, x_: &T::Key) -> bool {
        self.0.contains_key_(x_)
    }

    pub fn get_loc(&self, x: &T) -> Option<&T::Loc> {
        self.0.get_loc(x)
    }

    pub fn get_loc_(&self, x_: &T::Key) -> Option<&T::Loc> {
        self.0.get_loc_(x_)
    }

    // intersection of two sets. Keeps the loc of the first set
    pub fn intersect(&self, other: &Self) -> Self {
        let mut intersection = Self::new();
        for x in self.cloned_iter() {
            if !other.contains(&x) {
                continue;
            }
            assert!(intersection.add(x).is_ok());
        }
        intersection
    }

    // union of two sets. Prefers the loc of the first set
    pub fn union(&self, other: &Self) -> Self {
        let mut joined = Self::new();
        for x in self.cloned_iter() {
            assert!(joined.add(x).is_ok());
        }
        for (loc, x_) in other {
            if joined.contains_(x_) {
                continue;
            }
            assert!(joined.add(T::add_loc(loc, x_.clone())).is_ok())
        }
        joined
    }

    pub fn is_subset(&self, other: &Self) -> bool {
        self.iter().all(|(_, x_)| other.contains_(x_))
    }

    pub fn iter(&self) -> Iter<T> {
        self.into_iter()
    }

    pub fn cloned_iter(&self) -> impl Iterator<Item = T> {
        self.into_iter()
            .map(|(loc, k_)| T::add_loc(loc, k_.clone()))
            .collect::<Vec<_>>()
            .into_iter()
    }

    pub fn from_elements(
        iter: impl IntoIterator<Item = T>,
    ) -> Result<Self, (T::Key, T::Loc, T::Loc)> {
        Ok(Self(UniqueMap::maybe_from_iter(
            iter.into_iter().map(|x| (x, ())),
        )?))
    }

    pub fn from_elements_(
        loc: T::Loc,
        iter: impl IntoIterator<Item = T::Key>,
    ) -> Result<Self, (T::Key, T::Loc, T::Loc)> {
        Ok(Self(UniqueMap::maybe_from_iter(
            iter.into_iter().map(|x_| (T::add_loc(loc, x_), ())),
        )?))
    }
}

impl<T: TName> PartialEq for UniqueSet<T> {
    fn eq(&self, other: &UniqueSet<T>) -> bool {
        self.0 == other.0
    }
}
impl<T: TName> Eq for UniqueSet<T> {}

impl<T: TName> PartialOrd for UniqueSet<T> {
    fn partial_cmp(&self, other: &UniqueSet<T>) -> Option<Ordering> {
        (self.0).0.keys().partial_cmp((other.0).0.keys())
    }
}

impl<T: TName> Ord for UniqueSet<T> {
    fn cmp(&self, other: &UniqueSet<T>) -> Ordering {
        (self.0).0.keys().cmp((other.0).0.keys())
    }
}

impl<T: TName + Debug> Debug for UniqueSet<T>
where
    T::Key: Debug,
    T::Loc: Debug,
{
    fn fmt(&self, f: &mut std::fmt::Formatter) -> std::fmt::Result {
        self.0.fmt(f)
    }
}

impl<T: TName> Hash for UniqueSet<T>
where
    T::Key: Hash,
{
    fn hash<H: std::hash::Hasher>(&self, state: &mut H) {
        for k in (self.0).0.keys() {
            k.hash(state);
        }
    }
}

//**************************************************************************************************
// IntoIter
//**************************************************************************************************

pub struct IntoIter<T: TName>(
    std::iter::Map<unique_map::IntoIter<T, ()>, fn((T, ())) -> T>,
    usize,
);

impl<T: TName> Iterator for IntoIter<T> {
    type Item = T;

    fn next(&mut self) -> Option<Self::Item> {
        if self.1 > 0 {
            self.1 -= 1;
        }
        self.0.next()
    }

    fn size_hint(&self) -> (usize, Option<usize>) {
        (self.1, Some(self.1))
    }
}

impl<T: TName> IntoIterator for UniqueSet<T> {
    type Item = T;
    type IntoIter = IntoIter<T>;

    fn into_iter(self) -> Self::IntoIter {
        let len = self.len();
        IntoIter(
            self.0.into_iter().map(|ab_v| {
                let (ab, ()) = ab_v;
                ab
            }),
            len,
        )
    }
}

//**************************************************************************************************
// Iter
//**************************************************************************************************

pub struct Iter<'a, T: TName>(
    std::iter::Map<
        unique_map::Iter<'a, T, ()>,
        fn((T::Loc, &'a T::Key, &'a ())) -> (T::Loc, &'a T::Key),
    >,
    usize,
);

impl<'a, T: TName> Iterator for Iter<'a, T> {
    type Item = (T::Loc, &'a T::Key);

    fn next(&mut self) -> Option<Self::Item> {
        if self.1 > 0 {
            self.1 -= 1;
        }
        self.0.next()
    }

    fn size_hint(&self) -> (usize, Option<usize>) {
        (self.1, Some(self.1))
    }
}

impl<'a, T: TName> IntoIterator for &'a UniqueSet<T> {
    type Item = (T::Loc, &'a T::Key);
    type IntoIter = Iter<'a, T>;

    fn into_iter(self) -> Self::IntoIter {
        let len = self.len();
        Iter(self.0.iter().map(|(loc, x_, ())| (loc, x_)), len)
    }
}