@@ -20,6 +20,8 @@ proc new*(
2020 maxBuckets: int = DefaultMaxBuckets ,
2121 selfIdPreHashed = false ,
2222): T =
23+ doAssert maxBuckets > 0 and maxBuckets <= MaxBucketsLimit ,
24+ " maxBuckets must be in 1 .. " & $ MaxBucketsLimit
2325 RoutingTableConfig (
2426 replication: replication,
2527 hasher: hasher,
@@ -40,6 +42,9 @@ proc new*(
4042 selfId: selfId, localNodeId: localNodeId.get (selfId), buckets: @ [], config: config
4143 )
4244
45+ func bucketCount (maxBuckets: int ): int =
46+ clamp (maxBuckets, 1 , MaxBucketsLimit )
47+
4348proc bucketIndex * (rtable: RoutingTable , key: Key ): int =
4449 let
4550 selfHash =
@@ -50,10 +55,7 @@ proc bucketIndex*(rtable: RoutingTable, key: Key): int =
5055 keyHash = key.hashFor (rtable.config.hasher)
5156 lz = xorDistance (selfHash, keyHash).leadingZeros
5257
53- if rtable.config.maxBuckets <= 1 :
54- return 0
55-
56- return min (((lz * rtable.config.maxBuckets) div 256 ), rtable.config.maxBuckets - 1 )
58+ min (lz, bucketCount (rtable.config.maxBuckets) - 1 )
5759
5860proc peerIndexInBucket (bucket: Bucket , nodeId: Key ): Opt [int ] =
5961 for i, p in bucket.peers:
@@ -209,9 +211,7 @@ proc randomKeyInBucket*(
209211 selfId: Key , bucketIndex: int , rng: Rng , maxBuckets: int = DefaultMaxBuckets
210212): Key =
211213 let
212- index = clamp (bucketIndex, 0 , (maxBuckets - 1 ))
213- buckets = max (1 , maxBuckets)
214- leadingZeros = index * 256 div buckets
214+ leadingZeros = clamp (bucketIndex, 0 , bucketCount (maxBuckets) - 1 )
215215 (byteIdx, rem) = divmod (leadingZeros, 8 )
216216 boundBitIdx = 7 - rem
217217
0 commit comments