Skip to content

Commit

Permalink
go-uuid: Fix JSON encoding for empty UUIDs
Browse files Browse the repository at this point in the history
  • Loading branch information
bormanp committed Dec 2, 2014
1 parent e1a3bdb commit ed3ca8a
Show file tree
Hide file tree
Showing 4 changed files with 17 additions and 9 deletions.
6 changes: 6 additions & 0 deletions uuid/json.go
Original file line number Diff line number Diff line change
Expand Up @@ -7,10 +7,16 @@ package uuid
import "errors"

func (u UUID) MarshalJSON() ([]byte, error) {
if len(u) == 0 {
return []byte(`""`), nil
}
return []byte(`"` + u.String() + `"`), nil
}

func (u *UUID) UnmarshalJSON(data []byte) error {
if len(data) == 0 || string(data) == `""` {
return nil
}
if len(data) < 2 || data[0] != '"' || data[len(data)-1] != '"' {
return errors.New("invalid UUID format")
}
Expand Down
10 changes: 6 additions & 4 deletions uuid/json_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -6,16 +6,18 @@ package uuid

import (
"encoding/json"
"reflect"
"testing"
)

var testUUID = Parse("f47ac10b-58cc-0372-8567-0e02b2c3d479")

func TestJSON(t *testing.T) {
type S struct {
ID UUID
ID1 UUID
ID2 UUID
}
s1 := S{testUUID}
s1 := S{ID1: testUUID}
data, err := json.Marshal(&s1)
if err != nil {
t.Fatal(err)
Expand All @@ -24,7 +26,7 @@ func TestJSON(t *testing.T) {
if err := json.Unmarshal(data, &s2); err != nil {
t.Fatal(err)
}
if !Equal(s1.ID, s2.ID) {
t.Errorf("got UUID %v, want %v", s2.ID, s1.ID)
if !reflect.DeepEqual(&s1, &s2) {
t.Errorf("got %#v, want %#v", s2, s1)
}
}
6 changes: 3 additions & 3 deletions uuid/seq_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -48,16 +48,16 @@ func TestClockSeqRace(t *testing.T) {
}()
}

uuid_map := make(map[string]bool)
uuids := make(map[string]bool)
cnt := 0
start := time.Now()
for u := range ch {
s := u.String()
if uuid_map[s] {
if uuids[s] {
t.Errorf("duplicate uuid after %d in %v: %s", cnt, time.Since(start), s)
return
}
uuid_map[s] = true
uuids[s] = true
if time.Since(start) > duration {
return
}
Expand Down
4 changes: 2 additions & 2 deletions uuid/time.go
Original file line number Diff line number Diff line change
Expand Up @@ -40,8 +40,8 @@ func (t Time) UnixTime() (sec, nsec int64) {
}

// GetTime returns the current Time (100s of nanoseconds since 15 Oct 1582) and
// adjusts the clock sequence as needed. An error is returned if the current
// time cannot be determined.
// clock sequence as well as adjusting the clock sequence as needed. An error
// is returned if the current time cannot be determined.
func GetTime() (Time, uint16, error) {
defer mu.Unlock()
mu.Lock()
Expand Down

0 comments on commit ed3ca8a

Please # to comment.