-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathencoder.go
69 lines (53 loc) · 1.56 KB
/
encoder.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
package ksuid
import (
"bytes"
"encoding/binary"
"encoding/hex"
"time"
"errors"
)
// Encoder is a function which takes a KSUID and returns a sequence of bytes to represent it.
type Encoder func(KSUID) []byte
// Decoder is a function which takes a sequence of bytes and returns a KSUID
type Decoder func([]byte) (*KSUID, error)
// EncodeBinary encodes the KSUID as a sequence of bytes in big-endian order.
// This function always returns a []byte with a length of exactly 12.
// Useful for efficient transport over a network to other machines.
// Also used by most other encoder functions.
func EncodeBinary(k KSUID) []byte {
b := new(bytes.Buffer)
binary.Write(b, binary.BigEndian, k.Epoch())
binary.Write(b, binary.BigEndian, k.Seq)
binary.Write(b, binary.BigEndian, k.Partition)
return b.Bytes()
}
// EncodeHex encodes the KSUID to hex
// This function returns a []byte with a length of exactly 24.
func EncodeHex(k KSUID) []byte {
b := EncodeBinary(k)
r := make([]byte, 2*len(b))
hex.Encode(r, b)
return r
}
// DecodeBinary decodes a KSUID from 12 bytes of binary data.
func DecodeBinary(b []byte) (*KSUID, error) {
if len(b) != 12 {
return nil, errors.New("encoded KSUID must be exactly 12 bytes")
}
t := binary.BigEndian.Uint32(b)
s := binary.BigEndian.Uint32(b[4:])
p := binary.BigEndian.Uint32(b[8:])
k := &KSUID{
T: time.Unix(Epoch + int64(t), 0),
Seq: s,
Partition: p,
}
return k, nil
}
func DecodeHex(b []byte) (*KSUID, error) {
v, err := hex.DecodeString(string(b))
if err != nil {
return nil, err
}
return DecodeBinary(v)
}