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 {
// 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 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