diff --git a/types/opt/bool.go b/types/opt/bool.go index 66ff1bd82..ca9c048d5 100644 --- a/types/opt/bool.go +++ b/types/opt/bool.go @@ -87,21 +87,15 @@ func (b Bool) MarshalJSON() ([]byte, error) { } func (b *Bool) UnmarshalJSON(j []byte) error { - // Note: written with a bunch of ifs instead of a switch - // because I'm sure the Go compiler optimizes away these - // []byte->string allocations in an == comparison, but I'm too - // lazy to check whether that's true in a switch also. - if string(j) == "true" { + switch string(j) { + case "true": *b = "true" - return nil - } - if string(j) == "false" { + case "false": *b = "false" - return nil - } - if string(j) == "null" { + case "null": *b = "unset" - return nil + default: + return fmt.Errorf("invalid opt.Bool value %q", j) } - return fmt.Errorf("invalid opt.Bool value %q", j) + return nil } diff --git a/types/opt/bool_test.go b/types/opt/bool_test.go index 2dc2d1707..92ba275e1 100644 --- a/types/opt/bool_test.go +++ b/types/opt/bool_test.go @@ -119,3 +119,11 @@ func TestBoolEqualBool(t *testing.T) { } } } + +func TestUnmarshalAlloc(t *testing.T) { + b := json.Unmarshaler(new(Bool)) + n := testing.AllocsPerRun(10, func() { b.UnmarshalJSON(trueBytes) }) + if n > 0 { + t.Errorf("got %v allocs, want 0", n) + } +}