strong_id 0.4.0

Strongly typed, base32 encoded IDs
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
//! Strongly typed IDs which optionally satisfy the [TypeID](https://github.com/jetpack-io/typeid) specification.
//!
//! A StrongId is any type which implements `StrongId<T: Id>`.
//!
//! The `Id` trait is implemented for `u8`, `u16`, `u32`, `u64`, `u128`, `usize` and when the `"uuid"` feature is enabled,
//! `Uuid`.
//!
//! ## Examples
//!
//! ### Dynamic StrongIds
//!
//! #### ID with a prefix
//! ```rust
//! use strong_id::{prefix, DynamicStrongId};
//!
//! let user_id = DynamicStrongId::<u16>::new(prefix!("user"), 3203).unwrap();
//! println!("{}", user_id); // user_0343
//!
//! let user_id = "user_0343".parse::<DynamicStrongId<u16>>().unwrap();
//! println!("{:#?}", user_id);
//! // DynamicStrongId {
//! //     prefix: Some(
//! //        Prefix {
//! //           inner: "user",
//! //        ,
//! //     ),
//! //     suffix: 3203,
//! // }
//! ```
//!
//! #### ID without a prefix
//!
//! ```rust
//! use strong_id::{prefix, DynamicStrongId};
//!
//! let id = DynamicStrongId::<u16>::new_plain(3203);
//! println!("{}", id); // 0343
//!
//! let id = "0343".parse::<DynamicStrongId<u16>>().unwrap();
//! println!("{:#?}", id);
//! // DynamicStrongId {
//! //     prefix: None,
//! //     suffix: 3203,
//! // }
//! ```
//!
//! #### TypeId with a prefix
//!
//! ```rust,ignore
//! use strong_id::{prefix, DynamicStrongId};
//! use uuid::Uuid;
//!
//! let user_id = DynamicStrongId::<Uuid>::now_v7(prefix!("user")).unwrap();
//! println!("{}", user_id); // user_01h536gfwffx2rm6pa0xg63337
//!
//! let user_id = "user_01h536gfwffx2rm6pa0xg63337"
//!     .parse::<DynamicStrongId<Uuid>>()
//!     .unwrap();
//! println!("{:#?}", user_id);
//! // DynamicStrongId {
//! //     prefix: Some(
//! //        Prefix {
//! //            inner: "user",
//! //        },
//! //     ),
//! //     suffix: 01894668-3f8f-7f45-8a1a-ca0760618c67,
//! // }
//! ```
//!
//! #### TypeId without a prefix
//!
//! ```rust,ignore
//! use strong_id::{prefix, DynamicStrongId};
//! use uuid::Uuid;
//!
//! let id = DynamicStrongId::<Uuid>::now_v7_plain();
//! println!("{}", id); // 01h536gfwffx2rm6pa0xg63337
//!
//! let id = "01h536gfwffx2rm6pa0xg63337"
//!     .parse::<DynamicStrongId<Uuid>>()
//!     .unwrap();
//! println!("{:#?}", id);
//! // DynamicStrongId {
//! //     prefix: None,
//! //     suffix: 01894668-3f8f-7f45-8a1a-ca0760618c67,
//! // }
//! ```
//!
//! ### Generated StrongIds
//!
//! #### ID with a prefix
//! ```rust
//! use strong_id::strong_id;
//!
//! strong_id!(pub struct UserId(u16 => "user"));
//!
//! let user_id = UserId::from(3203);
//! println!("{}", user_id); // user_0343
//!
//! let user_id = "user_0343".parse::<UserId>().unwrap();
//! println!("{:#?}", user_id);
//! // UserId {
//! //     suffix: 3203,
//! // }
//! ```
//!
//! #### ID without a prefix
//!
//! ```rust
//! use strong_id::strong_id;
//!
//! strong_id!(pub struct Id(u16));
//!
//! let id = Id::from(3203);
//! println!("{}", id); // user_0343
//!
//! let id = "0343".parse::<Id>().unwrap();
//! println!("{:#?}", id);
//! // Id {
//! //     suffix: 3203,
//! // }
//! ```
//!
//! #### Generated TypeId with a prefix
//!
//! ```rust,ignore
//! use strong_id::{strong_uuid, StrongUuid};
//!
//! strong_uuid!(pub struct UserId(pub Uuid => "user"));
//!
//! let user_id = UserId::now_v7();
//! println!("{}", user_id); // user_01h536z8abez196j2nzz06y8c8
//!
//! let user_id = "user_01h536z8abez196j2nzz06y8c8".parse::<UserId>().unwrap();
//! println!("{:#?}", user_id);
//! // UserId {
//! //     suffix: 0189466f-a14b-77c2-9348-55ffc06f2188,
//! // }
//! ```
//!
//! Alternatively, derive [`StrongUuid`] yourself:
//!
//! ```rust
//! use strong_id::{strong_id, StrongUuid};
//! use uuid::Uuid;
//!
//! strong_id! {
//!     #[derive(StrongUuid)]
//!     pub struct UserId(pub Uuid => "user")
//! }
//! ```
//!
//! If you don't need the utility functions, then just create a Uuid-backed ID:
//!
//! ```rust
//! use strong_id::strong_id;
//! use uuid::Uuid;
//!
//! strong_id!(pub struct UserId(pub Uuid));
//! ```
//!
//! Note that this would still require the "uuid" feature so that the [`Id`] trait can be implemented
//! for Uuid.
//!
//! #### Generated TypeId without a prefix
//!
//! ```rust,ignore
//! use strong_id::{strong_uuid, StrongUuid};
//!
//! strong_uuid!(pub struct Id(pub Uuid);
//!
//! let id = Id::now_v7();
//! println!("{}", id); // 01h5372sq2egxb6ps3taq7p6np
//!
//! let id = "01h5372sq2egxb6ps3taq7p6np".parse::<Id>().unwrap();
//! println!("{:#?}", id);
//! // UserId {
//! //     suffix: 01894671-66e2-743a-b35b-23d2ae7b1ab6,
//! // }
//! ```

#![cfg_attr(docsrs, feature(doc_cfg))]

extern crate self as strong_id;

mod base32;
mod dynamic;

use crate::base32::encoded_len;
pub use dynamic::*;
use thiserror::Error;

pub use base32::Base32Error;
pub use strong_id_macros::*;

#[cfg(feature = "uuid")]
pub use uuid;
#[cfg(feature = "uuid")]
use uuid::Uuid;

#[cfg(feature = "serde")]
pub use serde;

/// Represents a type which can be encoded and decoded
pub trait Id {
	/// Encode the value into a `String`
	fn encode(&self) -> String;
	/// Decode the value from a `str`
	fn decode<T: AsRef<str>>(val: T) -> Result<Self, Error>
	where
		Self: Sized;
}

/// Represents a type which can be used as a StrongId
pub trait StrongId<T: Id>: core::fmt::Display + core::str::FromStr {
	fn prefix(&self) -> Option<&str>;
	fn id(&self) -> &T;
}

/// Utility trait to allow StrongId's backed by a Uuid to wrap calls to Uuid `new_` and `now_`
/// functions.
#[cfg(feature = "uuid")]
#[cfg_attr(docsrs, doc(cfg(feature = "uuid")))]
pub trait StrongUuid {
	fn from_u128(v: u128) -> Self;

	#[cfg(feature = "uuid-v1")]
	#[cfg_attr(docsrs, doc(cfg(feature = "uuid-v1")))]
	fn new_v1(ts: uuid::Timestamp, node_id: &[u8; 6]) -> Self;

	#[cfg(feature = "uuid-v1")]
	#[cfg_attr(docsrs, doc(cfg(feature = "uuid-v1")))]
	fn now_v1(node_id: &[u8; 6]) -> Self;

	#[cfg(feature = "uuid-v3")]
	#[cfg_attr(docsrs, doc(cfg(feature = "uuid-v3")))]
	fn new_v3(namespace: &Uuid, name: &[u8]) -> Self;

	#[cfg(feature = "uuid-v4")]
	#[cfg_attr(docsrs, doc(cfg(feature = "uuid-v4")))]
	fn new_v4() -> Self;

	#[cfg(feature = "uuid-v5")]
	#[cfg_attr(docsrs, doc(cfg(feature = "uuid-v5")))]
	fn new_v5(namespace: &Uuid, name: &[u8]) -> Self;

	#[cfg(feature = "uuid-v6")]
	#[cfg_attr(docsrs, doc(cfg(all(feature = "uuid-v6"))))]
	fn new_v6(ts: uuid::Timestamp, node_id: &[u8; 6]) -> Self;

	#[cfg(feature = "uuid-v6")]
	#[cfg_attr(docsrs, doc(cfg(all(feature = "uuid-v6"))))]
	fn now_v6(node_id: &[u8; 6]) -> Self;

	#[cfg(feature = "uuid-v7")]
	#[cfg_attr(docsrs, doc(cfg(all(feature = "uuid-v7"))))]
	fn new_v7(ts: uuid::Timestamp) -> Self;

	#[cfg(feature = "uuid-v7")]
	#[cfg_attr(docsrs, doc(cfg(all(feature = "uuid-v7"))))]
	fn now_v7() -> Self;

	#[cfg(feature = "uuid-v8")]
	#[cfg_attr(docsrs, doc(cfg(all(feature = "uuid-v8"))))]
	fn new_v8(buf: [u8; 16]) -> Self;
}

macro_rules! impl_strong_uint {
	($t:ty) => {
		impl Id for $t {
			fn encode(&self) -> ::std::string::String {
				let mut out = [0u8; encoded_len::<$t>()];
				::strong_id::base32::encode(&self.to_be_bytes(), &mut out);
				let encoded = unsafe { ::core::str::from_utf8_unchecked(&out) };
				encoded.to_string()
			}

			fn decode<T: AsRef<str>>(val: T) -> ::core::result::Result<Self, ::strong_id::Error> {
				let val = val.as_ref();
				if val.len() != encoded_len::<$t>() {
					return Err(::strong_id::Error::InvalidLength(encoded_len::<$t>(), val.len()));
				}

				let mut out = [0; ::core::mem::size_of::<$t>()];
				::strong_id::base32::decode(val.as_bytes(), &mut out)?;

				Ok(Self::from_be_bytes(out))
			}
		}
	};
}

impl_strong_uint!(u8);
impl_strong_uint!(u16);
impl_strong_uint!(u32);
impl_strong_uint!(u64);
impl_strong_uint!(u128);
impl_strong_uint!(usize);

#[cfg(feature = "uuid")]
impl Id for Uuid {
	fn encode(&self) -> String {
		let mut out = [0; 26];
		base32::encode(self.as_bytes(), &mut out);
		let encoded = unsafe { core::str::from_utf8_unchecked(&out) };
		encoded.to_string()
	}

	fn decode<T: AsRef<str>>(val: T) -> Result<Self, Error> {
		let val = val.as_ref();
		if val.len() != 26 {
			return Err(Error::InvalidLength(26, val.len()));
		}
		let mut out = [0; 16];
		base32::decode(val.as_bytes(), &mut out)?;

		Ok(Self::from_bytes(out))
	}
}

/// Errors which may occur when creating or parsing StrongIds
#[derive(Error, Debug, Eq, PartialEq)]
pub enum Error {
	/// Created from a [`Base32Error`]
	#[error(transparent)]
	Base32Error(#[from] Base32Error),
	/// A prefix was expected, but was not found
	#[error("expected prefix `{0}`")]
	MissingPrefix(String),
	/// The given prefix did not match the expected prefix
	#[error("invalid prefix. expected {0}, found {1}")]
	InvalidPrefix(String, String),
	/// A prefix was expected to be configured, but was not found
	#[error("no prefix was given, but one was expected")]
	PrefixExpected,
	/// A prefix was given, but none was expected
	#[error("found prefix `{0}`, none expected")]
	NoPrefixExpected(String),
	/// The length of the encoded value to be decoded was incorrect
	#[error("invalid length. expected {0}, found {1}")]
	InvalidLength(usize, usize),
	/// The prefix is too long
	#[error("prefix too long. should be less than 64 characters, found {0}")]
	PrefixTooLong(usize),
	/// A non-alphanumeric, non-lowercase character was found. When the "delimited" feature is
	/// enabled, this will not include the `'_'` character.
	#[error("prefix may only contain lowercase ascii characters, found `{0}`")]
	IncorrectPrefixCharacter(char),
}

/// Generate a StrongId
///
/// TODO examples
#[macro_export]
macro_rules! strong_id {
    (
        $(#[$outer:meta])*
        $vis:vis struct $t:ident($inner_vis:vis $inner:ty)
    ) => {
        $crate::_internal_strong_id! {
            $(#[$outer])*
            $vis struct $t($inner_vis $inner)
        }
    };
    (
        $(#[$outer:meta])*
        $vis:vis struct $t:ident($inner_vis:vis $inner:ty => $prefix:literal)
    ) => {
        $crate::_internal_strong_id! {
            $(#[$outer])*
            $vis struct $t($inner_vis $inner => $prefix)
        }
    };
}

#[macro_export]
#[doc(hidden)]
macro_rules! _internal_strong_id {
    (
        $(#[$outer:meta])*
        $vis:vis struct $t:ident($inner_vis:vis $inner:ty$( => $prefix:literal)?)
    ) => {
        $(#[$outer])*
        #[derive(Copy, Clone, Debug, Eq, PartialEq, Hash, Ord, PartialOrd)]
        #[derive($crate::StrongId)]
		#[strong_id($(prefix = $prefix, )?suffix = "suffix")]
        $vis struct $t($inner_vis $inner);

		$crate::_internal_impl_common!(@@internal $t($inner));

		$crate::_internal_impl_from_str!(@@internal $t($inner => $($prefix)?));
    };
}

/// Generate a StrongId backed by a [`Uuid`].
///
/// This is a convenient wrapper around to [`strong_id`] which derives [`StrongUuid`].
#[cfg(feature = "uuid")]
#[cfg_attr(docsrs, doc(cfg(feature = "uuid")))]
#[macro_export]
macro_rules! strong_uuid {
    (
        $(#[$outer:meta])*
        $vis:vis struct $t:ident($inner_vis:vis Uuid)
    ) => {
        $crate::_internal_strong_uuid! {
            $(#[$outer])*
            $vis struct $t($inner_vis Uuid)
        }
    };
    (
        $(#[$outer:meta])*
        $vis:vis struct $t:ident($inner_vis:vis Uuid => $prefix:literal)
    ) => {
        $crate::_internal_strong_uuid! {
            $(#[$outer])*
            $vis struct $t($inner_vis Uuid => $prefix)
        }
    };
}

#[cfg(feature = "uuid")]
#[macro_export]
#[doc(hidden)]
macro_rules! _internal_strong_uuid {
    (
        $(#[$outer:meta])*
        $vis:vis struct $t:ident($inner_vis:vis Uuid$( => $prefix:literal)?)
    ) => {
		$crate::strong_id!{
			#[derive($crate::StrongUuid)]
            $(#[$outer])*
			$vis struct $t($inner_vis $crate::uuid::Uuid$( => $prefix)?)
		}
    };
}

#[macro_export]
#[doc(hidden)]
macro_rules! _internal_impl_common {
	(@@internal $t:ident($inner:ty)) => {
		impl ::core::fmt::Display for $t {
			fn fmt(&self, f: &mut ::core::fmt::Formatter<'_>) -> ::core::fmt::Result {
				use $crate::{Id, StrongId};
				match self.prefix() {
					Some(prefix) => write!(f, "{}_{}", prefix, self.0.encode()),
					None => write!(f, "{}", self.0.encode()),
				}
			}
		}

		impl From<$t> for $inner {
			fn from(value: $t) -> Self {
				value.0
			}
		}

		impl From<$inner> for $t {
			fn from(value: $inner) -> Self {
				Self(value)
			}
		}
	};
}

#[macro_export]
#[doc(hidden)]
macro_rules! _internal_impl_from_str {
	(@@internal $t:ident($inner:ty => $($prefix:literal)?)) => {
        impl ::core::str::FromStr for $t {
			type Err = $crate::Error;

            #[inline]
            fn from_str(value: &str) -> ::core::result::Result<Self, Self::Err> {
				let split = value.rsplit_once('_');

				#[allow(unused_mut)]
				#[allow(unused_assignments)]
				let mut prefix: Option<&str> = None;
				$(prefix = Some($prefix);)?

                let suffix = match prefix {
                    Some(prefix) => {
						 match split {
							  None => return Err($crate::Error::MissingPrefix(prefix.into())),
							  Some((parsed_prefix, _suffix)) if parsed_prefix.is_empty() => return Err($crate::Error::MissingPrefix(prefix.into())),
							  Some((parsed_prefix, suffix)) => {
								  if parsed_prefix != prefix {
									  return Err($crate::Error::InvalidPrefix(prefix.to_string(), parsed_prefix.to_string()));
								  }

								  <$inner as $crate::Id>::decode(suffix)?
							  },
						 }
					},
                    None => {
						 match split {
							  Some((parsed_prefix, _suffix)) => return Err($crate::Error::NoPrefixExpected(parsed_prefix.to_string())),
							  None => <$inner as $crate::Id>::decode(value)?
						 }
					}
                };

				Ok(Self(suffix))
            }
        }
	}
}

#[cfg(test)]
mod tests {
	use super::*;

	#[test]
	fn u32_prefix_valid() {
		strong_id!(pub struct PrefixU32(u32 => "prefix"));

		assert_eq!(PrefixU32::from(0).prefix(), Some("prefix"));

		struct Case(&'static str, u32);
		let cases = vec![
			Case("prefix_0000000", u32::MIN),
			Case("prefix_3zzzzzz", u32::MAX),
			Case("prefix_000009d", 301),
		];

		for case in cases {
			let id = PrefixU32::from(case.1);
			assert_eq!(&format!("{id}"), case.0);
			assert_eq!(*id.id(), case.1);

			let parsed = case.0.parse::<PrefixU32>().unwrap();
			assert_eq!(parsed.0, case.1);
			assert_eq!(*parsed.id(), case.1);
		}
	}

	#[test]
	fn u32_prefix_invalid() {
		strong_id!(pub struct PrefixU32(u32 => "prefix"));

		struct Case(&'static str, Error);
		let cases = vec![
			Case("0000000", Error::MissingPrefix("prefix".into())),
			Case("000009d", Error::MissingPrefix("prefix".into())),
			Case("3zzzzzz", Error::MissingPrefix("prefix".into())),
			Case("prefix_0000000000", Error::InvalidLength(7, 10)),
			Case(
				"prefix_zzzzzzz",
				Error::Base32Error(Base32Error::InvalidFirstByte),
			),
			Case(
				"prefix_z000000",
				Error::Base32Error(Base32Error::InvalidFirstByte),
			),
			Case("prefix_09d", Error::InvalidLength(7, 3)),
			Case("zzzzzzz", Error::MissingPrefix("prefix".into())),
			Case("dyn_3000000", Error::InvalidPrefix("prefix".into(), "dyn".into())),
		];

		for case in cases {
			let error = case.0.parse::<PrefixU32>().unwrap_err();
			assert_eq!(error, case.1);
		}
	}

	#[test]
	fn u16_no_prefix_valid() {
		strong_id!(pub struct NoPrefixU16(u16));

		assert_eq!(NoPrefixU16::from(0).prefix(), None);

		struct Case(&'static str, u16);
		let cases = vec![
			Case("0000", u16::MIN),
			Case("1zzz", u16::MAX),
			Case("009d", 301),
		];

		for case in cases {
			let id = NoPrefixU16::from(case.1);
			assert_eq!(&format!("{id}"), case.0);
			assert_eq!(*id.id(), case.1);

			let parsed = case.0.parse::<NoPrefixU16>().unwrap();
			assert_eq!(parsed.0, case.1);
			assert_eq!(*parsed.id(), case.1);
		}
	}

	#[test]
	fn u16_no_prefix_invalid() {
		strong_id!(pub struct NoPrefixU16(u16));

		struct Case(&'static str, Error);
		let cases = vec![
			Case("00000", Error::InvalidLength(4, 5)),
			Case("prefix_00000", Error::NoPrefixExpected("prefix".into())),
			Case("zzzz", Error::Base32Error(Base32Error::InvalidFirstByte)),
			Case("z000", Error::Base32Error(Base32Error::InvalidFirstByte)),
			Case("09d", Error::InvalidLength(4, 3)),
		];

		for case in cases {
			let error = case.0.parse::<NoPrefixU16>().unwrap_err();
			assert_eq!(error, case.1);
		}
	}

	#[cfg(feature = "serde")]
	#[test]
	fn u32_prefix_serde() {
		strong_id!(pub struct PrefixU32(u32 => "prefix"));

		let value: PrefixU32 = serde_json::from_str("\"prefix_000009d\"").unwrap();
		assert_eq!(*value.id(), 301);

		let value = serde_json::to_string(&value).unwrap();
		assert_eq!("\"prefix_000009d\"", value);
	}
}