Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

protocols/kad: Implement log2 for Distance #1719

Merged
merged 7 commits into from
Aug 28, 2020
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
4 changes: 1 addition & 3 deletions protocols/kad/src/kbucket.rs
Original file line number Diff line number Diff line change
Expand Up @@ -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.
Expand Down
9 changes: 9 additions & 0 deletions protocols/kad/src/kbucket/key.rs
Original file line number Diff line number Diff line change
Expand Up @@ -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)
mxinden marked this conversation as resolved.
Show resolved Hide resolved
}
}

#[cfg(test)]
mod tests {
use super::*;
Expand Down