use std::cmp::Ordering;
use std::fmt;
use std::ops::BitXor;
use super::constants::ID_LENGTH;
#[derive(Clone, Copy, PartialEq, Eq, Hash)]
pub struct NodeId(pub [u8; ID_LENGTH]);
impl NodeId {
pub const ZERO: NodeId = NodeId([0u8; ID_LENGTH]);
pub const MAX: NodeId = NodeId([0xFFu8; ID_LENGTH]);
pub fn from_slice(data: &[u8]) -> Self {
assert_eq!(data.len(), ID_LENGTH, "NodeId must be exactly 20 bytes");
let mut id = [0u8; ID_LENGTH];
id.copy_from_slice(data);
NodeId(id)
}
pub fn random() -> Self {
use rand::RngCore;
let mut id = [0u8; ID_LENGTH];
rand::thread_rng().fill_bytes(&mut id);
NodeId(id)
}
pub fn as_bytes(&self) -> &[u8; ID_LENGTH] {
&self.0
}
pub fn distance_to(&self, other: &NodeId) -> NodeId {
let result: [u8; ID_LENGTH] = std::array::from_fn(|i| self.0[i] ^ other.0[i]);
NodeId(result)
}
pub fn common_prefix_len(&self, other: &NodeId) -> usize {
let dist = self.distance_to(other);
let mut count = 0usize;
for &byte in &dist.0 {
if byte == 0 {
count += 8;
} else {
count += byte.leading_zeros() as usize;
break;
}
}
count
}
pub fn get_bit(&self, index: usize) -> bool {
let byte_idx = index / 8;
let bit_idx = 7 - (index % 8);
if byte_idx >= ID_LENGTH {
return false;
}
(self.0[byte_idx] >> bit_idx) & 1 == 1
}
pub fn flip_bit(&mut self, index: usize) {
let byte_idx = index / 8;
let bit_idx = 7 - (index % 8);
if byte_idx < ID_LENGTH {
self.0[byte_idx] ^= 1 << bit_idx;
}
}
pub fn is_in_range(&self, min: &NodeId, max: &NodeId) -> bool {
self >= min && self <= max
}
pub fn to_hex(&self) -> String {
hex::encode(self.0)
}
}
impl BitXor for NodeId {
type Output = NodeId;
fn bitxor(self, rhs: NodeId) -> NodeId {
self.distance_to(&rhs)
}
}
impl fmt::Debug for NodeId {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
write!(f, "NodeId({})", self.to_hex())
}
}
impl fmt::Display for NodeId {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
write!(f, "{}", self.to_hex())
}
}
impl Ord for NodeId {
fn cmp(&self, other: &Self) -> Ordering {
for i in 0..ID_LENGTH {
match self.0[i].cmp(&other.0[i]) {
Ordering::Equal => continue,
other => return other,
}
}
Ordering::Equal
}
}
impl PartialOrd for NodeId {
fn partial_cmp(&self, other: &Self) -> Option<Ordering> {
Some(self.cmp(other))
}
}
impl AsRef<[u8; ID_LENGTH]> for NodeId {
fn as_ref(&self) -> &[u8; ID_LENGTH] {
&self.0
}
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn zero_id() {
assert_eq!(NodeId::ZERO.0, [0u8; ID_LENGTH]);
}
#[test]
fn max_id() {
assert_eq!(NodeId::MAX.0, [0xFFu8; ID_LENGTH]);
}
#[test]
fn from_slice() {
let data = [0xABu8; ID_LENGTH];
let id = NodeId::from_slice(&data);
assert_eq!(id.0, [0xABu8; ID_LENGTH]);
}
#[test]
#[should_panic]
fn from_slice_wrong_length() {
let data = [0u8; 10];
let _ = NodeId::from_slice(&data);
}
#[test]
fn xor_distance() {
let a = NodeId::from_slice(&[0xFF; ID_LENGTH]);
let b = NodeId::ZERO;
let dist = a.distance_to(&b);
assert_eq!(dist.0, [0xFF; ID_LENGTH]);
let c = NodeId::ZERO;
let d = NodeId::ZERO;
assert_eq!(c.distance_to(&d).0, [0; ID_LENGTH]);
}
#[test]
fn common_prefix_len_identical() {
let a = NodeId::from_slice(&[0xFF; ID_LENGTH]);
assert_eq!(a.common_prefix_len(&a), 160);
}
#[test]
fn common_prefix_len_diff_first_bit() {
let mut a_data = [0u8; ID_LENGTH];
a_data[0] = 0x80;
let a = NodeId(a_data);
let b = NodeId::ZERO;
assert_eq!(a.common_prefix_len(&b), 0);
}
#[test]
fn common_prefix_len_diff_second_bit() {
let mut a_data = [0u8; ID_LENGTH];
a_data[0] = 0x40;
let a = NodeId(a_data);
let b = NodeId::ZERO;
assert_eq!(a.common_prefix_len(&b), 1);
}
#[test]
fn get_bit() {
let mut data = [0u8; ID_LENGTH];
data[0] = 0b1000_0000; data[1] = 0b0000_0001; let id = NodeId(data);
assert!(id.get_bit(0));
assert!(!id.get_bit(1));
assert!(!id.get_bit(7));
assert!(id.get_bit(15));
}
#[test]
fn flip_bit() {
let mut id = NodeId::ZERO;
id.flip_bit(0);
assert_eq!(id.0[0], 0x80);
id.flip_bit(0);
assert_eq!(id.0[0], 0x00);
id.flip_bit(7);
assert_eq!(id.0[0], 0x01);
}
#[test]
fn range_check() {
let min = NodeId::ZERO;
let max = NodeId::MAX;
let mid = NodeId::from_slice(&[0x80; ID_LENGTH]);
assert!(mid.is_in_range(&min, &max));
assert!(NodeId::ZERO.is_in_range(&min, &max));
assert!(NodeId::MAX.is_in_range(&min, &max));
}
#[test]
fn ordering() {
let mut a_data = [0u8; ID_LENGTH];
a_data[0] = 0x01;
let a = NodeId(a_data);
let b = NodeId::ZERO;
assert!(a > b);
assert!(b < a);
}
#[test]
fn display_hex() {
let id = NodeId::from_slice(&[0xAB; ID_LENGTH]);
assert_eq!(id.to_hex(), "ab".repeat(ID_LENGTH));
}
#[test]
fn random_produces_valid_id() {
let id = NodeId::random();
assert_ne!(id.0, [0u8; ID_LENGTH]);
}
}