1
0
mirror of https://github.com/google/uuid.git synced 2025-09-16 09:16:30 +02:00

opitimize json interface methods

A common helper function is used for UUID.String(), UUID.URN(), and
UUID.MarshalJSON().  Any perforance hit in UUID.String() and
UUID.Marshal() appears to be negligable.  The benefit to
UUID.MarshalJSON() is several hundred nanoseconds (23% faster) and 2
allocations (21% fewer bytes).

Some redundant checks are removed from UUID.UnmarshalJSON() method.  The
"encoding/json".Unmarshaler interface specifies that implementations can
assume input is valid JSON content.  This allows one to assume that (1)
input is not empty and (2) if index 0 is a quote, then the content is a
json string and the last index will contain a terminating quote.  The
second point is not completely explicit in the documentation but it is
true in practice (and it is safe to assume -- errors will be caught).
This commit is contained in:
Bryan Matsuo
2015-10-10 20:56:32 -07:00
parent 0ec82b41c6
commit 1c7b0fea16
2 changed files with 22 additions and 23 deletions

12
json.go
View File

@@ -7,17 +7,21 @@ package uuid
import "errors"
func (u UUID) MarshalJSON() ([]byte, error) {
if len(u) == 0 {
if len(u) != 16 {
return []byte(`""`), nil
}
return []byte(`"` + u.String() + `"`), nil
var js [38]byte
js[0] = '"'
encodeHex(js[1:], u)
js[37] = '"'
return js[:], nil
}
func (u *UUID) UnmarshalJSON(data []byte) error {
if len(data) == 0 || string(data) == `""` {
if string(data) == `""` {
return nil
}
if len(data) < 2 || data[0] != '"' || data[len(data)-1] != '"' {
if data[0] != '"' {
return errors.New("invalid UUID format")
}
data = data[1 : len(data)-1]