Add a method to encode the snowflake as a byte slice
This commit is contained in:
parent
cd8e42350a
commit
95d961a628
11
snowflake.go
11
snowflake.go
@ -3,6 +3,7 @@ package snowflake
|
|||||||
|
|
||||||
import (
|
import (
|
||||||
"encoding/base64"
|
"encoding/base64"
|
||||||
|
"encoding/binary"
|
||||||
"errors"
|
"errors"
|
||||||
"strconv"
|
"strconv"
|
||||||
"sync"
|
"sync"
|
||||||
@ -105,11 +106,19 @@ func (f ID) Base64() string {
|
|||||||
return base64.StdEncoding.EncodeToString(f.Bytes())
|
return base64.StdEncoding.EncodeToString(f.Bytes())
|
||||||
}
|
}
|
||||||
|
|
||||||
// Bytes returns a byte array of the snowflake ID
|
// Bytes returns a byte slice of the snowflake ID
|
||||||
func (f ID) Bytes() []byte {
|
func (f ID) Bytes() []byte {
|
||||||
return []byte(f.String())
|
return []byte(f.String())
|
||||||
}
|
}
|
||||||
|
|
||||||
|
// IntBytes returns an array of bytes of the snowflake ID, encoded as a
|
||||||
|
// big endian integer.
|
||||||
|
func (f ID) IntBytes() [8]byte {
|
||||||
|
var b [8]byte
|
||||||
|
binary.BigEndian.PutUint64(b[:], uint64(f))
|
||||||
|
return b
|
||||||
|
}
|
||||||
|
|
||||||
// Time returns an int64 unix timestamp of the snowflake ID time
|
// Time returns an int64 unix timestamp of the snowflake ID time
|
||||||
func (f ID) Time() int64 {
|
func (f ID) Time() int64 {
|
||||||
return (int64(f) >> 22) + Epoch
|
return (int64(f) >> 22) + Epoch
|
||||||
|
@ -1,6 +1,9 @@
|
|||||||
package snowflake
|
package snowflake
|
||||||
|
|
||||||
import "testing"
|
import (
|
||||||
|
"bytes"
|
||||||
|
"testing"
|
||||||
|
)
|
||||||
|
|
||||||
func TestMarshalJSON(t *testing.T) {
|
func TestMarshalJSON(t *testing.T) {
|
||||||
id := ID(13587)
|
id := ID(13587)
|
||||||
@ -16,6 +19,14 @@ func TestMarshalJSON(t *testing.T) {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
func TestMarshalsIntBytes(t *testing.T) {
|
||||||
|
id := ID(13587).IntBytes()
|
||||||
|
expected := []byte{0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x35, 0x13}
|
||||||
|
if !bytes.Equal(id[:], expected) {
|
||||||
|
t.Errorf("Expected ID to be encoded as %v, got %v", expected, id)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
func TestUnmarshalJSON(t *testing.T) {
|
func TestUnmarshalJSON(t *testing.T) {
|
||||||
strID := "\"13587\""
|
strID := "\"13587\""
|
||||||
expected := ID(13587)
|
expected := ID(13587)
|
||||||
|
Loading…
x
Reference in New Issue
Block a user