protocols/kad: Implement ilog2 for Distance (#1719)

In order to make use of the distances returned by `KBucketRef::range` in
a human readable format, one needs to be able to translate the 256 bit in
a `Distance` to a smaller space.
This commit is contained in:
Max Inden 2020-08-28 09:00:07 +02:00 committed by GitHub
parent 73f596ef32
commit 0136af5025
No known key found for this signature in database
GPG Key ID: 4AEE18F83AFDEB23
2 changed files with 10 additions and 3 deletions

View File

@ -106,9 +106,7 @@ impl BucketIndex {
/// `local_key` is the `local_key` itself, which does not belong in any
/// bucket.
fn new(d: &Distance) -> Option<BucketIndex> {
(NUM_BUCKETS - d.0.leading_zeros() as usize)
.checked_sub(1)
.map(BucketIndex)
d.ilog2().map(|i| BucketIndex(i as usize))
}
/// Gets the index value as an unsigned integer.

View File

@ -169,6 +169,15 @@ impl AsRef<KeyBytes> for KeyBytes {
#[derive(Copy, Clone, PartialEq, Eq, Default, PartialOrd, Ord, Debug)]
pub struct Distance(pub(super) U256);
impl Distance {
/// Returns the integer part of the base 2 logarithm of the [`Distance`].
///
/// Returns `None` if the distance is zero.
pub fn ilog2(&self) -> Option<u32> {
(256 - self.0.leading_zeros()).checked_sub(1)
}
}
#[cfg(test)]
mod tests {
use super::*;