Merge pull request #1 from zeroZshadow/master

Added tests, optimized MarshalJSON, removed unused error from Generate
This commit is contained in:
Bruce 2016-06-10 17:59:15 -05:00 committed by GitHub
commit 82eab22d0d
2 changed files with 38 additions and 7 deletions

View File

@ -51,7 +51,7 @@ func NewNode(node int64) (*Node, error) {
}
// Generate creates and returns a unique snowflake ID
func (n *Node) Generate() (ID, error) {
func (n *Node) Generate() ID {
n.Lock()
defer n.Unlock()
@ -75,7 +75,7 @@ func (n *Node) Generate() (ID, error) {
return ID((now-Epoch)<<timeShift |
(n.node << nodeShift) |
(n.step),
), nil
)
}
// Int64 returns an int64 of the snowflake ID
@ -125,12 +125,14 @@ func (f ID) Step() int64 {
// MarshalJSON returns a json byte array string of the snowflake ID.
func (f ID) MarshalJSON() ([]byte, error) {
return []byte(`"` + f.String() + `"`), nil
buff := []byte("\"")
buff = strconv.AppendInt(buff, int64(f), 10)
buff = append(buff, '"')
return buff, nil
}
// UnmarshalJSON converts a json byte array of a snowflake ID into an ID type.
func (f *ID) UnmarshalJSON(b []byte) error {
i, err := strconv.ParseInt(string(b[1:len(b)-1]), 10, 64)
if err != nil {
return err

View File

@ -2,6 +2,35 @@ package snowflake
import "testing"
func TestMarshalJSON(t *testing.T) {
id := ID(13587)
expected := "\"13587\""
bytes, err := id.MarshalJSON()
if err != nil {
t.Error("Unexpected error during MarshalJSON")
}
if string(bytes) != expected {
t.Errorf("Got %s, expected %s", string(bytes), expected)
}
}
func TestUnmarshalJSON(t *testing.T) {
strID := "\"13587\""
expected := ID(13587)
var id ID
err := id.UnmarshalJSON([]byte(strID))
if err != nil {
t.Error("Unexpected error during UnmarshalJSON")
}
if id != expected {
t.Errorf("Got %d, expected %d", id, expected)
}
}
func BenchmarkGenerate(b *testing.B) {
node, _ := NewNode(1)
@ -10,14 +39,14 @@ func BenchmarkGenerate(b *testing.B) {
b.ResetTimer()
for n := 0; n < b.N; n++ {
_, _ = node.Generate()
_ = node.Generate()
}
}
func BenchmarkUnmarshal(b *testing.B) {
node, _ := NewNode(1)
id, _ := node.Generate()
id := node.Generate()
var id2 ID
b.ReportAllocs()
@ -31,7 +60,7 @@ func BenchmarkUnmarshal(b *testing.B) {
func BenchmarkMarshal(b *testing.B) {
node, _ := NewNode(1)
id, _ := node.Generate()
id := node.Generate()
b.ReportAllocs()