From 930e6f68f281b7e0f88f896cb9d9c4a71d7b3b16 Mon Sep 17 00:00:00 2001 From: Joe Tsai Date: Tue, 29 Aug 2023 13:12:49 -0700 Subject: [PATCH] types/opt: use switch in Bool.UnmarshalJSON (#9140) The compiler does indeed perform this optimization. Updates #cleanup Signed-off-by: Joe Tsai --- types/opt/bool.go | 20 +++++++------------- types/opt/bool_test.go | 8 ++++++++ 2 files changed, 15 insertions(+), 13 deletions(-) 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) + } +}