2018-05-14 16:26:38 +00:00
|
|
|
package platform
|
|
|
|
|
|
|
|
import (
|
|
|
|
"encoding/hex"
|
|
|
|
"encoding/json"
|
|
|
|
)
|
|
|
|
|
|
|
|
// ID is a unique identifier.
|
2018-08-01 18:54:32 +00:00
|
|
|
type ID []byte
|
2018-05-14 16:26:38 +00:00
|
|
|
|
2018-05-16 15:32:19 +00:00
|
|
|
// IDGenerator represents a generator for IDs.
|
|
|
|
type IDGenerator interface {
|
|
|
|
// ID creates unique byte slice ID.
|
2018-07-30 11:38:23 +00:00
|
|
|
ID() ID
|
2018-05-16 15:32:19 +00:00
|
|
|
}
|
|
|
|
|
2018-08-01 18:54:32 +00:00
|
|
|
// IDFromString creates an ID from a given string
|
|
|
|
func IDFromString(idstr string) (*ID, error) {
|
2018-07-20 15:00:31 +00:00
|
|
|
var id ID
|
2018-08-01 18:54:32 +00:00
|
|
|
err := id.DecodeFromString(idstr)
|
2018-07-20 15:00:31 +00:00
|
|
|
if err != nil {
|
|
|
|
return nil, err
|
|
|
|
}
|
|
|
|
return &id, nil
|
|
|
|
}
|
|
|
|
|
2018-05-14 16:26:38 +00:00
|
|
|
// Decode parses b as a hex-encoded byte-slice-string.
|
|
|
|
func (i *ID) Decode(b []byte) error {
|
2018-08-01 18:54:32 +00:00
|
|
|
dst := make([]byte, hex.DecodedLen(len(b)))
|
2018-05-14 16:26:38 +00:00
|
|
|
_, err := hex.Decode(dst, b)
|
|
|
|
if err != nil {
|
|
|
|
return err
|
|
|
|
}
|
2018-08-01 18:54:32 +00:00
|
|
|
*i = dst
|
2018-05-14 16:26:38 +00:00
|
|
|
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.
|
2018-08-01 18:54:32 +00:00
|
|
|
func (i ID) Encode() []byte {
|
|
|
|
dst := make([]byte, hex.EncodedLen(len(i)))
|
|
|
|
hex.Encode(dst, i)
|
|
|
|
return dst
|
2018-07-30 11:38:23 +00:00
|
|
|
}
|
|
|
|
|
2018-08-01 18:54:32 +00:00
|
|
|
// String returns the ID as a hex encoded string
|
2018-05-14 16:26:38 +00:00
|
|
|
func (i ID) String() string {
|
2018-08-01 18:54:32 +00:00
|
|
|
return string(i.Encode())
|
2018-05-14 16:26:38 +00:00
|
|
|
}
|
|
|
|
|
|
|
|
// 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) {
|
2018-08-01 18:54:32 +00:00
|
|
|
id := i.Encode()
|
|
|
|
return json.Marshal(string(id[:]))
|
2018-05-14 16:26:38 +00:00
|
|
|
}
|