-
Notifications
You must be signed in to change notification settings - Fork 29
/
Copy pathtwophase_set.go
55 lines (46 loc) · 1.21 KB
/
twophase_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
package crdt
import "encoding/json"
var (
// TwoPhaseSet should implement Set.
_ Set = &TwoPhaseSet{}
)
// TwoPhaseSet supports both addition and removal of
// elements to set.
type TwoPhaseSet struct {
addSet *GSet
rmSet *GSet
}
// NewTwoPhaseSet returns a new instance of TwoPhaseSet.
func NewTwoPhaseSet() *TwoPhaseSet {
return &TwoPhaseSet{
addSet: NewGSet(),
rmSet: NewGSet(),
}
}
// Add inserts element into the TwoPhaseSet.
func (t *TwoPhaseSet) Add(elem interface{}) {
t.addSet.Add(elem)
}
// Remove deletes the element from the set.
func (t *TwoPhaseSet) Remove(elem interface{}) {
t.rmSet.Add(elem)
}
// Contains returns true if the set contains the element.
// The set is said to contain the element if it is present
// in the add-set and not in the remove-set.
func (t *TwoPhaseSet) Contains(elem interface{}) bool {
return t.addSet.Contains(elem) && !t.rmSet.Contains(elem)
}
type tpsetJSON struct {
T string `json:"type"`
A []interface{} `json:"a"`
R []interface{} `json:"r"`
}
// MarshalJSON serializes TwoPhaseSet into an JSON array.
func (t *TwoPhaseSet) MarshalJSON() ([]byte, error) {
return json.Marshal(&tpsetJSON{
T: "2p-set",
A: t.addSet.Elems(),
R: t.rmSet.Elems(),
})
}