samod_core/
peer_id.rs

1use serde::{Deserialize, Serialize};
2use std::fmt;
3
4/// Unique identifier for a peer in the sync network.
5///
6/// Peer IDs are ephemeral identifiers that identify a specific instance
7/// of a peer (e.g., a browser tab, a process). They are UTF-8 strings
8/// that are different from storage IDs which identify the underlying storage.
9#[derive(Debug, Clone, PartialEq, Eq, Hash, PartialOrd, Ord, Serialize, Deserialize)]
10pub struct PeerId(String);
11
12impl PeerId {
13    /// Creates a new peer ID with a generated value using the provided RNG.
14    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    /// Creates a peer ID from a string.
20    pub fn from_string(s: String) -> Self {
21        Self(s)
22    }
23
24    /// Returns the peer ID as a string slice.
25    pub fn as_str(&self) -> &str {
26        &self.0
27    }
28
29    /// Returns the peer ID as a String.
30    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 {}