use serde::{Deserialize, Serialize};
use std::{
fmt::{self, Display, Formatter},
hash::Hash,
net::SocketAddr,
};
use xor_name::XorName;
#[derive(Clone, Copy, Debug, Hash, PartialEq, PartialOrd, Ord, Eq, Serialize, Deserialize)]
pub struct Peer {
name: XorName,
addr: SocketAddr,
age: u8,
}
impl Peer {
pub fn new(name: XorName, addr: SocketAddr, age: u8) -> Self {
Self { name, addr, age }
}
pub fn name(&self) -> &XorName {
&self.name
}
pub fn addr(&self) -> &SocketAddr {
&self.addr
}
pub fn age(&self) -> u8 {
self.age
}
pub fn with_age(self, age: u8) -> Self {
Self { age, ..self }
}
pub fn increment_age(self) -> Self {
Self {
age: self.age.saturating_add(1),
..self
}
}
}
impl Display for Peer {
fn fmt(&self, f: &mut Formatter) -> fmt::Result {
write!(f, "{} at {}", self.name, self.addr)
}
}
#[cfg(test)]
pub(crate) mod test_utils {
use super::*;
use proptest::{collection::SizeRange, prelude::*};
use xor_name::XOR_NAME_LEN;
pub(crate) fn arbitrary_xor_name() -> impl Strategy<Value = XorName> {
any::<[u8; XOR_NAME_LEN]>().prop_map(XorName)
}
pub(crate) fn arbitrary_unique_peers(
count: impl Into<SizeRange>,
age: impl Strategy<Value = u8>,
) -> impl Strategy<Value = Vec<Peer>> {
proptest::collection::btree_map(arbitrary_xor_name(), (any::<SocketAddr>(), age), count)
.prop_map(|peers| {
peers
.into_iter()
.map(|(name, (addr, age))| Peer::new(name, addr, age))
.collect()
})
}
}