From e9066ee6257d6c302e130a11703d134069ea5cf3 Mon Sep 17 00:00:00 2001 From: Josh Bleecher Snyder Date: Fri, 7 May 2021 21:38:31 -0700 Subject: [PATCH] types/wgkey: optimize Key.ShortString MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit name old time/op new time/op delta ShortString-8 82.6ns ± 0% 15.6ns ± 0% -81.07% (p=0.008 n=5+5) name old alloc/op new alloc/op delta ShortString-8 104B ± 0% 8B ± 0% -92.31% (p=0.008 n=5+5) name old allocs/op new allocs/op delta ShortString-8 3.00 ± 0% 1.00 ± 0% -66.67% (p=0.008 n=5+5) Signed-off-by: Josh Bleecher Snyder --- types/wgkey/key.go | 12 ++++++++++-- 1 file changed, 10 insertions(+), 2 deletions(-) diff --git a/types/wgkey/key.go b/types/wgkey/key.go index fe757083a..3e2252010 100644 --- a/types/wgkey/key.go +++ b/types/wgkey/key.go @@ -78,8 +78,16 @@ func (k Key) HexString() string { return hex.EncodeToString(k[:]) } func (k Key) Equal(k2 Key) bool { return subtle.ConstantTimeCompare(k[:], k2[:]) == 1 } func (k *Key) ShortString() string { - long := k.Base64() - return "[" + long[0:5] + "]" + // The goal here is to generate "[" + base64.StdEncoding.EncodeToString(k[:])[:5] + "]". + // Since we only care about the first 5 characters, it suffices to encode the first 4 bytes of k. + // Encoding those 4 bytes requires 8 bytes. + // Make dst have size 9, to fit the leading '[' plus those 8 bytes. + // We slice the unused ones away at the end. + dst := make([]byte, 9) + dst[0] = '[' + base64.StdEncoding.Encode(dst[1:], k[:4]) + dst[6] = ']' + return string(dst[:7]) } func (k *Key) IsZero() bool {