forked from neurodrone/crdt
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathg_set.go
More file actions
64 lines (51 loc) · 1.2 KB
/
Copy pathg_set.go
File metadata and controls
64 lines (51 loc) · 1.2 KB
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
package crdt
import "encoding/json"
type mainSet map[interface{}]struct{}
var (
// GSet should implement the set interface.
_ Set = &GSet{}
)
// Gset is a grow-only set.
type GSet struct {
mainSet mainSet
}
// NewGSet returns an instance of GSet.
func NewGSet() *GSet {
return &GSet{
mainSet: mainSet{},
}
}
// Add lets you add an element to grow-only set.
func (g *GSet) Add(elem interface{}) {
g.mainSet[elem] = struct{}{}
}
// Contains returns true if an element exists within the
// set or false otherwise.
func (g *GSet) Contains(elem interface{}) bool {
_, ok := g.mainSet[elem]
return ok
}
// Len returns the no. of elements present within GSet.
func (g *GSet) Len() int {
return len(g.mainSet)
}
// Elems returns all the elements present in the set.
func (g *GSet) Elems() []interface{} {
elems := make([]interface{}, 0, len(g.mainSet))
for elem := range g.mainSet {
elems = append(elems, elem)
}
return elems
}
type gsetJSON struct {
T string `json:"type"`
E []interface{} `json:"e"`
}
// MarshalJSON will be used to generate a serialized output
// of a given GSet.
func (g *GSet) MarshalJSON() ([]byte, error) {
return json.Marshal(&gsetJSON{
T: "g-set",
E: g.Elems(),
})
}