Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
15 changes: 14 additions & 1 deletion uuid.go
Original file line number Diff line number Diff line change
Expand Up @@ -14,9 +14,10 @@ import (
"fmt"
"hash"
"regexp"
"strings"
)

// The UUID reserved variants.
// The UUID reserved variants.
const (
ReservedNCS byte = 0x80
ReservedRFC4122 byte = 0x40
Expand Down Expand Up @@ -171,3 +172,15 @@ func (u *UUID) Version() uint {
func (u *UUID) String() string {
return fmt.Sprintf("%x-%x-%x-%x-%x", u[0:4], u[4:6], u[6:8], u[8:10], u[10:])
}

func (u *UUID) MarshalJSON() ([]byte, error) {

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

the pointer can be nil here right?

str := "\""+u.String()+"\""
return []byte(str), nil
}

func (u *UUID) UnmarshalJSON(data []byte) error {
str := strings.Replace(string(data), "\"", "", -1)
new_uuid, err := ParseHex(str)
copy(u[:], new_uuid[:])
return err
}
33 changes: 33 additions & 0 deletions uuid_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -122,6 +122,39 @@ func TestNewV5(t *testing.T) {
}
}

func TestMarshalJSON(t *testing.T) {
u, err := ParseHex("89d7afd8-b795-4a29-bb06-7a1aad5b1d62")
if err != nil {
t.Error("failed to generate uuid for testing: ", err.Error())
return
}
data, err := u.MarshalJSON()
if err != nil {
t.Error("failed to marshal uuid: ", err.Error())
return
}
if string(data) != "\"89d7afd8-b795-4a29-bb06-7a1aad5b1d62\"" {
t.Error("marsheld uuid does not match the original")
}
}

func TestUnmarshalJSON(t *testing.T) {
u1, err := ParseHex("89d7afd8-b795-4a29-bb06-7a1aad5b1d62")
u2 := new(UUID)
if err != nil {
t.Error("failed to generate uuid for testing: ", err.Error())
return
}
err = u2.UnmarshalJSON([]byte("\"89d7afd8-b795-4a29-bb06-7a1aad5b1d62\""))
if err != nil {
t.Error("failed to marshal uuid: ", err.Error())
return
}
if u1.String() != "89d7afd8-b795-4a29-bb06-7a1aad5b1d62" {
t.Error("unmarsheld uuid does not match the original")
}
}

func BenchmarkParseHex(b *testing.B) {
s := "f3593cff-ee92-40df-4086-87825b523f13"
for i := 0; i < b.N; i++ {
Expand Down