Skip to content

Commit 9087e44

Browse files
committed
device: optimize Peer.String even more
This reduces the allocation, branches, and amount of base64 encoding. Signed-off-by: Jason A. Donenfeld <[email protected]>
1 parent 25ad08a commit 9087e44

File tree

1 file changed

+16
-14
lines changed

1 file changed

+16
-14
lines changed

device/peer.go

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

88
import (
99
"container/list"
10-
"encoding/base64"
1110
"errors"
1211
"sync"
1312
"sync/atomic"
@@ -150,19 +149,22 @@ func (peer *Peer) String() string {
150149
// return fmt.Sprintf("peer(%s)", abbreviatedKey)
151150
//
152151
// except that it is considerably more efficient.
153-
const prefix = "peer("
154-
b := make([]byte, len(prefix)+44)
155-
copy(b, prefix)
156-
r := b[len(prefix):]
157-
base64.StdEncoding.Encode(r, peer.handshake.remoteStatic[:])
158-
r = r[4:]
159-
copy(r, "…")
160-
r = r[len("…"):]
161-
copy(r, b[len(prefix)+39:len(prefix)+43])
162-
r = r[4:]
163-
r[0] = ')'
164-
r = r[1:]
165-
return string(b[:len(b)-len(r)])
152+
src := peer.handshake.remoteStatic
153+
b64 := func(input byte) byte {
154+
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)
155+
}
156+
b := []byte("peer(____…____)")
157+
const first = len("peer(")
158+
const second = len("peer(____…")
159+
b[first+0] = b64((src[0] >> 2) & 63)
160+
b[first+1] = b64(((src[0] << 4) | (src[1] >> 4)) & 63)
161+
b[first+2] = b64(((src[1] << 2) | (src[2] >> 6)) & 63)
162+
b[first+3] = b64(src[2] & 63)
163+
b[second+0] = b64(src[29] & 63)
164+
b[second+1] = b64((src[30] >> 2) & 63)
165+
b[second+2] = b64(((src[30] << 4) | (src[31] >> 4)) & 63)
166+
b[second+3] = b64((src[31] << 2) & 63)
167+
return string(b)
166168
}
167169

168170
func (peer *Peer) Start() {

0 commit comments

Comments
 (0)