mirror of
https://github.com/tailscale/tailscale.git
synced 2025-01-05 23:07:44 +00:00
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>
This commit is contained in:
parent
11ece02f52
commit
930e6f68f2
@ -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
|
||||
}
|
||||
|
@ -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…
x
Reference in New Issue
Block a user