subspace_networking/utils/
key_with_distance.rsuse libp2p::kad::KBucketDistance;
pub use libp2p::kad::RecordKey;
pub use libp2p::PeerId;
use std::cmp::Ordering;
use std::hash::Hash;
type KademliaBucketKey<T> = libp2p::kad::KBucketKey<T>;
#[derive(Debug, Clone, Eq)]
pub struct KeyWithDistance {
key: RecordKey,
distance: KBucketDistance,
}
impl KeyWithDistance {
pub fn new<K>(peer_id: PeerId, key: K) -> Self
where
RecordKey: From<K>,
{
Self::new_with_record_key(peer_id, RecordKey::from(key))
}
pub fn new_with_record_key(peer_id: PeerId, key: RecordKey) -> Self {
let peer_key = KademliaBucketKey::from(peer_id);
let distance = KademliaBucketKey::new(key.as_ref()).distance(&peer_key);
Self { key, distance }
}
pub fn record_key(&self) -> &RecordKey {
&self.key
}
}
impl PartialEq for KeyWithDistance {
fn eq(&self, other: &Self) -> bool {
self.key == other.key
}
}
impl PartialOrd for KeyWithDistance {
fn partial_cmp(&self, other: &Self) -> Option<Ordering> {
Some(self.cmp(other))
}
}
impl Ord for KeyWithDistance {
fn cmp(&self, other: &Self) -> Ordering {
self.distance.cmp(&other.distance)
}
}
impl Hash for KeyWithDistance {
fn hash<H: std::hash::Hasher>(&self, state: &mut H) {
self.key.hash(state);
}
}