sos_core/
identity.rs

1//! Public identity information.
2use crate::AccountId;
3use crate::Error;
4use serde::{Deserialize, Serialize};
5use std::{fmt, str::FromStr};
6
7/// Public account identity information.
8#[typeshare::typeshare]
9#[derive(Debug, Clone, Serialize, Deserialize, Eq, PartialEq, Hash)]
10#[serde(rename_all = "camelCase")]
11pub struct PublicIdentity {
12    /// Account identifier.
13    account_id: AccountId,
14    /// Label for the account.
15    ///
16    /// This is the name given to the identity vault.
17    label: String,
18}
19
20impl PublicIdentity {
21    /// Create new account information.
22    pub fn new(account_id: AccountId, label: String) -> Self {
23        Self { account_id, label }
24    }
25
26    /// Get the account identifier.
27    pub fn account_id(&self) -> &AccountId {
28        &self.account_id
29    }
30
31    /// Get the label of this account.
32    pub fn label(&self) -> &str {
33        &self.label
34    }
35
36    /// Set the account label.
37    pub fn set_label(&mut self, label: String) {
38        self.label = label;
39    }
40}
41
42impl From<&PublicIdentity> for AccountRef {
43    fn from(value: &PublicIdentity) -> Self {
44        AccountRef::Id(*value.account_id())
45    }
46}
47
48impl From<PublicIdentity> for AccountRef {
49    fn from(value: PublicIdentity) -> Self {
50        (&value).into()
51    }
52}
53
54/// Reference to an account using an address or a named label.
55#[derive(Debug, Clone)]
56pub enum AccountRef {
57    /// Account identifier.
58    Id(AccountId),
59    /// Account label.
60    Name(String),
61}
62
63impl fmt::Display for AccountRef {
64    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
65        match self {
66            Self::Id(id) => write!(f, "{}", id),
67            Self::Name(name) => write!(f, "{}", name),
68        }
69    }
70}
71
72impl FromStr for AccountRef {
73    type Err = Error;
74    fn from_str(s: &str) -> std::result::Result<Self, Self::Err> {
75        if let Ok(id) = s.parse::<AccountId>() {
76            Ok(Self::Id(id))
77        } else {
78            Ok(Self::Name(s.to_string()))
79        }
80    }
81}