From 05bed64772bd71695e70e323303e546213d53dc0 Mon Sep 17 00:00:00 2001 From: Josh Bleecher Snyder Date: Fri, 30 Apr 2021 15:02:31 -0700 Subject: [PATCH] types/wgkey: simplify Key.UnmarshalJSON MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Instead of calling ParseHex, do the hex.Decode directly. name old time/op new time/op delta UnmarshalJSON-8 86.9ns ± 0% 42.6ns ± 0% -50.94% (p=0.000 n=15+14) name old alloc/op new alloc/op delta UnmarshalJSON-8 128B ± 0% 0B -100.00% (p=0.000 n=15+15) name old allocs/op new allocs/op delta UnmarshalJSON-8 2.00 ± 0% 0.00 -100.00% (p=0.000 n=15+15) Signed-off-by: Josh Bleecher Snyder --- types/wgkey/key.go | 7 +++---- types/wgkey/key_test.go | 15 +++++++++++++++ 2 files changed, 18 insertions(+), 4 deletions(-) diff --git a/types/wgkey/key.go b/types/wgkey/key.go index 668ceee85..fe757083a 100644 --- a/types/wgkey/key.go +++ b/types/wgkey/key.go @@ -106,11 +106,10 @@ func (k *Key) UnmarshalJSON(b []byte) error { return errors.New("wgkey.Key: UnmarshalJSON not given a string") } b = b[1 : len(b)-1] - key, err := ParseHex(string(b)) - if err != nil { - return fmt.Errorf("wgkey.Key: UnmarshalJSON: %v", err) + if len(b) != 2*Size { + return fmt.Errorf("wgkey.Key: UnmarshalJSON input wrong size: %d", len(b)) } - copy(k[:], key[:]) + hex.Decode(k[:], b) return nil } diff --git a/types/wgkey/key_test.go b/types/wgkey/key_test.go index ba3e4166f..1c4c2da59 100644 --- a/types/wgkey/key_test.go +++ b/types/wgkey/key_test.go @@ -156,3 +156,18 @@ func BenchmarkMarshalJSON(b *testing.B) { } } } + +func BenchmarkUnmarshalJSON(b *testing.B) { + b.ReportAllocs() + var k Key + buf, err := k.MarshalJSON() + if err != nil { + b.Fatal(err) + } + for i := 0; i < b.N; i++ { + err := k.UnmarshalJSON(buf) + if err != nil { + b.Fatal(err) + } + } +}