use std::net;
type NodeLink = Option<Box<Node>>;
#[derive(Debug)]
pub struct BucketTree {
pub node_id: [u8; 64],
pub root: Node,
}
#[derive(Debug)]
pub enum Node {
BranchNode(BranchNode),
LeafNode(LeafNode),
}
#[derive(Debug)]
pub struct BranchNode {
pub left: NodeLink,
pub right: NodeLink,
}
#[derive(Debug)]
pub struct LeafNode {
pub can_split: bool,
pub contacts: Vec<NodeInfo>,
}
#[derive(Debug)]
pub enum Address {
V4(net::Ipv4Addr),
V6(net::Ipv6Addr),
}
#[derive(Debug)]
pub struct NodeInfo {
id: [u8; 64],
ip: Address,
port: u64,
}
impl BucketTree {
pub fn new(node_id: [u8; 64]) -> Self {
BucketTree {
node_id,
root: Node::LeafNode(LeafNode {
can_split: true,
contacts: Vec::new(),
}),
}
}
pub fn add(&mut self, node: &NodeInfo) {
let mut current_node = &mut self.root;
let mut bit_index = 0;
while let Node::BranchNode(x) = current_node {
if bit_value(&node.id, bit_index) {
current_node = x.right.as_mut().unwrap();
} else {
current_node = x.left.as_mut().unwrap();
}
bit_index += 1;
continue;
}
println!("{:?}", current_node);
}
}
impl LeafNode {
#[allow(clippy::all)]
pub fn new() -> Option<Box<Node>> {
Some(Box::new(Node::LeafNode(LeafNode {
can_split: true,
contacts: Vec::new(),
})))
}
}
impl BranchNode {
#[allow(clippy::all)]
pub fn new() -> Option<Box<Node>> {
Some(Box::new(Node::BranchNode(BranchNode {
left: None,
right: None,
})))
}
}
impl NodeInfo {
pub fn new(id: [u8; 64], ip: Address, port: u64) -> Self {
NodeInfo { id, ip, port }
}
}
fn bit_value(key: &[u8; 64], bit_index: usize) -> bool {
let byte_index = bit_index >> 3;
let inner_bit_index = bit_index % 8;
key[byte_index] & (1 << (7 - inner_bit_index)) >= 1
}