forked from ava-labs/avalanchego
-
Notifications
You must be signed in to change notification settings - Fork 0
/
set.go
107 lines (92 loc) · 2.1 KB
/
set.go
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
// (c) 2019-2020, Ava Labs, Inc. All rights reserved.
// See the file LICENSE for licensing terms.
package ids
import (
"strings"
)
// Set is a set of IDs
type Set map[[32]byte]bool
func (ids *Set) init(size int) {
if *ids == nil {
*ids = make(map[[32]byte]bool, size)
}
}
// Add all the ids to this set, if the id is already in the set, nothing happens
func (ids *Set) Add(idList ...ID) {
ids.init(2 * len(idList))
for _, id := range idList {
(*ids)[*id.ID] = true
}
}
// Union adds all the ids from the provided sets to this set.
func (ids *Set) Union(set Set) {
ids.init(2 * set.Len())
for id := range set {
(*ids)[id] = true
}
}
// Contains returns true if the set contains this id, false otherwise
func (ids *Set) Contains(id ID) bool {
ids.init(1)
return (*ids)[*id.ID]
}
// Overlaps returns true if the intersection of the set is non-empty
func (ids *Set) Overlaps(big Set) bool {
small := *ids
if small.Len() > big.Len() {
small = big
big = *ids
}
for _, id := range small.List() {
if big.Contains(id) {
return true
}
}
return false
}
// Len returns the number of ids in this set
func (ids Set) Len() int { return len(ids) }
// Remove all the id from this set, if the id isn't in the set, nothing happens
func (ids *Set) Remove(idList ...ID) {
ids.init(1)
for _, id := range idList {
delete(*ids, *id.ID)
}
}
// Clear empties this set
func (ids *Set) Clear() { *ids = nil }
// List converts this set into a list
func (ids Set) List() []ID {
idList := []ID(nil)
for id := range ids {
idList = append(idList, NewID(id))
}
return idList
}
// Equals returns true if the sets contain the same elements
func (ids Set) Equals(oIDs Set) bool {
if ids.Len() != oIDs.Len() {
return false
}
for key := range oIDs {
if !ids[key] {
return false
}
}
return true
}
// String returns the string representation of a set
func (ids Set) String() string {
sb := strings.Builder{}
sb.WriteString("{")
first := true
for idBytes := range ids {
if !first {
sb.WriteString(", ")
}
first = false
sb.WriteString(NewID(idBytes).String())
}
sb.WriteString("}")
return sb.String()
}