-
Notifications
You must be signed in to change notification settings - Fork 3
/
set_builder.go
54 lines (46 loc) · 1.36 KB
/
set_builder.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
package frozen
// SetBuilder provides a more efficient way to build sets incrementally.
type SetBuilder struct {
root *node
prepared *node
attemptedAdds int
redundantAdds int
removals int
cloner *cloner
}
func NewSetBuilder(capacity int) *SetBuilder {
return &SetBuilder{cloner: newCloner(true, capacity)}
}
func (b *SetBuilder) getCloner() *cloner {
if b.cloner == nil {
b.cloner = theMutator
}
return b.cloner
}
// Count returns the count of the Set that will be returned from Finish().
func (b *SetBuilder) Count() int {
return b.attemptedAdds - b.redundantAdds - b.removals
}
// Add adds el to the Set under construction.
func (b *SetBuilder) Add(v interface{}) {
b.root = b.root.with(v, useRHS, 0, newHasher(v, 0), &b.redundantAdds, b.getCloner(), &b.prepared)
b.attemptedAdds++
}
// Remove removes el to the Set under construction.
func (b *SetBuilder) Remove(v interface{}) {
b.root = b.root.without(v, 0, newHasher(v, 0), &b.removals, b.getCloner(), &b.prepared)
}
func (b *SetBuilder) Has(el interface{}) bool {
return b.root.get(el) != nil
}
// Finish returns a Set containing all elements added since the SetBuilder was
// initialised or the last call to Finish.
func (b *SetBuilder) Finish() Set {
count := b.Count()
if count == 0 {
return Set{}
}
root := b.root
*b = SetBuilder{}
return Set{root: root, count: count}
}