1use serde::{Deserialize, Serialize};
2use std::fmt;
3
4#[derive(Debug, Clone, PartialEq, Eq, Hash, PartialOrd, Ord, Serialize, Deserialize)]
10pub struct PeerId(String);
11
12impl PeerId {
13 pub fn new_with_rng<R: rand::Rng>(rng: &mut R) -> Self {
15 let id: u64 = rng.random();
16 Self(format!("peer-{id}"))
17 }
18
19 pub fn from_string(s: String) -> Self {
21 Self(s)
22 }
23
24 pub fn as_str(&self) -> &str {
26 &self.0
27 }
28
29 pub fn into_string(self) -> String {
31 self.0
32 }
33}
34
35impl fmt::Display for PeerId {
36 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
37 write!(f, "{}", self.0)
38 }
39}
40
41impl From<String> for PeerId {
42 fn from(s: String) -> Self {
43 PeerId(s)
44 }
45}
46
47impl From<&str> for PeerId {
48 fn from(s: &str) -> Self {
49 PeerId(s.to_string())
50 }
51}
52
53#[derive(Debug, Clone, PartialEq, Eq)]
54pub enum PeerIdError {
55 InvalidFormat,
56}
57
58impl fmt::Display for PeerIdError {
59 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
60 match self {
61 PeerIdError::InvalidFormat => write!(f, "Invalid peer ID format"),
62 }
63 }
64}
65
66impl std::error::Error for PeerIdError {}