From ea09e705e7915ea7586636eef456267d323b9440 Mon Sep 17 00:00:00 2001 From: Alexander Yastrebov Date: Sat, 31 May 2025 11:49:50 +0200 Subject: [PATCH] device: cache peer string I am not sure why it must be fast but there were previous efforts 25ad08a59157ed8a9750e827c658260b4138fd93 and 9087e444e6457a21fdb1037b9ed204ac417abc05 to speed it up; and I even did my own #60. If that is so important lets cache peer string to make it fast and readable again. Signed-off-by: Alexander Yastrebov --- device/peer.go | 29 ++++++----------------------- 1 file changed, 6 insertions(+), 23 deletions(-) diff --git a/device/peer.go b/device/peer.go index ebf25f941..8fa90ff2d 100644 --- a/device/peer.go +++ b/device/peer.go @@ -7,6 +7,7 @@ package device import ( "container/list" + "encoding/base64" "errors" "sync" "sync/atomic" @@ -24,6 +25,7 @@ type Peer struct { txBytes atomic.Uint64 // bytes send to peer (endpoint) rxBytes atomic.Uint64 // bytes received from peer lastHandshakeNano atomic.Int64 // nano seconds since epoch + string string // cached [Peer.String] endpoint struct { sync.Mutex @@ -107,6 +109,9 @@ func (device *Device) NewPeer(pk NoisePublicKey) (*Peer, error) { // init timers peer.timersInit() + base64Key := base64.StdEncoding.EncodeToString(pk[:]) + peer.string = "peer(" + base64Key[0:4] + "…" + base64Key[39:43] + ")" + // add device.peers.keyMap[pk] = peer @@ -145,29 +150,7 @@ func (peer *Peer) SendBuffers(buffers [][]byte) error { } func (peer *Peer) String() string { - // The awful goo that follows is identical to: - // - // base64Key := base64.StdEncoding.EncodeToString(peer.handshake.remoteStatic[:]) - // abbreviatedKey := base64Key[0:4] + "…" + base64Key[39:43] - // return fmt.Sprintf("peer(%s)", abbreviatedKey) - // - // except that it is considerably more efficient. - src := peer.handshake.remoteStatic - b64 := func(input byte) byte { - return input + 'A' + byte(((25-int(input))>>8)&6) - byte(((51-int(input))>>8)&75) - byte(((61-int(input))>>8)&15) + byte(((62-int(input))>>8)&3) - } - b := []byte("peer(____…____)") - const first = len("peer(") - const second = len("peer(____…") - b[first+0] = b64((src[0] >> 2) & 63) - b[first+1] = b64(((src[0] << 4) | (src[1] >> 4)) & 63) - b[first+2] = b64(((src[1] << 2) | (src[2] >> 6)) & 63) - b[first+3] = b64(src[2] & 63) - b[second+0] = b64(src[29] & 63) - b[second+1] = b64((src[30] >> 2) & 63) - b[second+2] = b64(((src[30] << 4) | (src[31] >> 4)) & 63) - b[second+3] = b64((src[31] << 2) & 63) - return string(b) + return peer.string } func (peer *Peer) Start() {