1use std::fmt;
5
6#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
9pub struct KeyId(pub [u8; 8]);
10
11impl KeyId {
12 #[must_use]
14 pub fn generate() -> KeyId {
15 KeyId(random())
16 }
17
18 pub fn parse(text: &str) -> Option<KeyId> {
21 unhex(text).map(KeyId)
22 }
23
24 pub(crate) fn bytes(self) -> [u8; 8] {
26 self.0
27 }
28}
29
30#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
32pub struct TenantId(pub [u8; 16]);
33
34impl TenantId {
35 #[must_use]
37 pub fn generate() -> TenantId {
38 TenantId(random())
39 }
40
41 pub fn parse(text: &str) -> Option<TenantId> {
44 unhex(text).map(TenantId)
45 }
46}
47
48#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, PartialOrd, Ord)]
50pub struct UserId(pub [u8; 16]);
51
52impl UserId {
53 #[must_use]
55 pub fn generate() -> UserId {
56 UserId(random())
57 }
58
59 pub fn parse(text: &str) -> Option<UserId> {
62 unhex(text).map(UserId)
63 }
64}
65
66impl fmt::Display for UserId {
67 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
68 hex(&self.0, f)
69 }
70}
71
72#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
74pub struct VersionId(pub [u8; 16]);
75
76impl VersionId {
77 #[must_use]
79 pub fn generate() -> VersionId {
80 VersionId(random())
81 }
82}
83
84impl VersionId {
85 pub fn parse(text: &str) -> Option<VersionId> {
88 unhex(text).map(VersionId)
89 }
90}
91
92#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
94pub struct FileId(pub [u8; 16]);
95
96impl FileId {
97 #[must_use]
99 pub fn generate() -> FileId {
100 FileId(random())
101 }
102
103 pub fn parse(text: &str) -> Option<FileId> {
106 unhex(text).map(FileId)
107 }
108}
109
110fn random<const N: usize>() -> [u8; N] {
111 let mut bytes = [0; N];
112 aws_lc_rs::rand::fill(&mut bytes).expect("AWS-LC aborts instead of failing");
115 bytes
116}
117
118fn unhex<const N: usize>(text: &str) -> Option<[u8; N]> {
120 let digits = text.as_bytes();
121 if digits.len() != 2 * N {
122 return None;
123 }
124 let digit = |d: u8| match d {
125 b'0'..=b'9' => Some(d - b'0'),
126 b'a'..=b'f' => Some(d - b'a' + 10),
127 _ => None,
128 };
129 let mut bytes = [0; N];
130 let (pairs, _) = digits.as_chunks::<2>();
131 for (byte, [high, low]) in bytes.iter_mut().zip(pairs) {
132 *byte = digit(*high)? << 4 | digit(*low)?;
133 }
134 Some(bytes)
135}
136
137fn hex(bytes: &[u8], f: &mut fmt::Formatter<'_>) -> fmt::Result {
138 bytes.iter().try_for_each(|b| write!(f, "{b:02x}"))
139}
140
141impl fmt::Display for KeyId {
142 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
143 hex(&self.0, f)
144 }
145}
146
147impl fmt::Display for TenantId {
148 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
149 hex(&self.0, f)
150 }
151}
152
153impl fmt::Display for VersionId {
154 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
155 hex(&self.0, f)
156 }
157}
158
159impl fmt::Display for FileId {
160 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
161 hex(&self.0, f)
162 }
163}
164
165#[cfg(test)]
166mod tests {
167 use super::*;
168
169 #[test]
170 fn ids_are_written_as_32_lowercase_hex_digits() {
171 let mut bytes = [0; 16];
172 bytes[0] = 0x0a;
173 bytes[15] = 0xff;
174 let expected = format!("0a{}ff", "00".repeat(14));
175 assert_eq!(
176 TenantId(bytes).to_string(),
177 expected,
178 "two lower-case hex digits per byte, in order, zeros kept"
179 );
180 assert_eq!(
181 VersionId(bytes).to_string(),
182 expected,
183 "two lower-case hex digits per byte, in order, zeros kept"
184 );
185 }
186
187 fn varies(ids: &[[u8; 16]]) {
189 for i in 0..16 {
190 assert!(
191 ids.iter().any(|id| id[i] != ids[0][i]),
192 "byte {i} never varies"
193 );
194 }
195 }
196
197 #[test]
198 fn a_key_id_is_64_random_bits_written_as_16_hex_digits() {
199 let ids: Vec<[u8; 8]> = (0..8).map(|_| KeyId::generate().0).collect();
200 for i in 0..8 {
201 assert!(
202 ids.iter().any(|id| id[i] != ids[0][i]),
203 "byte {i} never varies"
204 );
205 }
206 let id = KeyId([0x0a, 0, 0, 0, 0, 0, 0, 0xff]);
207 assert_eq!(
208 id.to_string(),
209 "0a000000000000ff",
210 "two lower-case hex digits per byte, in order, zeros kept"
211 );
212 assert_eq!(
213 KeyId::parse("0a000000000000ff"),
214 Some(id),
215 "parse reads the spelling Display writes"
216 );
217 for bad in [
218 "0A000000000000FF",
219 "0a000000000000f",
220 "0a000000000000ff0",
221 "",
222 ] {
223 assert_eq!(KeyId::parse(bad), None, "{bad:?}");
224 }
225 }
226
227 #[test]
228 fn ids_are_random() {
229 varies(&(0..8).map(|_| VersionId::generate().0).collect::<Vec<_>>());
230 varies(&(0..8).map(|_| TenantId::generate().0).collect::<Vec<_>>());
231 varies(&(0..8).map(|_| FileId::generate().0).collect::<Vec<_>>());
232 }
233
234 #[test]
237 fn a_file_id_parses_only_from_its_own_spelling() {
238 let mut bytes = [0; 16];
239 bytes[0] = 0x0a;
240 bytes[15] = 0xff;
241 assert_eq!(
242 FileId(bytes).to_string(),
243 format!("0a{}ff", "00".repeat(14)),
244 "two lower-case hex digits per byte, in order, zeros kept"
245 );
246 let file = FileId::generate();
247 assert_eq!(
248 FileId::parse(&file.to_string()),
249 Some(file),
250 "parse reads the spelling Display writes"
251 );
252 let text = file.to_string();
253 for bad in misspelled(&text) {
254 if bad != text {
255 assert_eq!(
256 FileId::parse(&bad),
257 None,
258 "not a file id's spelling: {bad:?}"
259 );
260 }
261 }
262 }
263
264 fn misspelled(text: &str) -> [String; 7] {
266 [
267 String::new(),
268 text[..31].to_owned(),
269 format!("{text}0"),
270 text.to_uppercase(),
271 format!("g{}", &text[1..]),
272 format!("{text}.tmp"),
273 format!("+{}", &text[1..]),
274 ]
275 }
276
277 #[test]
278 fn tenant_and_version_ids_parse_only_from_their_own_spelling() {
279 let tenant = TenantId::generate();
280 let version = VersionId::generate();
281 assert_eq!(
282 TenantId::parse(&tenant.to_string()),
283 Some(tenant),
284 "parse reads the spelling Display writes"
285 );
286 assert_eq!(
287 VersionId::parse(&version.to_string()),
288 Some(version),
289 "parse reads the spelling Display writes"
290 );
291 for (text, parsed) in [
292 (
293 tenant.to_string(),
294 (|t: &str| TenantId::parse(t).is_some()) as fn(&str) -> bool,
295 ),
296 (version.to_string(), |t: &str| VersionId::parse(t).is_some()),
297 ] {
298 for bad in misspelled(&text) {
299 if bad != text {
301 assert!(!parsed(&bad), "not an id's own spelling: {bad:?}");
302 }
303 }
304 }
305 }
306}