use serde::{Deserialize, Serialize};
use std::fmt;
use weirdnet_net::{Keypair, PeerId, PublicKey};
#[derive(Clone, Debug, PartialEq, Eq, Hash, PartialOrd, Ord, Serialize, Deserialize)]
#[serde(transparent)]
pub struct UserId(String);
#[derive(Debug, thiserror::Error)]
#[error("not a peer id: {0}")]
pub struct IdError(pub String);
impl UserId {
pub fn parse(s: &str) -> Result<UserId, IdError> {
s.parse::<PeerId>().map(|p| UserId(p.to_string())).map_err(|_| IdError(s.to_string()))
}
pub fn of_key(pk: &PublicKey) -> UserId {
UserId(pk.to_peer_id().to_string())
}
pub fn of_keypair(kp: &Keypair) -> UserId {
Self::of_key(&kp.public())
}
pub fn of_key_bytes(b: &[u8]) -> Option<UserId> {
PublicKey::try_decode_protobuf(b).ok().map(|pk| Self::of_key(&pk))
}
pub fn as_str(&self) -> &str {
&self.0
}
pub fn short(&self) -> &str {
let n = self.0.len();
&self.0[n.saturating_sub(8)..]
}
}
impl fmt::Display for UserId {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
f.write_str(&self.0)
}
}