-
Notifications
You must be signed in to change notification settings - Fork 10
/
entity_map.go
51 lines (42 loc) · 1.09 KB
/
entity_map.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
package types
import (
"encoding/json"
"slices"
"strings"
"golang.org/x/exp/maps"
)
// An EntityGetter is an interface for retrieving an Entity by EntityUID.
type EntityGetter interface {
Get(uid EntityUID) (Entity, bool)
}
var _ EntityGetter = EntityMap{}
// An EntityMap is a collection of all the entities that are needed to evaluate
// authorization requests. The key is an EntityUID which uniquely identifies
// the Entity (it must be the same as the UID within the Entity itself.)
type EntityMap map[EntityUID]Entity
func (e EntityMap) MarshalJSON() ([]byte, error) {
s := maps.Values(e)
slices.SortFunc(s, func(a, b Entity) int {
return strings.Compare(a.UID.String(), b.UID.String())
})
return json.Marshal(s)
}
func (e *EntityMap) UnmarshalJSON(b []byte) error {
var s []Entity
if err := json.Unmarshal(b, &s); err != nil {
return err
}
var res = EntityMap{}
for _, e := range s {
res[e.UID] = e
}
*e = res
return nil
}
func (e EntityMap) Clone() EntityMap {
return maps.Clone(e)
}
func (e EntityMap) Get(uid EntityUID) (Entity, bool) {
ent, ok := e[uid]
return ent, ok
}