Skip to content

Commit

Permalink
Merge pull request #8 from m4rw3r/fix/unmarshal-json-slice
Browse files Browse the repository at this point in the history
Error instead of Panic on too short JSON string
  • Loading branch information
m4rw3r authored Mar 28, 2020
2 parents 9b5450c + d3871cf commit 80a86a3
Show file tree
Hide file tree
Showing 2 changed files with 59 additions and 1 deletion.
16 changes: 15 additions & 1 deletion marshal.go
Original file line number Diff line number Diff line change
Expand Up @@ -4,6 +4,14 @@ import (
"bytes"
)

// ErrNotJSONString occurs when attempting to parse an UUID from a JSON string
// which is too short or is missing quotes.
type ErrNotJSONString struct{}

func (e ErrNotJSONString) Error() string {
return "invalid UUID: invalid JSON string"
}

var nullByteString = []byte("null")

// MarshalText returns the string-representation of the UUID as a byte-array.
Expand Down Expand Up @@ -80,7 +88,13 @@ func (u *UUID) UnmarshalText(data []byte) error {
// UnmarshalJSON reads an UUID from a JSON-string into the UUID instance.
// If this fails the state of the UUID is undetermined.
func (u *UUID) UnmarshalJSON(data []byte) error {
return u.ReadBytes(data[1 : len(data)-1])
l := len(data)

if l < 2 || data[0] != '"' || data[l-1] != '"' {
return &ErrNotJSONString{}
}

return u.ReadBytes(data[1 : l-1])
}

// MarshalJSON marshals a potentially null UUID into either a string-
Expand Down
44 changes: 44 additions & 0 deletions marshal_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -108,6 +108,50 @@ func TestUUIDUnmarshalJSON(t *testing.T) {
}
}

func TestUUIDUnmarshalJSONShortError(t *testing.T) {
list := [][]byte{
[]byte(""),
[]byte("\""),
[]byte("'"),
[]byte("a"),
[]byte("\"'"),
[]byte("\"a"),
}

for _, i := range list {
u := UUID{}

if err := u.UnmarshalJSON([]byte("")); err != nil {
if err.Error() != (&ErrNotJSONString{}).Error() {
t.Errorf("Expected ErrNotJSONString, got %s for %s", err.Error(), i)
}
} else {
t.Errorf("%s resulted in successful parse", i)
}

if !u.IsZero() {
t.Errorf("Modified UUID with invalid JSON string for %s", i)
}
}
}

func TestUUIDUnmarshalJSONShort(t *testing.T) {
u := UUID{}

if err := u.UnmarshalJSON([]byte("\"\"")); err != nil {
fmt.Print(err.Error())
if err.Error() != (&ErrTooShort{0, 0, 0}).Error() {
t.Errorf("Expected ErrNotJSONString, got %s", err.Error())
}
} else {
t.Error("Empty string resulted in successful parse")
}

if !u.IsZero() {
t.Error("Modified UUID with invalid JSON string")
}
}

func BenchmarkUnmarshalText(b *testing.B) {
u := UUID{}

Expand Down

0 comments on commit 80a86a3

Please sign in to comment.