summaryrefslogtreecommitdiffhomepage
diff options
context:
space:
mode:
authorJosh Bleecher Snyder <josh@tailscale.com>2021-05-07 21:38:31 -0700
committerJosh Bleecher Snyder <josharian@gmail.com>2021-05-10 09:43:44 -0700
commite9066ee6257d6c302e130a11703d134069ea5cf3 (patch)
treee27726bcb5ac0148970db69fd95b77f016a56c1d
parent7cd4766d5e8bd9cc41b57c87be29aa34f988e0f7 (diff)
downloadtailscale-e9066ee6257d6c302e130a11703d134069ea5cf3.tar.xz
tailscale-e9066ee6257d6c302e130a11703d134069ea5cf3.zip
types/wgkey: optimize Key.ShortString
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 <josh@tailscale.com>
-rw-r--r--types/wgkey/key.go12
1 files 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 {