mirror of
https://github.com/fluencelabs/rust-libp2p
synced 2025-05-28 10:11:19 +00:00
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:
parent
73f596ef32
commit
0136af5025
@ -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.
|
||||
|
@ -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::*;
|
||||
|
Loading…
x
Reference in New Issue
Block a user