use crate::peer::{Error, Result};
use rand::RngExt;
use std::fmt::{Debug, Display, Formatter};
const ID_PREFIX: &str = "-RW0082-";
#[derive(Copy, Clone, PartialEq, Eq, Hash)]
pub struct PeerId([u8; 20]);
impl PeerId {
pub fn new() -> Self {
let id = Self::generate_peer_id();
Self {
0: id
.as_bytes()
.try_into()
.expect("peer id should be exactly 20 bytes long"),
}
}
pub fn value(&self) -> [u8; 20] {
self.0.clone()
}
pub fn as_slice(&self) -> &[u8] {
&self.0
}
fn generate_peer_id() -> String {
let mut rng = rand::rng();
let suffix: String = (0..12)
.map(|_| rng.random_range(b'0'..=b'9') as char)
.collect();
format!("{}{}", ID_PREFIX, suffix)
}
}
impl Display for PeerId {
fn fmt(&self, f: &mut Formatter<'_>) -> std::fmt::Result {
write!(f, "{}", String::from_utf8_lossy(&self.0))
}
}
impl Debug for PeerId {
fn fmt(&self, f: &mut Formatter<'_>) -> std::fmt::Result {
write!(f, "{}", String::from_utf8_lossy(&self.0))
}
}
impl TryFrom<&[u8]> for PeerId {
type Error = Error;
fn try_from(value: &[u8]) -> Result<Self> {
if value.len() != 20 {
return Err(Error::InvalidPeerId);
}
let mut buffer = [0u8; 20];
buffer.copy_from_slice(value);
Ok(Self(buffer))
}
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn test_peer_id_new() {
let result = PeerId::new();
assert_eq!(20, result.0.len(), "expected the peer id length to be 20");
assert!(
result.to_string().starts_with(ID_PREFIX),
"expected the peer id to start with the fixed prefix"
);
}
#[test]
fn test_generate_peer_id() {
let result = PeerId::generate_peer_id();
assert_eq!(20, result.len(), "expected the peer id length to be 20");
}
#[test]
fn test_peer_id_display() {
let peer_str = format!("{}123456789012", ID_PREFIX);
let peer_bytes = peer_str.as_bytes();
let peer_id = PeerId::try_from(peer_bytes).unwrap();
let result = peer_id.to_string();
assert_eq!(peer_str, result.as_str());
}
}