#[cfg(feature = "serialize")]
use serde_derive::{Deserialize, Serialize};
use std::cmp::Ordering;
use std::fmt;
use std::net::SocketAddr;
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, PartialOrd, Ord)]
#[cfg_attr(feature = "serialize", derive(Serialize, Deserialize))]
pub struct LocalNodeId(u64);
impl LocalNodeId {
pub fn new(id: u64) -> Self {
LocalNodeId(id)
}
pub fn value(self) -> u64 {
self.0
}
}
#[derive(Clone, Copy, PartialEq, Eq, Hash)]
#[cfg_attr(feature = "serialize", derive(Serialize, Deserialize))]
pub struct NodeId {
address: SocketAddr,
local_id: LocalNodeId,
}
impl NodeId {
pub fn new(address: SocketAddr, local_id: LocalNodeId) -> Self {
NodeId { address, local_id }
}
pub fn address(&self) -> SocketAddr {
self.address
}
pub fn local_id(&self) -> LocalNodeId {
self.local_id
}
}
impl fmt::Debug for NodeId {
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
write!(f, "NodeId({:?})", self.to_string())
}
}
impl fmt::Display for NodeId {
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
write!(f, "{:08x}@{}", self.local_id.0, self.address)
}
}
impl PartialOrd for NodeId {
fn partial_cmp(&self, other: &Self) -> Option<Ordering> {
Some(self.cmp(other))
}
}
impl Ord for NodeId {
fn cmp(&self, other: &Self) -> Ordering {
self.address
.ip()
.cmp(&other.address.ip())
.then_with(|| self.address.port().cmp(&other.address.port()))
.then_with(|| self.local_id.cmp(&other.local_id))
}
}