Skip to content

Commit

Permalink
fix(snowflake): make UnmarshalJSON accept empty strings
Browse files Browse the repository at this point in the history
An empty string is now interpreted as a Snowflake with value 0.
Also added a new test to ensure empty strings get properly unmarshalled
into Snowflakes.
  • Loading branch information
DasPoet committed Aug 28, 2021
1 parent 39748d5 commit 1efa62c
Show file tree
Hide file tree
Showing 2 changed files with 28 additions and 18 deletions.
35 changes: 17 additions & 18 deletions snowflake.go
Original file line number Diff line number Diff line change
@@ -1,8 +1,6 @@
package snowflake

import (
"bytes"
"encoding/json"
"strconv"
"time"
)
Expand Down Expand Up @@ -58,24 +56,25 @@ func (s Snowflake) Increment() int64 {

// UnmarshalJSON unmarshals data into s.
func (s *Snowflake) UnmarshalJSON(data []byte) error {
dec := json.NewDecoder(bytes.NewReader(data))
dec.UseNumber()

var raw json.Number
if err := dec.Decode(&raw); err != nil {
typeErr, ok := err.(*json.UnmarshalTypeError)
if ok {
return UnmarshalTypeError{
value: typeErr.Value,
structName: typeErr.Struct,
field: typeErr.Field,
typ: "int or string",
}
}
return err
start, stop := 0, len(data)
if data[0] == '"' && data[len(data)-1] == '"' {
start++
stop--
}

raw := data[start:stop]
if len(raw) == 0 {
*s = 0
return nil
}

parsed, err := raw.Int64()
parsed, err := strconv.Atoi(string(raw))
if err != nil {
return UnmarshalTypeError{
value: string(data),
typ: "int or string",
}
}
if err == nil {
*s = Snowflake(parsed)
}
Expand Down
11 changes: 11 additions & 0 deletions snowflake_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -44,6 +44,17 @@ func TestSnowflake_UnmarshalJSONWithString(t *testing.T) {
fmt.Println(test.Snowflake)
}

func TestSnowflake_UnmarshalJSONWithEmptyString(t *testing.T) {
require := require.New(t)

raw, test := "{\"snowflake\": \"\"}", new(test)

err := json.Unmarshal([]byte(raw), &test)
require.NoError(err)

fmt.Println(test.Snowflake)
}

func TestSnowflake_UnmarshalJSONWithNonsense(t *testing.T) {
require := require.New(t)

Expand Down

0 comments on commit 1efa62c

Please sign in to comment.