Merge pull request #1 from zeroZshadow/master
Added tests, optimized MarshalJSON, removed unused error from Generate
This commit is contained in:
commit
82eab22d0d
10
snowflake.go
10
snowflake.go
@ -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
|
||||
|
@ -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()
|
||||
|
||||
|
Loading…
x
Reference in New Issue
Block a user