pub struct Id<D: IdDomain> { /* private fields */ }Expand description
Lightweight, type-safe numeric identifier
Id<D> wraps a NonZeroU64 with a phantom domain marker, providing
compile-time type safety for numeric identifiers. It is Copy, making it
ideal for use as database primary keys, entity IDs, and similar use cases.
The non-zero invariant means Option<Id<D>> is the same size as Id<D>
(niche optimization), and zero can never accidentally represent a valid ID.
§Domain Trait
Id<D> uses IdDomain — a lightweight marker trait with only a domain name.
No string validation or normalization needed, unlike KeyDomain.
§Memory Layout
Id<D> struct (8 bytes, niche-optimized):
┌──────────────────┬─────────────┐
│ NonZeroU64 (8B) │ marker (0B) │
└──────────────────┴─────────────┘
Option<Id<D>>: also 8 bytes (None = 0)§Type Safety
Different domains produce incompatible ID types at compile time:
use domain_key::{Id, Domain, IdDomain};
#[derive(Debug)]
struct UserDomain;
impl Domain for UserDomain { const DOMAIN_NAME: &'static str = "user"; }
impl IdDomain for UserDomain {}
#[derive(Debug)]
struct OrderDomain;
impl Domain for OrderDomain { const DOMAIN_NAME: &'static str = "order"; }
impl IdDomain for OrderDomain {}
type UserId = Id<UserDomain>;
type OrderId = Id<OrderDomain>;
let user_id = UserId::new(1).unwrap();
let order_id: OrderId = user_id; // Compile error!Implementations§
Source§impl<D: IdDomain> Id<D>
impl<D: IdDomain> Id<D>
Sourcepub const fn new(value: u64) -> Option<Self>
pub const fn new(value: u64) -> Option<Self>
Creates a new typed identifier from a u64 value.
Returns None if value is zero.
§Examples
use domain_key::{Id, Domain, IdDomain};
#[derive(Debug)]
struct UserDomain;
impl Domain for UserDomain { const DOMAIN_NAME: &'static str = "user"; }
impl IdDomain for UserDomain {}
type UserId = Id<UserDomain>;
assert!(UserId::new(1).is_some());
assert!(UserId::new(0).is_none());Sourcepub const fn from_non_zero(value: NonZeroU64) -> Self
pub const fn from_non_zero(value: NonZeroU64) -> Self
Creates a new typed identifier from a NonZeroU64 value.
Sourcepub const fn non_zero(&self) -> NonZeroU64
pub const fn non_zero(&self) -> NonZeroU64
Returns the underlying NonZeroU64 value.
Trait Implementations§
Source§impl<'de, D: IdDomain> Deserialize<'de> for Id<D>
Available on crate feature serde only.
impl<'de, D: IdDomain> Deserialize<'de> for Id<D>
serde only.