1use std::fmt;
2use std::str::FromStr;
3use std::sync::Arc;
4
5#[derive(Clone, PartialEq, Eq, PartialOrd, Ord, Hash)]
14pub struct Identity {
15 text: Arc<str>,
16 minted: bool,
17}
18
19#[derive(Debug, Clone, Copy, PartialEq, Eq, thiserror::Error)]
21#[error("invalid identity: {0}")]
22#[non_exhaustive]
23pub struct InvalidIdentity(&'static str);
24
25pub(crate) const MAX_LEN: usize = 256;
28
29impl Identity {
30 pub fn random() -> Self {
32 Self::named(random().into())
33 }
34
35 fn named(text: Arc<str>) -> Self {
36 Self { text, minted: false }
37 }
38
39 #[cfg_attr(not(feature = "async"), allow(dead_code, reason = "async-only"))]
41 pub(crate) fn minted() -> Self {
42 Self {
43 text: random().into(),
44 minted: true,
45 }
46 }
47
48 pub(crate) fn decoded(text: &str, minted: bool) -> Result<Self, InvalidIdentity> {
50 Ok(Self {
51 minted,
52 ..text.parse()?
53 })
54 }
55
56 pub fn as_str(&self) -> &str {
58 &self.text
59 }
60
61 pub fn is_minted(&self) -> bool {
67 self.minted
68 }
69}
70
71fn random() -> String {
73 use rand::RngExt;
74 format!("{:032x}", kio::clock::rng().random::<u128>())
75}
76
77impl FromStr for Identity {
78 type Err = InvalidIdentity;
79
80 fn from_str(text: &str) -> Result<Self, Self::Err> {
81 check(text)?;
82 Ok(Self::named(text.into()))
83 }
84}
85
86fn check(text: &str) -> Result<(), InvalidIdentity> {
88 match text.len() {
89 0 => Err(InvalidIdentity("empty")),
90 len if len > MAX_LEN => Err(InvalidIdentity("longer than 256 bytes")),
91 _ => Ok(()),
92 }
93}
94
95impl TryFrom<String> for Identity {
96 type Error = InvalidIdentity;
97
98 fn try_from(text: String) -> Result<Self, Self::Error> {
99 check(&text)?;
100 Ok(Self::named(text.into()))
101 }
102}
103
104impl fmt::Debug for Identity {
105 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
106 let mut debug = f.debug_tuple("Identity");
107 debug.field(&self.as_str());
108 if self.minted {
109 debug.field(&"minted");
110 }
111 debug.finish()
112 }
113}
114
115impl fmt::Display for Identity {
116 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
117 f.write_str(self.as_str())
118 }
119}
120
121impl AsRef<str> for Identity {
122 fn as_ref(&self) -> &str {
123 self.as_str()
124 }
125}
126
127#[cfg(test)]
128mod tests {
129 use super::*;
130
131 #[test]
132 fn random_is_fresh_and_round_trips() {
133 let identity = Identity::random();
134 assert_ne!(identity, Identity::random());
135 assert_eq!(identity.as_str().parse::<Identity>().unwrap(), identity);
136 assert!("".parse::<Identity>().is_err());
137 assert!(!identity.is_minted());
138 }
139
140 #[test]
141 fn text_never_builds_a_minted_identity() {
142 let minted = Identity::minted();
143 assert!(minted.is_minted());
144 let named: Identity = minted.as_str().parse().unwrap();
145 assert!(!named.is_minted());
146 assert_ne!(named, minted, "the same text, named, is another identity");
147 assert!(!"~tilde".parse::<Identity>().unwrap().is_minted());
148 assert_eq!(Identity::decoded(minted.as_str(), true).unwrap(), minted);
149 assert!(Identity::decoded("", true).is_err());
150 }
151
152 #[test]
153 fn caps_at_256_utf8_bytes() {
154 let full = "é".repeat(128);
155 assert_eq!(full.parse::<Identity>().unwrap().as_str(), full);
156 assert!(format!("{full}a").parse::<Identity>().is_err());
157 assert!(Identity::try_from(format!("{full}a")).is_err());
158 assert!(Identity::decoded(&format!("{full}a"), true).is_err());
159 }
160}