1use serde::{Deserialize, Serialize};
3use std::fmt;
4use weirdnet_net::{Keypair, PeerId, PublicKey};
5
6#[derive(Clone, Debug, PartialEq, Eq, Hash, PartialOrd, Ord, Serialize, Deserialize)]
8#[serde(transparent)]
9pub struct UserId(String);
10
11#[derive(Debug, thiserror::Error)]
13#[error("not a peer id: {0}")]
14pub struct IdError(pub String);
15
16impl UserId {
17 pub fn parse(s: &str) -> Result<UserId, IdError> {
19 s.parse::<PeerId>().map(|p| UserId(p.to_string())).map_err(|_| IdError(s.to_string()))
20 }
21
22 pub fn of_key(pk: &PublicKey) -> UserId {
24 UserId(pk.to_peer_id().to_string())
25 }
26
27 pub fn of_keypair(kp: &Keypair) -> UserId {
29 Self::of_key(&kp.public())
30 }
31
32 pub fn of_key_bytes(b: &[u8]) -> Option<UserId> {
34 PublicKey::try_decode_protobuf(b).ok().map(|pk| Self::of_key(&pk))
35 }
36
37 pub fn as_str(&self) -> &str {
39 &self.0
40 }
41
42 pub fn short(&self) -> &str {
44 let n = self.0.len();
45 &self.0[n.saturating_sub(8)..]
46 }
47}
48
49impl fmt::Display for UserId {
50 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
51 f.write_str(&self.0)
52 }
53}