types/opt: use switch in Bool.UnmarshalJSON (#9140)

The compiler does indeed perform this optimization.

Updates #cleanup

Signed-off-by: Joe Tsai <joetsai@digital-static.net>
pull/9097/head
Joe Tsai 1 year ago committed by GitHub
parent 11ece02f52
commit 930e6f68f2
No known key found for this signature in database
GPG Key ID: 4AEE18F83AFDEB23

@ -87,21 +87,15 @@ func (b Bool) MarshalJSON() ([]byte, error) {
} }
func (b *Bool) UnmarshalJSON(j []byte) error { func (b *Bool) UnmarshalJSON(j []byte) error {
// Note: written with a bunch of ifs instead of a switch switch string(j) {
// because I'm sure the Go compiler optimizes away these case "true":
// []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" {
*b = "true" *b = "true"
return nil case "false":
}
if string(j) == "false" {
*b = "false" *b = "false"
return nil case "null":
}
if string(j) == "null" {
*b = "unset" *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
} }

@ -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)
}
}

Loading…
Cancel
Save