mirror of
https://github.com/ethereum/go-ethereum.git
synced 2026-07-23 05:06:43 +00:00
p2p/enode: opt LogDist
This commit is contained in:
parent
659342a523
commit
225d0095b3
2 changed files with 32 additions and 5 deletions
|
|
@ -19,6 +19,7 @@ package enode
|
||||||
import (
|
import (
|
||||||
"crypto/ecdsa"
|
"crypto/ecdsa"
|
||||||
"encoding/base64"
|
"encoding/base64"
|
||||||
|
"encoding/binary"
|
||||||
"encoding/hex"
|
"encoding/hex"
|
||||||
"errors"
|
"errors"
|
||||||
"fmt"
|
"fmt"
|
||||||
|
|
@ -372,15 +373,19 @@ func DistCmp(target, a, b ID) int {
|
||||||
|
|
||||||
// LogDist returns the logarithmic distance between a and b, log2(a ^ b).
|
// LogDist returns the logarithmic distance between a and b, log2(a ^ b).
|
||||||
func LogDist(a, b ID) int {
|
func LogDist(a, b ID) int {
|
||||||
|
lenA := len(a)
|
||||||
|
totalBits := lenA * 8
|
||||||
lz := 0
|
lz := 0
|
||||||
for i := range a {
|
for i := 0; i < lenA; i += 8 {
|
||||||
x := a[i] ^ b[i]
|
ai := binary.BigEndian.Uint64(a[i : i+8])
|
||||||
|
bi := binary.BigEndian.Uint64(b[i : i+8])
|
||||||
|
x := ai ^ bi
|
||||||
if x == 0 {
|
if x == 0 {
|
||||||
lz += 8
|
lz += 64
|
||||||
} else {
|
} else {
|
||||||
lz += bits.LeadingZeros8(x)
|
lz += bits.LeadingZeros64(x)
|
||||||
break
|
break
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
return len(a)*8 - lz
|
return totalBits - lz
|
||||||
}
|
}
|
||||||
|
|
|
||||||
|
|
@ -378,6 +378,28 @@ func TestID_logdist(t *testing.T) {
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
func makeIDs() (ID, ID) {
|
||||||
|
var a, b ID
|
||||||
|
size := len(a)
|
||||||
|
// last byte differs
|
||||||
|
for i := 0; i < size-1; i++ {
|
||||||
|
a[i] = 0xAA
|
||||||
|
b[i] = 0xAA
|
||||||
|
}
|
||||||
|
a[size-1] = 0xAA
|
||||||
|
b[size-1] = 0xAB
|
||||||
|
return a, b
|
||||||
|
}
|
||||||
|
|
||||||
|
// Benchmark LogDist
|
||||||
|
func BenchmarkLogDist(b *testing.B) {
|
||||||
|
aID, bID := makeIDs() // 256-bit ID
|
||||||
|
b.ResetTimer()
|
||||||
|
for i := 0; i < b.N; i++ {
|
||||||
|
_ = LogDist(aID, bID)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
// The random tests is likely to miss the case where a and b are equal,
|
// The random tests is likely to miss the case where a and b are equal,
|
||||||
// this test checks it explicitly.
|
// this test checks it explicitly.
|
||||||
func TestID_logdistEqual(t *testing.T) {
|
func TestID_logdistEqual(t *testing.T) {
|
||||||
|
|
|
||||||
Loading…
Reference in a new issue