Unverified Commit 2bd723f9 authored by Steven Allen's avatar Steven Allen Committed by GitHub

Merge pull request #20 from libp2p/nit/performance

small perf improvements
parents 5f4553e0 666d5702
......@@ -4,6 +4,7 @@ import (
"bytes"
"crypto/sha256"
"math/big"
"math/bits"
u "github.com/ipfs/go-ipfs-util"
)
......@@ -44,23 +45,14 @@ func (s *xorKeySpace) Distance(k1, k2 Key) *big.Int {
// Less returns whether the first key is smaller than the second.
func (s *xorKeySpace) Less(k1, k2 Key) bool {
a := k1.Bytes
b := k2.Bytes
for i := 0; i < len(a); i++ {
if a[i] != b[i] {
return a[i] < b[i]
}
}
return true
return bytes.Compare(k1.Bytes, k2.Bytes) < 0
}
// ZeroPrefixLen returns the number of consecutive zeroes in a byte slice.
func ZeroPrefixLen(id []byte) int {
for i := 0; i < len(id); i++ {
for j := 0; j < 8; j++ {
if (id[i]>>uint8(7-j))&0x1 != 0 {
return i*8 + j
}
for i, b := range id {
if b != 0 {
return i*8 + bits.LeadingZeros8(uint8(b))
}
}
return len(id) * 8
......
......@@ -89,12 +89,10 @@ func (rt *RoutingTable) Update(p peer.ID) {
// If this bucket is the rightmost bucket, and its full
// we need to split it and create a new bucket
if bucketID == len(rt.Buckets)-1 {
rt.PeerRemoved(rt.nextBucket())
return
rt.nextBucket()
} else {
// If the bucket cant split kick out least active node
rt.PeerRemoved(bucket.PopBack())
return
}
}
}
......@@ -117,19 +115,18 @@ func (rt *RoutingTable) Remove(p peer.ID) {
rt.PeerRemoved(p)
}
func (rt *RoutingTable) nextBucket() peer.ID {
func (rt *RoutingTable) nextBucket() {
bucket := rt.Buckets[len(rt.Buckets)-1]
newBucket := bucket.Split(len(rt.Buckets)-1, rt.local)
rt.Buckets = append(rt.Buckets, newBucket)
if newBucket.Len() > rt.bucketsize {
return rt.nextBucket()
rt.nextBucket()
}
// If all elements were on left side of split...
if bucket.Len() > rt.bucketsize {
return bucket.PopBack()
rt.PeerRemoved(bucket.PopBack())
}
return ""
}
// Find a specific peer by ID or return nil
......
Markdown is supported
0% or .
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment