Skip to content

Commit ea09e70

Browse files
device: cache peer string
I am not sure why it must be fast but there were previous efforts 25ad08a and 9087e44 to speed it up; and I even did my own WireGuard#60. If that is so important lets cache peer string to make it fast and readable again. Signed-off-by: Alexander Yastrebov <[email protected]>
1 parent f333402 commit ea09e70

File tree

1 file changed

+6
-23
lines changed

1 file changed

+6
-23
lines changed

device/peer.go

Lines changed: 6 additions & 23 deletions
Original file line numberDiff line numberDiff line change
@@ -7,6 +7,7 @@ package device
77

88
import (
99
"container/list"
10+
"encoding/base64"
1011
"errors"
1112
"sync"
1213
"sync/atomic"
@@ -24,6 +25,7 @@ type Peer struct {
2425
txBytes atomic.Uint64 // bytes send to peer (endpoint)
2526
rxBytes atomic.Uint64 // bytes received from peer
2627
lastHandshakeNano atomic.Int64 // nano seconds since epoch
28+
string string // cached [Peer.String]
2729

2830
endpoint struct {
2931
sync.Mutex
@@ -107,6 +109,9 @@ func (device *Device) NewPeer(pk NoisePublicKey) (*Peer, error) {
107109
// init timers
108110
peer.timersInit()
109111

112+
base64Key := base64.StdEncoding.EncodeToString(pk[:])
113+
peer.string = "peer(" + base64Key[0:4] + "…" + base64Key[39:43] + ")"
114+
110115
// add
111116
device.peers.keyMap[pk] = peer
112117

@@ -145,29 +150,7 @@ func (peer *Peer) SendBuffers(buffers [][]byte) error {
145150
}
146151

147152
func (peer *Peer) String() string {
148-
// The awful goo that follows is identical to:
149-
//
150-
// base64Key := base64.StdEncoding.EncodeToString(peer.handshake.remoteStatic[:])
151-
// abbreviatedKey := base64Key[0:4] + "…" + base64Key[39:43]
152-
// return fmt.Sprintf("peer(%s)", abbreviatedKey)
153-
//
154-
// except that it is considerably more efficient.
155-
src := peer.handshake.remoteStatic
156-
b64 := func(input byte) byte {
157-
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)
158-
}
159-
b := []byte("peer(____…____)")
160-
const first = len("peer(")
161-
const second = len("peer(____…")
162-
b[first+0] = b64((src[0] >> 2) & 63)
163-
b[first+1] = b64(((src[0] << 4) | (src[1] >> 4)) & 63)
164-
b[first+2] = b64(((src[1] << 2) | (src[2] >> 6)) & 63)
165-
b[first+3] = b64(src[2] & 63)
166-
b[second+0] = b64(src[29] & 63)
167-
b[second+1] = b64((src[30] >> 2) & 63)
168-
b[second+2] = b64(((src[30] << 4) | (src[31] >> 4)) & 63)
169-
b[second+3] = b64((src[31] << 2) & 63)
170-
return string(b)
153+
return peer.string
171154
}
172155

173156
func (peer *Peer) Start() {

0 commit comments

Comments
 (0)