-
Notifications
You must be signed in to change notification settings - Fork 20
/
misc.go
43 lines (36 loc) · 961 Bytes
/
misc.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
package utils
import (
"slices"
"golang.org/x/exp/constraints"
"golang.org/x/exp/maps"
)
// Set converts a slice to a set (a K > bool map)
func Set[K constraints.Ordered](s []K) map[K]bool {
m := make(map[K]bool, len(s))
for _, v := range s {
m[v] = true
}
return m
}
// SortedKeys returns the keys of a set in lexical order
func SortedKeys[K constraints.Ordered, V any](m map[K]V) []K {
keys := maps.Keys(m)
slices.Sort(keys)
return keys
}
// Typed is an interface of objects that are marshalled as typed envelopes
type Typed interface {
Type() string
}
// TypedEnvelope can be mixed into envelopes that have a type field
type TypedEnvelope struct {
Type string `json:"type" validate:"required"`
}
// ReadTypeFromJSON reads a field called `type` from the given JSON
func ReadTypeFromJSON(data []byte) (string, error) {
t := &TypedEnvelope{}
if err := UnmarshalAndValidate(data, t); err != nil {
return "", err
}
return t.Type, nil
}