weirdnet-contacts 0.1.0

A contact book for Weirdnet apps: trusted and blocked identities, presence with privacy rules (base to everyone, detail to trusted contacts), signed text direct messages with delivery state and an offline queue, and contact links, served over weirdnet-service.
Documentation
//! The identity type.
use serde::{Deserialize, Serialize};
use std::fmt;
use weirdnet_net::{Keypair, PeerId, PublicKey};

/// An identity: a Weirdnet peer id, as text. It is the key for contacts, blocks and bans.
#[derive(Clone, Debug, PartialEq, Eq, Hash, PartialOrd, Ord, Serialize, Deserialize)]
#[serde(transparent)]
pub struct UserId(String);

/// A string that is not a peer id.
#[derive(Debug, thiserror::Error)]
#[error("not a peer id: {0}")]
pub struct IdError(pub String);

impl UserId {
    /// Checks that `s` is a peer id.
    pub fn parse(s: &str) -> Result<UserId, IdError> {
        s.parse::<PeerId>().map(|p| UserId(p.to_string())).map_err(|_| IdError(s.to_string()))
    }

    /// The identity of a public key.
    pub fn of_key(pk: &PublicKey) -> UserId {
        UserId(pk.to_peer_id().to_string())
    }

    /// The identity of a keypair.
    pub fn of_keypair(kp: &Keypair) -> UserId {
        Self::of_key(&kp.public())
    }

    /// The identity of a protobuf-encoded public key, if it decodes.
    pub fn of_key_bytes(b: &[u8]) -> Option<UserId> {
        PublicKey::try_decode_protobuf(b).ok().map(|pk| Self::of_key(&pk))
    }

    /// The peer id text.
    pub fn as_str(&self) -> &str {
        &self.0
    }

    /// The first characters, for a label when there is no name.
    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)
    }
}