Skip to main content

Id

Struct Id 

Source
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>

Source

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());
Source

pub const fn from_non_zero(value: NonZeroU64) -> Self

Creates a new typed identifier from a NonZeroU64 value.

Source

pub const fn get(&self) -> u64

Returns the underlying value as u64.

Source

pub const fn non_zero(&self) -> NonZeroU64

Returns the underlying NonZeroU64 value.

Source

pub fn domain(&self) -> &'static str

Returns the domain name for this identifier type.

Trait Implementations§

Source§

impl<D: IdDomain> Clone for Id<D>

Source§

fn clone(&self) -> Self

Returns a duplicate of the value. Read more
1.0.0 · Source§

fn clone_from(&mut self, source: &Self)

Performs copy-assignment from source. Read more
Source§

impl<D: IdDomain> Debug for Id<D>

Source§

fn fmt(&self, f: &mut Formatter<'_>) -> Result

Formats the value using the given formatter. Read more
Source§

impl<'de, D: IdDomain> Deserialize<'de> for Id<D>

Available on crate feature serde only.
Source§

fn deserialize<De: Deserializer<'de>>( deserializer: De, ) -> Result<Self, De::Error>

Deserialize this value from the given Serde deserializer. Read more
Source§

impl<D: IdDomain> Display for Id<D>

Source§

fn fmt(&self, f: &mut Formatter<'_>) -> Result

Formats the value using the given formatter. Read more
Source§

impl<D: IdDomain> From<Id<D>> for NonZeroU64

Source§

fn from(id: Id<D>) -> Self

Converts to this type from the input type.
Source§

impl<D: IdDomain> From<Id<D>> for u64

Source§

fn from(id: Id<D>) -> Self

Converts to this type from the input type.
Source§

impl<D: IdDomain> From<NonZero<u64>> for Id<D>

Source§

fn from(value: NonZeroU64) -> Self

Converts to this type from the input type.
Source§

impl<D: IdDomain> FromStr for Id<D>

Source§

type Err = IdParseError

The associated error which can be returned from parsing.
Source§

fn from_str(s: &str) -> Result<Self, Self::Err>

Parses a string s to return a value of this type. Read more
Source§

impl<D: IdDomain> Hash for Id<D>

Source§

fn hash<H: Hasher>(&self, state: &mut H)

Feeds this value into the given Hasher. Read more
1.3.0 · Source§

fn hash_slice<H>(data: &[Self], state: &mut H)
where H: Hasher, Self: Sized,

Feeds a slice of this type into the given Hasher. Read more
Source§

impl<D: IdDomain> Ord for Id<D>

Source§

fn cmp(&self, other: &Self) -> Ordering

This method returns an Ordering between self and other. Read more
1.21.0 · Source§

fn max(self, other: Self) -> Self
where Self: Sized,

Compares and returns the maximum of two values. Read more
1.21.0 · Source§

fn min(self, other: Self) -> Self
where Self: Sized,

Compares and returns the minimum of two values. Read more
1.50.0 · Source§

fn clamp(self, min: Self, max: Self) -> Self
where Self: Sized,

Restrict a value to a certain interval. Read more
Source§

impl<D: IdDomain> PartialEq for Id<D>

Source§

fn eq(&self, other: &Self) -> bool

Tests for self and other values to be equal, and is used by ==.
1.0.0 · Source§

fn ne(&self, other: &Rhs) -> bool

Tests for !=. The default implementation is almost always sufficient, and should not be overridden without very good reason.
Source§

impl<D: IdDomain> PartialOrd for Id<D>

Source§

fn partial_cmp(&self, other: &Self) -> Option<Ordering>

This method returns an ordering between self and other values if one exists. Read more
1.0.0 · Source§

fn lt(&self, other: &Rhs) -> bool

Tests less than (for self and other) and is used by the < operator. Read more
1.0.0 · Source§

fn le(&self, other: &Rhs) -> bool

Tests less than or equal to (for self and other) and is used by the <= operator. Read more
1.0.0 · Source§

fn gt(&self, other: &Rhs) -> bool

Tests greater than (for self and other) and is used by the > operator. Read more
1.0.0 · Source§

fn ge(&self, other: &Rhs) -> bool

Tests greater than or equal to (for self and other) and is used by the >= operator. Read more
Source§

impl<D: IdDomain> Serialize for Id<D>

Available on crate feature serde only.
Source§

fn serialize<S: Serializer>(&self, serializer: S) -> Result<S::Ok, S::Error>

Serialize this value into the given Serde serializer. Read more
Source§

impl<D: IdDomain> TryFrom<&str> for Id<D>

Source§

type Error = IdParseError

The type returned in the event of a conversion error.
Source§

fn try_from(s: &str) -> Result<Self, Self::Error>

Performs the conversion.
Source§

impl<D: IdDomain> TryFrom<String> for Id<D>

Source§

type Error = IdParseError

The type returned in the event of a conversion error.
Source§

fn try_from(s: String) -> Result<Self, Self::Error>

Performs the conversion.
Source§

impl<D: IdDomain> TryFrom<u64> for Id<D>

Source§

type Error = IdParseError

The type returned in the event of a conversion error.
Source§

fn try_from(value: u64) -> Result<Self, Self::Error>

Performs the conversion.
Source§

impl<D: IdDomain> Copy for Id<D>

Source§

impl<D: IdDomain> Eq for Id<D>

Auto Trait Implementations§

§

impl<D> Freeze for Id<D>

§

impl<D> RefUnwindSafe for Id<D>
where D: RefUnwindSafe,

§

impl<D> Send for Id<D>

§

impl<D> Sync for Id<D>

§

impl<D> Unpin for Id<D>
where D: Unpin,

§

impl<D> UnsafeUnpin for Id<D>

§

impl<D> UnwindSafe for Id<D>
where D: UnwindSafe,

Blanket Implementations§

Source§

impl<T> Any for T
where T: 'static + ?Sized,

Source§

fn type_id(&self) -> TypeId

Gets the TypeId of self. Read more
Source§

impl<T> Borrow<T> for T
where T: ?Sized,

Source§

fn borrow(&self) -> &T

Immutably borrows from an owned value. Read more
Source§

impl<T> BorrowMut<T> for T
where T: ?Sized,

Source§

fn borrow_mut(&mut self) -> &mut T

Mutably borrows from an owned value. Read more
Source§

impl<T> CloneToUninit for T
where T: Clone,

Source§

unsafe fn clone_to_uninit(&self, dest: *mut u8)

🔬This is a nightly-only experimental API. (clone_to_uninit)
Performs copy-assignment from self to dest. Read more
Source§

impl<T> From<T> for T

Source§

fn from(t: T) -> T

Returns the argument unchanged.

Source§

impl<T, U> Into<U> for T
where U: From<T>,

Source§

fn into(self) -> U

Calls U::from(self).

That is, this conversion is whatever the implementation of From<T> for U chooses to do.

Source§

impl<T> ToOwned for T
where T: Clone,

Source§

type Owned = T

The resulting type after obtaining ownership.
Source§

fn to_owned(&self) -> T

Creates owned data from borrowed data, usually by cloning. Read more
Source§

fn clone_into(&self, target: &mut T)

Uses borrowed data to replace owned data, usually by cloning. Read more
Source§

impl<T> ToString for T
where T: Display + ?Sized,

Source§

fn to_string(&self) -> String

Converts the given value to a String. Read more
Source§

impl<T, U> TryFrom<U> for T
where U: Into<T>,

Source§

type Error = Infallible

The type returned in the event of a conversion error.
Source§

fn try_from(value: U) -> Result<T, <T as TryFrom<U>>::Error>

Performs the conversion.
Source§

impl<T, U> TryInto<U> for T
where U: TryFrom<T>,

Source§

type Error = <U as TryFrom<T>>::Error

The type returned in the event of a conversion error.
Source§

fn try_into(self) -> Result<U, <U as TryFrom<T>>::Error>

Performs the conversion.
Source§

impl<T> DeserializeOwned for T
where T: for<'de> Deserialize<'de>,