-
Notifications
You must be signed in to change notification settings - Fork 246
/
onrbytypeset.go
82 lines (70 loc) · 2.16 KB
/
onrbytypeset.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
package tuple
import (
"github.com/samber/lo"
core "github.com/authzed/spicedb/pkg/proto/core/v1"
)
// ONRByTypeSet is a set of ObjectAndRelation's, grouped by namespace+relation.
type ONRByTypeSet struct {
byType map[string][]string
}
// NewONRByTypeSet creates and returns a new ONRByTypeSet.
func NewONRByTypeSet() *ONRByTypeSet {
return &ONRByTypeSet{
byType: map[string][]string{},
}
}
// Add adds the specified ObjectAndRelation to the set.
func (s *ONRByTypeSet) Add(onr *core.ObjectAndRelation) {
key := JoinRelRef(onr.Namespace, onr.Relation)
if _, ok := s.byType[key]; !ok {
s.byType[key] = []string{}
}
s.byType[key] = append(s.byType[key], onr.ObjectId)
}
// ForEachType invokes the handler for each type of ObjectAndRelation found in the set, along
// with all IDs of objects of that type.
func (s *ONRByTypeSet) ForEachType(handler func(rr *core.RelationReference, objectIds []string)) {
for key, objectIds := range s.byType {
ns, rel := MustSplitRelRef(key)
handler(&core.RelationReference{
Namespace: ns,
Relation: rel,
}, lo.Uniq(objectIds))
}
}
// Map runs the mapper function over each type of object in the set, returning a new ONRByTypeSet with
// the object type replaced by that returned by the mapper function.
func (s *ONRByTypeSet) Map(mapper func(rr *core.RelationReference) (*core.RelationReference, error)) (*ONRByTypeSet, error) {
mapped := NewONRByTypeSet()
for key, objectIds := range s.byType {
ns, rel := MustSplitRelRef(key)
updatedType, err := mapper(&core.RelationReference{
Namespace: ns,
Relation: rel,
})
if err != nil {
return nil, err
}
if updatedType == nil {
continue
}
mapped.byType[JoinRelRef(updatedType.Namespace, updatedType.Relation)] = lo.Uniq(objectIds)
}
return mapped, nil
}
// IsEmpty returns true if the set is empty.
func (s *ONRByTypeSet) IsEmpty() bool {
return len(s.byType) == 0
}
// KeyLen returns the number of keys in the set.
func (s *ONRByTypeSet) KeyLen() int {
return len(s.byType)
}
// ValueLen returns the number of values in the set.
func (s *ONRByTypeSet) ValueLen() int {
var total int
for _, vals := range s.byType {
total += len(vals)
}
return total
}