Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

device: optimize Peer.String even more so #60

Open
wants to merge 1 commit into
base: master
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
32 changes: 21 additions & 11 deletions device/peer.go
Original file line number Diff line number Diff line change
Expand Up @@ -139,20 +139,30 @@ func (peer *Peer) String() string {
//
// 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)
const encodeStd = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/"

// Convert 3x 8bit source bytes into 4 bytes
val := uint(src[0+0])<<16 | uint(src[0+1])<<8 | uint(src[0+2])

b[first+0] = encodeStd[val>>18&0x3F]
b[first+1] = encodeStd[val>>12&0x3F]
b[first+2] = encodeStd[val>>6&0x3F]
b[first+3] = encodeStd[val&0x3F]

val = /*uint(src[27+0])<<16 | uint(src[27+1])<<8 |*/ uint(src[27+2])

b[second+0] = encodeStd[val&0x3F]

val = uint(src[30+0])<<16 | uint(src[30+1])<<8 /*| uint(src[30+2])*/

b[second+1] = encodeStd[val>>18&0x3F]
b[second+2] = encodeStd[val>>12&0x3F]
b[second+3] = encodeStd[val>>6&0x3F]

return string(b)
}

Expand Down
20 changes: 20 additions & 0 deletions device/peer_test.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,20 @@
package device

import (
"testing"
)

var sinkS string

func BenchmarkPeerString(b *testing.B) {
k := [32]byte{0: 0x4e, 1: 0xb3, 2: 0x2f, 29: 0x16, 30: 0x5d, 31: 0x7d} // TrMv…WXX0
p := &Peer{handshake: Handshake{remoteStatic: k}}
s := p.String()

b.ResetTimer()
b.ReportAllocs()
for i := 0; i < b.N; i++ {
s = p.String()
}
sinkS = s
}