p2p/enode: opt DistCmp

This commit is contained in:
cuiweixie 2025-10-12 20:19:31 +08:00
parent 659342a523
commit bacd81ee73
No known key found for this signature in database
GPG key ID: 16DF64EE15E495A3
2 changed files with 16 additions and 3 deletions

View file

@ -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"
@ -358,9 +359,11 @@ func ParseID(in string) (ID, error) {
// Returns -1 if a is closer to target, 1 if b is closer to target // Returns -1 if a is closer to target, 1 if b is closer to target
// and 0 if they are equal. // and 0 if they are equal.
func DistCmp(target, a, b ID) int { func DistCmp(target, a, b ID) int {
for i := range target { const size = 8
da := a[i] ^ target[i] n := len(target)
db := b[i] ^ target[i] for i := 0; i+size <= n; i += size {
da := binary.BigEndian.Uint64(a[i:i+size]) ^ binary.BigEndian.Uint64(target[i:i+size])
db := binary.BigEndian.Uint64(b[i:i+size]) ^ binary.BigEndian.Uint64(target[i:i+size])
if da > db { if da > db {
return 1 return 1
} else if da < db { } else if da < db {

View file

@ -368,6 +368,16 @@ func TestID_distcmpEqual(t *testing.T) {
} }
} }
func BenchmarkDistCmp(b *testing.B) {
base := ID{0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15}
aID := ID{15, 14, 13, 12, 11, 10, 9, 8, 7, 6, 5, 4, 3, 2, 1, 0}
bID := ID{15, 14, 13, 12, 11, 10, 9, 8, 7, 6, 5, 4, 3, 2, 1, 1}
b.ResetTimer()
for i := 0; i < b.N; i++ {
_ = DistCmp(base, aID, bID)
}
}
func TestID_logdist(t *testing.T) { func TestID_logdist(t *testing.T) {
logdistBig := func(a, b ID) int { logdistBig := func(a, b ID) int {
abig, bbig := new(big.Int).SetBytes(a[:]), new(big.Int).SetBytes(b[:]) abig, bbig := new(big.Int).SetBytes(a[:]), new(big.Int).SetBytes(b[:])