newtype_uuid/lib.rs
1//! A newtype wrapper around [`Uuid`].
2//!
3//! # Motivation
4//!
5//! Many large systems use UUIDs as unique identifiers for various entities. However, the [`Uuid`]
6//! type does not carry information about the kind of entity it identifies, which can lead to mixing
7//! up different types of UUIDs at runtime.
8//!
9//! This crate provides a wrapper type around [`Uuid`] that allows you to specify the kind of entity
10//! the UUID identifies.
11//!
12//! # Example
13//!
14//! ```
15//! use newtype_uuid::{GenericUuid, TypedUuid, TypedUuidKind, TypedUuidTag};
16//!
17//! // First, define a type that represents the kind of UUID this is.
18//! enum MyKind {}
19//!
20//! impl TypedUuidKind for MyKind {
21//! fn tag() -> TypedUuidTag {
22//! // Tags are required to be ASCII identifiers, with underscores
23//! // and dashes also supported. The validity of a tag can be checked
24//! // at compile time by assigning it to a const, like so:
25//! const TAG: TypedUuidTag = TypedUuidTag::new("my_kind");
26//! TAG
27//! }
28//! }
29//!
30//! // Now, a UUID can be created with this kind.
31//! let uuid: TypedUuid<MyKind> = "dffc3068-1cd6-47d5-b2f3-636b41b07084".parse().unwrap();
32//!
33//! // The Display (and therefore ToString) impls still show the same value.
34//! assert_eq!(uuid.to_string(), "dffc3068-1cd6-47d5-b2f3-636b41b07084");
35//!
36//! // The Debug impl will show the tag as well.
37//! assert_eq!(
38//! format!("{:?}", uuid),
39//! "dffc3068-1cd6-47d5-b2f3-636b41b07084 (my_kind)"
40//! );
41//! ```
42//!
43//! If you have a large number of UUID kinds, consider using
44//! [`newtype-uuid-macros`] which comes with several convenience features.
45//!
46//! ```
47//! use newtype_uuid_macros::impl_typed_uuid_kinds;
48//!
49//! // Invoke this macro with:
50//! impl_typed_uuid_kinds! {
51//! kinds = {
52//! User = {},
53//! Project = {},
54//! // ...
55//! },
56//! }
57//! ```
58//!
59//! See [`newtype-uuid-macros`] for more information.
60//!
61//! [`newtype-uuid-macros`]: https://docs.rs/newtype-uuid-macros
62//!
63//! For simpler cases, you can also write your own declarative macro. Use this
64//! template to get started:
65//!
66//! ```rust
67//! # use newtype_uuid::{TypedUuidKind, TypedUuidTag};
68//! macro_rules! impl_kinds {
69//! ($($kind:ident => $tag:literal),* $(,)?) => {
70//! $(
71//! pub enum $kind {}
72//!
73//! impl TypedUuidKind for $kind {
74//! #[inline]
75//! fn tag() -> TypedUuidTag {
76//! const TAG: TypedUuidTag = TypedUuidTag::new($tag);
77//! TAG
78//! }
79//! }
80//! )*
81//! };
82//! }
83//!
84//! // Invoke this macro with:
85//! impl_kinds! {
86//! UserKind => "user",
87//! ProjectKind => "project",
88//! }
89//! ```
90//!
91//! # Implementations
92//!
93//! In general, [`TypedUuid`] uses the same wire and serialization formats as [`Uuid`]. This means
94//! that persistent representations of [`TypedUuid`] are the same as [`Uuid`]; [`TypedUuid`] is
95//! intended to be helpful within Rust code, not across serialization boundaries.
96//!
97//! - The `Display` and `FromStr` impls are forwarded to the underlying [`Uuid`].
98//! - If the `serde` feature is enabled, `TypedUuid` will serialize and deserialize using the same
99//! format as [`Uuid`].
100//! - If the `schemars08` feature is enabled, [`TypedUuid`] will implement `JsonSchema` if the
101//! corresponding [`TypedUuidKind`] implements `JsonSchema`.
102//!
103//! To abstract over typed and untyped UUIDs, the [`GenericUuid`] trait is provided. This trait also
104//! permits conversions between typed and untyped UUIDs.
105//!
106//! # Dependencies
107//!
108//! - The only required dependency is the [`uuid`] crate. Optional features may add further
109//! dependencies.
110//!
111//! # Features
112//!
113//! - `default`: Enables default features in the newtype-uuid crate.
114//! - `std`: Enables the use of the standard library. *Enabled by default.*
115//! - `serde`: Enables serialization and deserialization support via Serde. *Not enabled by
116//! default.*
117//! - `v4`: Enables the `new_v4` method for generating UUIDs. *Not enabled by default.*
118//! - `schemars08`: Enables support for generating JSON schemas via schemars 0.8. *Not enabled by
119//! default.* Note that the format of the generated schema is **not currently part** of the stable
120//! API, though we hope to stabilize it in the future.
121//! - `proptest1`: Enables support for generating `proptest::Arbitrary` instances of UUIDs. *Not enabled by default.*
122//!
123//! # Minimum supported Rust version (MSRV)
124//!
125//! The MSRV of this crate is **Rust 1.88.** In general, this crate will follow the MSRV of the
126//! underlying `uuid` crate or of dependencies, with an aim to be conservative.
127//!
128//! Within the 1.x series, MSRV updates will be accompanied by a minor version bump. The MSRVs for
129//! each minor version are:
130//!
131//! * Version **1.0.x**: Rust 1.60.
132//! * Version **1.1.x**: Rust 1.61. This permits `TypedUuid<T>` to have `const fn` methods.
133//! * Version **1.2.x**: Rust 1.67, required by some dependency updates.
134//! * Version **1.3.x**: Rust 1.79, required by some dependency updates.
135//! * Version **1.4.x**: Rust 1.85, required by some dependency updates.
136//! * Version **1.5.x**: Rust 1.88, required by some dependency updates.
137//!
138//! # Alternatives
139//!
140//! - [`typed-uuid`](https://crates.io/crates/typed-uuid): generally similar, but with a few design
141//! decisions that are different.
142
143#![forbid(unsafe_code)]
144#![warn(missing_docs)]
145#![cfg_attr(not(feature = "std"), no_std)]
146#![cfg_attr(doc_cfg, feature(doc_cfg))]
147
148#[cfg(feature = "alloc")]
149extern crate alloc;
150
151/// Macro support for [`newtype-uuid-macros`].
152///
153/// This module re-exports types needed for [`newtype-uuid-macros`] to work.
154///
155/// [`newtype-uuid-macros`]: https://docs.rs/newtype-uuid-macros
156#[doc(hidden)]
157pub mod macro_support {
158 #[cfg(feature = "schemars08")]
159 pub use schemars as schemars08;
160 #[cfg(feature = "schemars08")]
161 pub use serde_json;
162}
163
164use core::{
165 cmp::Ordering,
166 fmt,
167 hash::{Hash, Hasher},
168 marker::PhantomData,
169 str::FromStr,
170};
171#[cfg(feature = "v7")]
172pub use uuid::Timestamp;
173use uuid::{Uuid, Version};
174
175/// A UUID with type-level information about what it's used for.
176///
177/// For more, see [the library documentation](crate).
178#[repr(transparent)]
179#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
180#[cfg_attr(feature = "serde", serde(transparent, bound = ""))]
181pub struct TypedUuid<T: TypedUuidKind> {
182 uuid: Uuid,
183 _phantom: PhantomData<T>,
184}
185
186impl<T: TypedUuidKind> TypedUuid<T> {
187 /// The 'nil UUID' (all zeros).
188 ///
189 /// The nil UUID is a special form of UUID that is specified to have all
190 /// 128 bits set to zero.
191 ///
192 /// # References
193 ///
194 /// * [Nil UUID in RFC4122](https://tools.ietf.org/html/rfc4122.html#section-4.1.7)
195 #[inline]
196 #[must_use]
197 pub const fn nil() -> Self {
198 Self {
199 uuid: Uuid::nil(),
200 _phantom: PhantomData,
201 }
202 }
203
204 /// The 'max UUID' (all ones).
205 ///
206 /// The max UUID is a special form of UUID that is specified to have all
207 /// 128 bits set to one.
208 ///
209 /// # References
210 ///
211 /// * [Max UUID in Draft RFC: New UUID Formats, Version 4](https://datatracker.ietf.org/doc/html/draft-peabody-dispatch-new-uuid-format-04#section-5.4)
212 #[inline]
213 #[must_use]
214 pub const fn max() -> Self {
215 Self {
216 uuid: Uuid::max(),
217 _phantom: PhantomData,
218 }
219 }
220
221 /// Creates a UUID from four field values.
222 #[inline]
223 #[must_use]
224 pub const fn from_fields(d1: u32, d2: u16, d3: u16, d4: [u8; 8]) -> Self {
225 Self {
226 uuid: Uuid::from_fields(d1, d2, d3, &d4),
227 _phantom: PhantomData,
228 }
229 }
230
231 /// Creates a UUID from four field values in little-endian order.
232 ///
233 /// The bytes in the `d1`, `d2` and `d3` fields will be flipped to convert into big-endian
234 /// order. This is based on the endianness of the UUID, rather than the target environment so
235 /// bytes will be flipped on both big and little endian machines.
236 #[inline]
237 #[must_use]
238 pub const fn from_fields_le(d1: u32, d2: u16, d3: u16, d4: [u8; 8]) -> Self {
239 Self {
240 uuid: Uuid::from_fields_le(d1, d2, d3, &d4),
241 _phantom: PhantomData,
242 }
243 }
244
245 /// Creates a UUID from a 128bit value.
246 #[inline]
247 #[must_use]
248 pub const fn from_u128(value: u128) -> Self {
249 Self {
250 uuid: Uuid::from_u128(value),
251 _phantom: PhantomData,
252 }
253 }
254
255 /// Creates a UUID from a 128bit value in little-endian order.
256 ///
257 /// The entire value will be flipped to convert into big-endian order. This is based on the
258 /// endianness of the UUID, rather than the target environment so bytes will be flipped on both
259 /// big and little endian machines.
260 #[inline]
261 #[must_use]
262 pub const fn from_u128_le(value: u128) -> Self {
263 Self {
264 uuid: Uuid::from_u128_le(value),
265 _phantom: PhantomData,
266 }
267 }
268
269 /// Creates a UUID from two 64bit values.
270 #[inline]
271 #[must_use]
272 pub const fn from_u64_pair(d1: u64, d2: u64) -> Self {
273 Self {
274 uuid: Uuid::from_u64_pair(d1, d2),
275 _phantom: PhantomData,
276 }
277 }
278
279 /// Creates a UUID using the supplied bytes.
280 #[inline]
281 #[must_use]
282 pub const fn from_bytes(bytes: uuid::Bytes) -> Self {
283 Self {
284 uuid: Uuid::from_bytes(bytes),
285 _phantom: PhantomData,
286 }
287 }
288
289 /// Creates a UUID using the supplied bytes in little-endian order.
290 ///
291 /// The individual fields encoded in the buffer will be flipped.
292 #[inline]
293 #[must_use]
294 pub const fn from_bytes_le(bytes: uuid::Bytes) -> Self {
295 Self {
296 uuid: Uuid::from_bytes_le(bytes),
297 _phantom: PhantomData,
298 }
299 }
300
301 /// Creates a new, random UUID v4 of this type.
302 #[inline]
303 #[cfg(feature = "v4")]
304 #[must_use]
305 pub fn new_v4() -> Self {
306 Self::from_untyped_uuid(Uuid::new_v4())
307 }
308
309 /// Creates a new, random UUID v7 of this type.
310 #[inline]
311 #[cfg(feature = "v7")]
312 #[must_use]
313 pub fn new_v7(ts: uuid::Timestamp) -> Self {
314 Self::from_untyped_uuid(Uuid::new_v7(ts))
315 }
316
317 /// Returns the version number of the UUID.
318 ///
319 /// This represents the algorithm used to generate the value.
320 /// This method is the future-proof alternative to [`Self::get_version`].
321 ///
322 /// # References
323 ///
324 /// * [Version Field in RFC 9562](https://www.ietf.org/rfc/rfc9562.html#section-4.2)
325 #[inline]
326 pub const fn get_version_num(&self) -> usize {
327 self.uuid.get_version_num()
328 }
329
330 /// Returns the version of the UUID.
331 ///
332 /// This represents the algorithm used to generate the value.
333 /// If the version field doesn't contain a recognized version then `None`
334 /// is returned. If you're trying to read the version for a future extension
335 /// you can also use [`Uuid::get_version_num`] to unconditionally return a
336 /// number. Future extensions may start to return `Some` once they're
337 /// standardized and supported.
338 ///
339 /// # References
340 ///
341 /// * [Version Field in RFC 9562](https://www.ietf.org/rfc/rfc9562.html#section-4.2)
342 #[inline]
343 pub fn get_version(&self) -> Option<Version> {
344 self.uuid.get_version()
345 }
346
347 /// Returns true if the UUID is nil (all zeros).
348 #[inline]
349 pub const fn is_nil(&self) -> bool {
350 self.uuid.is_nil()
351 }
352
353 /// Returns true if the UUID is the max value (all ones).
354 #[inline]
355 pub const fn is_max(&self) -> bool {
356 self.uuid.is_max()
357 }
358
359 /// Returns the four field values of the UUID.
360 ///
361 /// These values can be passed to [`Self::from_fields`] to reconstruct the
362 /// original UUID. The first field represents the initial eight hex digits
363 /// as a big-endian `u32`. The second and third fields represent subsequent
364 /// hex digit groups as `u16` values. The final field contains the last two
365 /// groups of hex digits as an 8-byte array.
366 ///
367 /// # Examples
368 ///
369 /// ```
370 /// # use newtype_uuid::TypedUuid;
371 /// # enum ExampleKind {}
372 /// # impl newtype_uuid::TypedUuidKind for ExampleKind {
373 /// # fn tag() -> newtype_uuid::TypedUuidTag {
374 /// # const TAG: newtype_uuid::TypedUuidTag = newtype_uuid::TypedUuidTag::new("example");
375 /// # TAG
376 /// # }
377 /// # }
378 /// let uuid: TypedUuid<ExampleKind> =
379 /// "a1a2a3a4-b1b2-c1c2-d1d2-d3d4d5d6d7d8".parse().unwrap();
380 ///
381 /// assert_eq!(
382 /// uuid.as_fields(),
383 /// (
384 /// 0xa1a2a3a4,
385 /// 0xb1b2,
386 /// 0xc1c2,
387 /// &[0xd1, 0xd2, 0xd3, 0xd4, 0xd5, 0xd6, 0xd7, 0xd8],
388 /// )
389 /// );
390 /// ```
391 #[inline]
392 pub fn as_fields(&self) -> (u32, u16, u16, &[u8; 8]) {
393 self.uuid.as_fields()
394 }
395
396 /// Returns the four field values in little-endian order.
397 ///
398 /// The bytes within integer fields are converted from big-endian order.
399 /// This is based on the endianness of the UUID rather than the target
400 /// environment, so bytes will be flipped on both big and little endian
401 /// machines.
402 ///
403 /// # Examples
404 ///
405 /// ```
406 /// # use newtype_uuid::TypedUuid;
407 /// # enum ExampleKind {}
408 /// # impl newtype_uuid::TypedUuidKind for ExampleKind {
409 /// # fn tag() -> newtype_uuid::TypedUuidTag {
410 /// # const TAG: newtype_uuid::TypedUuidTag = newtype_uuid::TypedUuidTag::new("example");
411 /// # TAG
412 /// # }
413 /// # }
414 /// let uuid: TypedUuid<ExampleKind> =
415 /// "a1a2a3a4-b1b2-c1c2-d1d2-d3d4d5d6d7d8".parse().unwrap();
416 ///
417 /// assert_eq!(
418 /// uuid.to_fields_le(),
419 /// (
420 /// 0xa4a3a2a1,
421 /// 0xb2b1,
422 /// 0xc2c1,
423 /// &[0xd1, 0xd2, 0xd3, 0xd4, 0xd5, 0xd6, 0xd7, 0xd8],
424 /// )
425 /// );
426 /// ```
427 #[inline]
428 pub fn to_fields_le(&self) -> (u32, u16, u16, &[u8; 8]) {
429 self.uuid.to_fields_le()
430 }
431
432 /// Returns a 128-bit value containing the UUID bytes.
433 ///
434 /// # Examples
435 ///
436 /// ```
437 /// # use newtype_uuid::TypedUuid;
438 /// # enum ExampleKind {}
439 /// # impl newtype_uuid::TypedUuidKind for ExampleKind {
440 /// # fn tag() -> newtype_uuid::TypedUuidTag {
441 /// # const TAG: newtype_uuid::TypedUuidTag = newtype_uuid::TypedUuidTag::new("example");
442 /// # TAG
443 /// # }
444 /// # }
445 /// let uuid: TypedUuid<ExampleKind> =
446 /// "a1a2a3a4-b1b2-c1c2-d1d2-d3d4d5d6d7d8".parse().unwrap();
447 ///
448 /// assert_eq!(
449 /// uuid.as_u128(),
450 /// 0xa1a2a3a4b1b2c1c2d1d2d3d4d5d6d7d8u128,
451 /// );
452 /// ```
453 #[inline]
454 pub const fn as_u128(&self) -> u128 {
455 self.uuid.as_u128()
456 }
457
458 /// Returns a 128-bit little-endian value.
459 ///
460 /// The bytes in the `u128` will be flipped to convert into big-endian order.
461 /// This is based on the endianness of the UUID, rather than the target
462 /// environment so bytes will be flipped on both big and little endian
463 /// machines.
464 ///
465 /// Note that this will produce a different result than
466 /// [`Self::to_fields_le`], because the entire UUID is reversed, rather than
467 /// reversing the individual fields in-place.
468 ///
469 /// # Examples
470 ///
471 /// ```
472 /// # use newtype_uuid::TypedUuid;
473 /// # enum ExampleKind {}
474 /// # impl newtype_uuid::TypedUuidKind for ExampleKind {
475 /// # fn tag() -> newtype_uuid::TypedUuidTag {
476 /// # const TAG: newtype_uuid::TypedUuidTag = newtype_uuid::TypedUuidTag::new("example");
477 /// # TAG
478 /// # }
479 /// # }
480 /// let uuid: TypedUuid<ExampleKind> =
481 /// "a1a2a3a4-b1b2-c1c2-d1d2-d3d4d5d6d7d8".parse().unwrap();
482 ///
483 /// assert_eq!(
484 /// uuid.to_u128_le(),
485 /// 0xd8d7d6d5d4d3d2d1c2c1b2b1a4a3a2a1u128,
486 /// );
487 /// ```
488 #[inline]
489 pub fn to_u128_le(&self) -> u128 {
490 self.uuid.to_u128_le()
491 }
492
493 /// Returns two 64-bit values representing the UUID.
494 ///
495 /// The first `u64` contains the most significant 64 bits; the second
496 /// contains the least significant bits.
497 ///
498 /// # Examples
499 ///
500 /// ```
501 /// # use newtype_uuid::TypedUuid;
502 /// # enum ExampleKind {}
503 /// # impl newtype_uuid::TypedUuidKind for ExampleKind {
504 /// # fn tag() -> newtype_uuid::TypedUuidTag {
505 /// # const TAG: newtype_uuid::TypedUuidTag = newtype_uuid::TypedUuidTag::new("example");
506 /// # TAG
507 /// # }
508 /// # }
509 /// let uuid: TypedUuid<ExampleKind> =
510 /// "a1a2a3a4-b1b2-c1c2-d1d2-d3d4d5d6d7d8".parse().unwrap();
511 ///
512 /// assert_eq!(
513 /// uuid.as_u64_pair(),
514 /// (0xa1a2a3a4b1b2c1c2, 0xd1d2d3d4d5d6d7d8),
515 /// );
516 /// ```
517 #[inline]
518 pub const fn as_u64_pair(&self) -> (u64, u64) {
519 self.uuid.as_u64_pair()
520 }
521
522 /// Returns a slice of 16 octets containing the value.
523 ///
524 /// This method borrows the underlying byte value of the UUID.
525 ///
526 /// # Examples
527 ///
528 /// ```
529 /// # use newtype_uuid::TypedUuid;
530 /// # enum ExampleKind {}
531 /// # impl newtype_uuid::TypedUuidKind for ExampleKind {
532 /// # fn tag() -> newtype_uuid::TypedUuidTag {
533 /// # const TAG: newtype_uuid::TypedUuidTag = newtype_uuid::TypedUuidTag::new("example");
534 /// # TAG
535 /// # }
536 /// # }
537 /// let bytes = [
538 /// 0xa1, 0xa2, 0xa3, 0xa4,
539 /// 0xb1, 0xb2,
540 /// 0xc1, 0xc2,
541 /// 0xd1, 0xd2, 0xd3, 0xd4, 0xd5, 0xd6, 0xd7, 0xd8,
542 /// ];
543 ///
544 /// let uuid = TypedUuid::<ExampleKind>::from_bytes(bytes);
545 /// let bytes2 = uuid.as_bytes();
546 ///
547 /// assert_eq!(&bytes, bytes2);
548 /// ```
549 #[inline]
550 pub const fn as_bytes(&self) -> &uuid::Bytes {
551 self.uuid.as_bytes()
552 }
553
554 /// Consumes self and returns the underlying byte value of the UUID.
555 ///
556 /// # Examples
557 ///
558 /// ```
559 /// # use newtype_uuid::TypedUuid;
560 /// # enum ExampleKind {}
561 /// # impl newtype_uuid::TypedUuidKind for ExampleKind {
562 /// # fn tag() -> newtype_uuid::TypedUuidTag {
563 /// # const TAG: newtype_uuid::TypedUuidTag = newtype_uuid::TypedUuidTag::new("example");
564 /// # TAG
565 /// # }
566 /// # }
567 /// let bytes = [
568 /// 0xa1, 0xa2, 0xa3, 0xa4,
569 /// 0xb1, 0xb2,
570 /// 0xc1, 0xc2,
571 /// 0xd1, 0xd2, 0xd3, 0xd4, 0xd5, 0xd6, 0xd7, 0xd8,
572 /// ];
573 ///
574 /// let uuid = TypedUuid::<ExampleKind>::from_bytes(bytes);
575 ///
576 /// assert_eq!(bytes, uuid.into_bytes());
577 /// ```
578 #[inline]
579 #[must_use]
580 pub const fn into_bytes(self) -> uuid::Bytes {
581 self.uuid.into_bytes()
582 }
583
584 /// Returns the bytes of the UUID in little-endian order.
585 ///
586 /// The bytes will be flipped to convert into little-endian order. This is
587 /// based on the endianness of the UUID, rather than the target environment
588 /// so bytes will be flipped on both big and little endian machines.
589 ///
590 /// # Examples
591 ///
592 /// ```
593 /// # use newtype_uuid::TypedUuid;
594 /// # enum ExampleKind {}
595 /// # impl newtype_uuid::TypedUuidKind for ExampleKind {
596 /// # fn tag() -> newtype_uuid::TypedUuidTag {
597 /// # const TAG: newtype_uuid::TypedUuidTag = newtype_uuid::TypedUuidTag::new("example");
598 /// # TAG
599 /// # }
600 /// # }
601 /// let uuid: TypedUuid<ExampleKind> =
602 /// "a1a2a3a4-b1b2-c1c2-d1d2-d3d4d5d6d7d8".parse().unwrap();
603 ///
604 /// assert_eq!(
605 /// uuid.to_bytes_le(),
606 /// [
607 /// 0xa4, 0xa3, 0xa2, 0xa1,
608 /// 0xb2, 0xb1,
609 /// 0xc2, 0xc1,
610 /// 0xd1, 0xd2, 0xd3, 0xd4, 0xd5, 0xd6, 0xd7, 0xd8,
611 /// ]
612 /// );
613 /// ```
614 #[inline]
615 pub fn to_bytes_le(&self) -> uuid::Bytes {
616 self.uuid.to_bytes_le()
617 }
618
619 /// Converts the UUID to one with looser semantics.
620 ///
621 /// By default, UUID kinds are considered independent, and conversions
622 /// between them must happen via the [`GenericUuid`] interface. But in some
623 /// cases, there may be a relationship between two different UUID kinds, and
624 /// you may wish to easily convert UUIDs from one kind to another.
625 ///
626 /// Typically, a conversion from `TypedUuid<T>` to `TypedUuid<U>` is most
627 /// useful when `T`'s semantics are a superset of `U`'s, or in other words,
628 /// when every `TypedUuid<T>` is logically also a `TypedUuid<U>`.
629 ///
630 /// For instance:
631 ///
632 /// * Imagine you have [`TypedUuidKind`]s for different types of
633 /// database connections, where `DbConnKind` is the general type
634 /// and `PgConnKind` is a specific kind for Postgres.
635 /// * Since every Postgres connection is also a database connection,
636 /// a cast from `TypedUuid<PgConnKind>` to `TypedUuid<DbConnKind>`
637 /// makes sense.
638 /// * The inverse cast would not make sense, as a database connection may not
639 /// necessarily be a Postgres connection.
640 ///
641 /// This interface provides an alternative, safer way to perform this
642 /// conversion. Indicate your intention to allow a conversion between kinds
643 /// by implementing `From<T> for U`, as shown in the example below.
644 ///
645 /// # Examples
646 ///
647 /// ```
648 /// use newtype_uuid::{TypedUuid, TypedUuidKind, TypedUuidTag};
649 ///
650 /// // Let's say that these UUIDs represent repositories for different
651 /// // version control systems, such that you have a generic RepoKind:
652 /// pub enum RepoKind {}
653 /// impl TypedUuidKind for RepoKind {
654 /// fn tag() -> TypedUuidTag {
655 /// const TAG: TypedUuidTag = TypedUuidTag::new("repo");
656 /// TAG
657 /// }
658 /// }
659 ///
660 /// // You also have more specific kinds:
661 /// pub enum GitRepoKind {}
662 /// impl TypedUuidKind for GitRepoKind {
663 /// fn tag() -> TypedUuidTag {
664 /// const TAG: TypedUuidTag = TypedUuidTag::new("git_repo");
665 /// TAG
666 /// }
667 /// }
668 /// // (and HgRepoKind, JujutsuRepoKind, etc...)
669 ///
670 /// // First, define a `From` impl. This impl indicates your desire
671 /// // to convert from one kind to another.
672 /// impl From<GitRepoKind> for RepoKind {
673 /// fn from(value: GitRepoKind) -> Self {
674 /// match value {}
675 /// }
676 /// }
677 ///
678 /// // Now you can convert between them:
679 /// let git_uuid: TypedUuid<GitRepoKind> =
680 /// TypedUuid::from_u128(0xe9245204_34ea_4ca7_a1c6_2e94fa49df61);
681 /// let repo_uuid: TypedUuid<RepoKind> = git_uuid.upcast();
682 /// ```
683 #[inline]
684 #[must_use]
685 pub const fn upcast<U: TypedUuidKind>(self) -> TypedUuid<U>
686 where
687 T: Into<U>,
688 {
689 TypedUuid {
690 uuid: self.uuid,
691 _phantom: PhantomData,
692 }
693 }
694}
695
696// ---
697// Trait impls
698// ---
699
700impl<T: TypedUuidKind> PartialEq for TypedUuid<T> {
701 #[inline]
702 fn eq(&self, other: &Self) -> bool {
703 self.uuid.eq(&other.uuid)
704 }
705}
706
707impl<T: TypedUuidKind> Eq for TypedUuid<T> {}
708
709impl<T: TypedUuidKind> PartialOrd for TypedUuid<T> {
710 #[inline]
711 fn partial_cmp(&self, other: &Self) -> Option<Ordering> {
712 Some(self.cmp(other))
713 }
714}
715
716impl<T: TypedUuidKind> Ord for TypedUuid<T> {
717 #[inline]
718 fn cmp(&self, other: &Self) -> core::cmp::Ordering {
719 self.uuid.cmp(&other.uuid)
720 }
721}
722
723impl<T: TypedUuidKind> Hash for TypedUuid<T> {
724 #[inline]
725 fn hash<H: Hasher>(&self, state: &mut H) {
726 self.uuid.hash(state);
727 }
728}
729
730impl<T: TypedUuidKind> fmt::Debug for TypedUuid<T> {
731 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
732 self.uuid.fmt(f)?;
733 write!(f, " ({})", T::tag())
734 }
735}
736
737impl<T: TypedUuidKind> fmt::Display for TypedUuid<T> {
738 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
739 self.uuid.fmt(f)
740 }
741}
742
743impl<T: TypedUuidKind> Clone for TypedUuid<T> {
744 #[inline]
745 fn clone(&self) -> Self {
746 *self
747 }
748}
749
750impl<T: TypedUuidKind> Copy for TypedUuid<T> {}
751
752impl<T: TypedUuidKind> FromStr for TypedUuid<T> {
753 type Err = ParseError;
754
755 fn from_str(s: &str) -> Result<Self, Self::Err> {
756 let uuid = Uuid::from_str(s).map_err(|error| ParseError {
757 error,
758 tag: T::tag(),
759 })?;
760 Ok(Self::from_untyped_uuid(uuid))
761 }
762}
763
764impl<T: TypedUuidKind> Default for TypedUuid<T> {
765 #[inline]
766 fn default() -> Self {
767 Self::from_untyped_uuid(Uuid::default())
768 }
769}
770
771impl<T: TypedUuidKind> AsRef<[u8]> for TypedUuid<T> {
772 #[inline]
773 fn as_ref(&self) -> &[u8] {
774 self.uuid.as_ref()
775 }
776}
777
778#[cfg(feature = "alloc")]
779impl<T: TypedUuidKind> From<TypedUuid<T>> for alloc::vec::Vec<u8> {
780 #[inline]
781 fn from(typed_uuid: TypedUuid<T>) -> Self {
782 typed_uuid.into_untyped_uuid().into_bytes().to_vec()
783 }
784}
785
786#[cfg(feature = "schemars08")]
787mod schemars08_imp {
788 use super::*;
789 use schemars::{
790 JsonSchema, SchemaGenerator,
791 schema::{InstanceType, Schema, SchemaObject},
792 schema_for,
793 };
794
795 const CRATE_NAME: &str = "newtype-uuid";
796 const CRATE_VERSION: &str = "1";
797 const CRATE_PATH: &str = "newtype_uuid::TypedUuid";
798
799 /// Implements `JsonSchema` for `TypedUuid<T>`, if `T` implements `JsonSchema`.
800 ///
801 /// * `schema_name` is set to `"TypedUuidFor"`, concatenated by the schema name of `T`.
802 /// * `schema_id` is set to `format!("newtype_uuid::TypedUuid<{}>", T::schema_id())`.
803 /// * `json_schema` is the same as the one for `Uuid`, with the `x-rust-type` extension
804 /// to allow automatic replacement in typify and progenitor.
805 impl<T> JsonSchema for TypedUuid<T>
806 where
807 T: TypedUuidKind + JsonSchema,
808 {
809 #[inline]
810 fn schema_name() -> String {
811 // Use the alias if available, otherwise generate our own schema name.
812 if let Some(alias) = T::alias() {
813 alias.to_owned()
814 } else {
815 format!("TypedUuidFor{}", T::schema_name())
816 }
817 }
818
819 #[inline]
820 fn schema_id() -> std::borrow::Cow<'static, str> {
821 std::borrow::Cow::Owned(format!("newtype_uuid::TypedUuid<{}>", T::schema_id()))
822 }
823
824 #[inline]
825 fn json_schema(generator: &mut SchemaGenerator) -> Schema {
826 // Look at the schema for `T`. If it has `x-rust-type`, *and* if an
827 // alias is available, we can lift up the `x-rust-type` into our own schema.
828 //
829 // We use a new schema generator for `T` to avoid T's schema being
830 // added to the list of schemas in `generator` in case the lifting
831 // is successful.
832 let t_schema = schema_for!(T);
833 if let Some(schema) = lift_json_schema(&t_schema.schema, T::alias()) {
834 return schema.into();
835 }
836
837 SchemaObject {
838 instance_type: Some(InstanceType::String.into()),
839 format: Some("uuid".to_string()),
840 extensions: [(
841 "x-rust-type".to_string(),
842 serde_json::json!({
843 "crate": CRATE_NAME,
844 "version": CRATE_VERSION,
845 "path": CRATE_PATH,
846 "parameters": [generator.subschema_for::<T>()]
847 }),
848 )]
849 .into_iter()
850 .collect(),
851 ..Default::default()
852 }
853 .into()
854 }
855 }
856
857 // ? on Option is too easy to make mistakes with, so we use `let Some(..) =
858 // .. else` instead.
859 #[allow(clippy::question_mark)]
860 fn lift_json_schema(schema: &SchemaObject, alias: Option<&str>) -> Option<SchemaObject> {
861 let Some(alias) = alias else {
862 return None;
863 };
864
865 let Some(v) = schema.extensions.get("x-rust-type") else {
866 return None;
867 };
868
869 // The crate, version and path must all be present.
870 let Some(crate_) = v.get("crate") else {
871 return None;
872 };
873 let Some(version) = v.get("version") else {
874 return None;
875 };
876 let Some(path) = v.get("path").and_then(|p| p.as_str()) else {
877 return None;
878 };
879 let Some((module_path, _)) = path.rsplit_once("::") else {
880 return None;
881 };
882
883 // The preconditions are all met. We can lift the schema by appending
884 // the alias to the module path.
885 let alias_path = format!("{module_path}::{alias}");
886
887 Some(SchemaObject {
888 instance_type: Some(InstanceType::String.into()),
889 format: Some("uuid".to_string()),
890 extensions: [(
891 "x-rust-type".to_string(),
892 serde_json::json!({
893 "crate": crate_,
894 "version": version,
895 "path": alias_path,
896 }),
897 )]
898 .into_iter()
899 .collect(),
900 ..Default::default()
901 })
902 }
903}
904
905#[cfg(feature = "proptest1")]
906mod proptest1_imp {
907 use super::*;
908 use proptest::{
909 arbitrary::{Arbitrary, any},
910 strategy::{BoxedStrategy, Strategy},
911 };
912
913 /// Parameters for use with `proptest` instances.
914 ///
915 /// This is currently not exported as a type because it has no options. But
916 /// it's left in as an extension point for the future.
917 #[derive(Clone, Debug, Default)]
918 pub struct TypedUuidParams(());
919
920 /// Generates random `TypedUuid<T>` instances.
921 ///
922 /// Currently, this always returns a version 4 UUID. Support for other kinds
923 /// of UUIDs might be added via [`Self::Parameters`] in the future.
924 impl<T> Arbitrary for TypedUuid<T>
925 where
926 T: TypedUuidKind,
927 {
928 type Parameters = TypedUuidParams;
929 type Strategy = BoxedStrategy<Self>;
930
931 fn arbitrary_with(_args: Self::Parameters) -> Self::Strategy {
932 let bytes = any::<[u8; 16]>();
933 bytes
934 .prop_map(|b| {
935 let uuid = uuid::Builder::from_random_bytes(b).into_uuid();
936 TypedUuid::<T>::from_untyped_uuid(uuid)
937 })
938 .boxed()
939 }
940 }
941}
942
943/// Represents marker types that can be used as a type parameter for [`TypedUuid`].
944///
945/// Generally, an implementation of this will be a zero-sized type that can never be constructed. An
946/// empty struct or enum works well for this.
947///
948/// # Implementations
949///
950/// If the `schemars08` feature is enabled, and [`JsonSchema`] is implemented for a kind `T`, then
951/// [`TypedUuid`]`<T>` will also implement [`JsonSchema`].
952///
953/// If you have a large number of UUID kinds, consider using
954/// [`newtype-uuid-macros`] which comes with several convenience features.
955///
956/// ```
957/// use newtype_uuid_macros::impl_typed_uuid_kinds;
958///
959/// // Invoke this macro with:
960/// impl_typed_uuid_kinds! {
961/// kinds = {
962/// User = {},
963/// Project = {},
964/// // ...
965/// },
966/// }
967/// ```
968///
969/// See [`newtype-uuid-macros`] for more information.
970///
971/// [`newtype-uuid-macros`]: https://docs.rs/newtype-uuid-macros
972/// [`JsonSchema`]: schemars::JsonSchema
973pub trait TypedUuidKind: Send + Sync + 'static {
974 /// Returns the corresponding tag for this kind.
975 ///
976 /// The tag forms a runtime representation of this type.
977 ///
978 /// The tag is required to be a static string.
979 fn tag() -> TypedUuidTag;
980
981 /// Returns a string that corresponds to a type alias for `TypedUuid<Self>`,
982 /// if one is defined.
983 ///
984 /// The type alias must be defined in the same module as `Self`. This
985 /// function is used by the schemars integration to refer to embed a
986 /// reference to that alias in the schema, if available.
987 ///
988 /// This is usually defined by the [`newtype-uuid-macros`] crate.
989 ///
990 /// [`newtype-uuid-macros`]: https://docs.rs/newtype-uuid-macros
991 #[inline]
992 fn alias() -> Option<&'static str> {
993 None
994 }
995}
996
997/// Describes what kind of [`TypedUuid`] something is.
998///
999/// This is the runtime equivalent of [`TypedUuidKind`].
1000#[derive(Clone, Debug, PartialEq, Eq, PartialOrd, Ord, Hash)]
1001pub struct TypedUuidTag(&'static str);
1002
1003impl TypedUuidTag {
1004 /// Creates a new `TypedUuidTag` from a static string.
1005 ///
1006 /// The string must be non-empty, and consist of:
1007 /// - ASCII letters
1008 /// - digits (only after the first character)
1009 /// - underscores
1010 /// - hyphens (only after the first character)
1011 ///
1012 /// # Panics
1013 ///
1014 /// Panics if the above conditions aren't met. Use [`Self::try_new`] to handle errors instead.
1015 #[must_use]
1016 pub const fn new(tag: &'static str) -> Self {
1017 match Self::try_new_impl(tag) {
1018 Ok(tag) => tag,
1019 Err(message) => panic!("{}", message),
1020 }
1021 }
1022
1023 /// Attempts to create a new `TypedUuidTag` from a static string.
1024 ///
1025 /// The string must be non-empty, and consist of:
1026 /// - ASCII letters
1027 /// - digits (only after the first character)
1028 /// - underscores
1029 /// - hyphens (only after the first character)
1030 ///
1031 /// # Errors
1032 ///
1033 /// Returns a [`TagError`] if the above conditions aren't met.
1034 pub const fn try_new(tag: &'static str) -> Result<Self, TagError> {
1035 match Self::try_new_impl(tag) {
1036 Ok(tag) => Ok(tag),
1037 Err(message) => Err(TagError {
1038 input: tag,
1039 message,
1040 }),
1041 }
1042 }
1043
1044 const fn try_new_impl(tag: &'static str) -> Result<Self, &'static str> {
1045 if tag.is_empty() {
1046 return Err("tag must not be empty");
1047 }
1048
1049 let bytes = tag.as_bytes();
1050 if !(bytes[0].is_ascii_alphabetic() || bytes[0] == b'_') {
1051 return Err("first character of tag must be an ASCII letter or underscore");
1052 }
1053
1054 let mut bytes = match bytes {
1055 [_, rest @ ..] => rest,
1056 [] => panic!("already checked that it's non-empty"),
1057 };
1058 while let [rest @ .., last] = &bytes {
1059 if !(last.is_ascii_alphanumeric() || *last == b'_' || *last == b'-') {
1060 break;
1061 }
1062 bytes = rest;
1063 }
1064
1065 if !bytes.is_empty() {
1066 return Err("tag must only contain ASCII letters, digits, underscores, or hyphens");
1067 }
1068
1069 Ok(Self(tag))
1070 }
1071
1072 /// Returns the tag as a string.
1073 pub const fn as_str(&self) -> &'static str {
1074 self.0
1075 }
1076}
1077
1078impl fmt::Display for TypedUuidTag {
1079 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
1080 f.write_str(self.0)
1081 }
1082}
1083
1084impl AsRef<str> for TypedUuidTag {
1085 fn as_ref(&self) -> &str {
1086 self.0
1087 }
1088}
1089
1090/// An error that occurred while creating a [`TypedUuidTag`].
1091#[derive(Clone, Debug)]
1092#[non_exhaustive]
1093pub struct TagError {
1094 /// The input string.
1095 pub input: &'static str,
1096
1097 /// The error message.
1098 pub message: &'static str,
1099}
1100
1101impl fmt::Display for TagError {
1102 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
1103 write!(
1104 f,
1105 "error creating tag from '{}': {}",
1106 self.input, self.message
1107 )
1108 }
1109}
1110
1111impl core::error::Error for TagError {}
1112
1113/// An error that occurred while parsing a [`TypedUuid`].
1114#[derive(Clone, Debug)]
1115#[non_exhaustive]
1116pub struct ParseError {
1117 /// The underlying error.
1118 pub error: uuid::Error,
1119
1120 /// The tag of the UUID that failed to parse.
1121 pub tag: TypedUuidTag,
1122}
1123
1124impl fmt::Display for ParseError {
1125 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
1126 write!(f, "error parsing UUID ({})", self.tag)
1127 }
1128}
1129
1130impl core::error::Error for ParseError {
1131 fn source(&self) -> Option<&(dyn core::error::Error + 'static)> {
1132 Some(&self.error)
1133 }
1134}
1135
1136/// A trait abstracting over typed and untyped UUIDs.
1137///
1138/// This can be used to write code that's generic over [`TypedUuid`], [`Uuid`], and other types that
1139/// may wrap [`TypedUuid`] (due to e.g. orphan rules).
1140///
1141/// This trait is similar to `From`, but a bit harder to get wrong -- in general, the conversion
1142/// from and to untyped UUIDs should be careful and explicit.
1143pub trait GenericUuid {
1144 /// Creates a new instance of `Self` from an untyped [`Uuid`].
1145 #[must_use]
1146 fn from_untyped_uuid(uuid: Uuid) -> Self
1147 where
1148 Self: Sized;
1149
1150 /// Converts `self` into an untyped [`Uuid`].
1151 #[must_use]
1152 fn into_untyped_uuid(self) -> Uuid
1153 where
1154 Self: Sized;
1155
1156 /// Returns the inner [`Uuid`].
1157 ///
1158 /// Generally, [`into_untyped_uuid`](Self::into_untyped_uuid) should be preferred. However,
1159 /// in some cases it may be necessary to use this method to satisfy lifetime constraints.
1160 fn as_untyped_uuid(&self) -> &Uuid;
1161}
1162
1163impl GenericUuid for Uuid {
1164 #[inline]
1165 fn from_untyped_uuid(uuid: Uuid) -> Self {
1166 uuid
1167 }
1168
1169 #[inline]
1170 fn into_untyped_uuid(self) -> Uuid {
1171 self
1172 }
1173
1174 #[inline]
1175 fn as_untyped_uuid(&self) -> &Uuid {
1176 self
1177 }
1178}
1179
1180impl<T: TypedUuidKind> GenericUuid for TypedUuid<T> {
1181 #[inline]
1182 fn from_untyped_uuid(uuid: Uuid) -> Self {
1183 Self {
1184 uuid,
1185 _phantom: PhantomData,
1186 }
1187 }
1188
1189 #[inline]
1190 fn into_untyped_uuid(self) -> Uuid {
1191 self.uuid
1192 }
1193
1194 #[inline]
1195 fn as_untyped_uuid(&self) -> &Uuid {
1196 &self.uuid
1197 }
1198}
1199
1200#[cfg(test)]
1201mod tests {
1202 use super::*;
1203
1204 #[test]
1205 fn test_validate_tags() {
1206 for &valid_tag in &[
1207 "a", "a-", "a_", "a-b", "a_b", "a1", "a1-", "a1_", "a1-b", "a1_b", "_a",
1208 ] {
1209 TypedUuidTag::try_new(valid_tag).expect("tag is valid");
1210 // Should not panic
1211 _ = TypedUuidTag::new(valid_tag);
1212 }
1213
1214 for invalid_tag in &["", "1", "-", "a1b!", "a1-b!", "a1_b:", "\u{1f4a9}"] {
1215 TypedUuidTag::try_new(invalid_tag).unwrap_err();
1216 }
1217 }
1218
1219 // This test just ensures that `GenericUuid` is object-safe.
1220 #[test]
1221 #[cfg(all(feature = "v4", feature = "std"))]
1222 fn test_generic_uuid_object_safe() {
1223 let uuid = Uuid::new_v4();
1224 let box_uuid = Box::new(uuid) as Box<dyn GenericUuid>;
1225 assert_eq!(box_uuid.as_untyped_uuid(), &uuid);
1226 }
1227}