diff --git a/snowflake.go b/snowflake.go index 26da1fe..7f10e5e 100644 --- a/snowflake.go +++ b/snowflake.go @@ -3,6 +3,7 @@ package snowflake import ( "encoding/base64" + "encoding/binary" "errors" "strconv" "sync" @@ -105,11 +106,19 @@ func (f ID) Base64() string { 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 { 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 func (f ID) Time() int64 { return (int64(f) >> 22) + Epoch diff --git a/snowflake_test.go b/snowflake_test.go index 40c1a95..a9c989c 100644 --- a/snowflake_test.go +++ b/snowflake_test.go @@ -1,6 +1,9 @@ package snowflake -import "testing" +import ( + "bytes" + "testing" +) func TestMarshalJSON(t *testing.T) { 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) { strID := "\"13587\"" expected := ID(13587)