-
Notifications
You must be signed in to change notification settings - Fork 24
/
id.go
55 lines (46 loc) · 1.14 KB
/
id.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 platform
import (
"encoding/hex"
"encoding/json"
)
// ID is a unique identifier.
type ID []byte
// IDGenerator represents a generator for IDs.
type IDGenerator interface {
// ID creates unique byte slice ID.
ID() ID
}
// Decode parses b as a hex-encoded byte-slice-string.
func (i *ID) Decode(b []byte) error {
dst := make([]byte, hex.DecodedLen(len(b)))
_, err := hex.Decode(dst, b)
if err != nil {
return err
}
*i = dst
return nil
}
// DecodeFromString parses s as a hex-encoded string.
func (i *ID) DecodeFromString(s string) error {
return i.Decode([]byte(s))
}
// Encode converts ID to a hex-encoded byte-slice-string.
func (i ID) Encode() []byte {
dst := make([]byte, hex.EncodedLen(len(i)))
hex.Encode(dst, i)
return dst
}
// String returns the ID as a hex encoded string
func (i ID) String() string {
return string(i.Encode())
}
// UnmarshalJSON implements JSON unmarshaller for IDs.
func (i *ID) UnmarshalJSON(b []byte) error {
b = b[1 : len(b)-1]
return i.Decode(b)
}
// MarshalJSON implements JSON marshaller for IDs.
func (i ID) MarshalJSON() ([]byte, error) {
id := i.Encode()
return json.Marshal(string(id[:]))
}