Skip to main content

Ulid

Struct Ulid 

Source
pub struct Ulid(/* private fields */);
Expand description

A ULID which never is zero.

Because this Ulid can never become zero, size of Ulid and size of Option<Ulid> are guaranteed to be equal thanks to Rust null pointer optimization:

use std::mem::size_of;
use mr_ulid::Ulid;

assert_eq!(size_of::<Ulid>(), size_of::<Option<Ulid>>());

Parsing a zero value ULID will fail:

use mr_ulid::Ulid;

let s = "00000000000000000000000000";

assert!(s.parse::<Ulid>().is_err());

For a ULID which can become zero, check out the ZeroableUlid type. However, it is more idiomatic to just use Option<Ulid>.

Implementations§

Source§

impl Ulid

Source

pub const MIN: Self

Minimum allowed Ulid

The smallest value for Ulid is 1, because zero is explicitly not allowed.

§Example
use mr_ulid::Ulid;

assert_eq!(Ulid::MIN.to_u128(), 1);
Source

pub const MAX: Self

Maximum allowed Ulid

The largest value for Ulid is u128::MAX.

§Example
use mr_ulid::Ulid;

assert_eq!(Ulid::MAX.to_u128(), u128::MAX);
Source

pub fn new() -> Self

Generates a new unique ULID.

The generated ULIDs are guaranteed to be unique and monotonically increasing and never zero.

A lot of care is taken, that the ULIDs cannot overflow. You can create as many ULIDs as you like, and they will always be unique and strict monotonically increasing.

§Panics

With the standard entropy source (STANDARD_ENTROPY_SOURCE), this method will panic if the system date is somewhere after the year 10889 or before the Unix epoch (year 1970).

§Example
use mr_ulid::Ulid;

let u1 = Ulid::new();
let u2 = Ulid::new();

assert!(u1 != u2);
assert!(u1 < u2);

let t1 = u1.timestamp();
let t2 = u2.timestamp();

let r1 = u1.randomness();
let r2 = u2.randomness();

assert!((t1 < t2) || (t1 == t2 && r1 < r2));
Source

pub const fn timestamp(self) -> u64

Returns the timestamp part of a Ulid.

The timestamp is measured in milliseconds since the Unix epoch (1. January 1970). ULID timestamps are limited to 48 bits.

§Example
use mr_ulid::Ulid;

let u = Ulid::new();

assert!(u.timestamp() > 1704067200000); // 1st January 2024
Source

pub const fn randomness(self) -> u128

Returns the random part of a Ulid.

The randomness of a ULID is limited to 80 bits.

§Example
use mr_ulid::Ulid;

let u = Ulid::new();

assert!(u.randomness() < (1<<80));
Source

pub fn datetime(self) -> SystemTime

Returns the timestamp part of a Ulid as a SystemTime.

§Panics

In Rust the allowed range for SystemTime is not defined. So this method may panic if the timestamp of the ULID cannot represented with SystemTime. On most common systems that will not happen.

For a variant which never panics, see Ulid::try_datetime.

§Example
use std::time::SystemTime;
use mr_ulid::Ulid;

let u = Ulid::new();

assert!(u.datetime() <= SystemTime::now());
Source

pub const fn to_zeroable_ulid(self) -> ZeroableUlid

Converts this Ulid to a ZeroableUlid.

This method always succeeds, as every Ulid is a valid ZeroableUlid.

§Example
use mr_ulid::Ulid;

let u1 = Ulid::new();
let u2 = u1.to_zeroable_ulid();

assert_eq!(u1.to_u128(), u2.to_u128());
Source

pub const fn from_zeroable_ulid(zeroable: ZeroableUlid) -> Option<Self>

Creates a Ulid from a ZeroableUlid.

When the ZeroableUlid is zero, None is returned.

§Example
use mr_ulid::{Ulid, ZeroableUlid};

let u1 = ZeroableUlid::new();
assert!(Ulid::from_zeroable_ulid(u1).is_some());

let u2 = ZeroableUlid::zeroed(); // Create a ZeroableUlid with zero value
assert!(Ulid::from_zeroable_ulid(u2).is_none());
Source

pub const fn to_parts(self) -> (u64, u128)

Returns the timestamp and randomness parts of a Ulid as a pair.

§Example
use mr_ulid::Ulid;

let u = Ulid::new();
let (timestamp, randomness) = u.to_parts();

assert_eq!(timestamp, u.timestamp());
assert_eq!(randomness, u.randomness());
Source

pub const fn from_parts(timestamp: u64, randomness: u128) -> Result<Self, Error>

Creates a Ulid from a timestamp and randomness parts.

§Errors

Will fail if the timestamp (48 bits) or randomness (80 bits) are out of range, and will fail, if both values are zero, because Ulid is not allowed to be zero.

§Example
use mr_ulid::Ulid;

let u1 = Ulid::new();
let (timestamp, randomness) = u1.to_parts();
let u2 = Ulid::from_parts(timestamp, randomness)?;

assert_eq!(u1, u2);

assert!(Ulid::from_parts(0, 0).is_err());
Source

pub const fn to_bytes(self) -> [u8; 16]

Converts a Ulid into binary bytes

The bytes are in network byte order (big endian).

§Example
use mr_ulid::Ulid;

let ulid: Ulid = "01JB05JV6H9ZA2YQ6X3K1DAGVA".parse()?;

assert_eq!(ulid.to_bytes(), [1, 146, 192, 89, 108, 209, 79, 212, 47, 92, 221, 28, 194, 213, 67, 106]);
Source

pub const fn from_bytes(bytes: [u8; 16]) -> Option<Self>

Creates a Ulid from a binary byte array.

The byte array must be in network byte order (big endian).

Returns None if all bytes in the byte array are zero, because Ulid is not allowed to be zero.

§Example
use mr_ulid::Ulid;

let bytes: [u8; 16] = [1, 146, 192, 89, 108, 209, 79, 212, 47, 92, 221, 28, 194, 213, 67, 106];
let u = Ulid::from_bytes(bytes)?;

assert_eq!(u.to_string(), "01JB05JV6H9ZA2YQ6X3K1DAGVA");
Source

pub const fn to_u128(self) -> u128

Converts a Ulid into a u128 integer.

§Example
use mr_ulid::Ulid;

let u: Ulid = "01JB07NQ643XZXVHZDY0JNYR02".parse()?;

assert_eq!(u.to_u128(), 2091207293934528941058695985186693122);
Source

pub const fn from_u128(n: u128) -> Option<Self>

Creates a Ulid from a u128 integer.

§Errors

Return None if the value was zero, because Ulid is not allowed to be zero.

§Example
use mr_ulid::Ulid;

let n = 2091207293934528941058695985186693122_u128;
let u = Ulid::from_u128(n)?;

assert_eq!(u.to_string(), "01JB07NQ643XZXVHZDY0JNYR02");
Source

pub const fn to_non_zero_u128(self) -> NonZero<u128>

Converts a Ulid into a NonZero<u128> integer.

§Example
use std::num::NonZero;

use mr_ulid::Ulid;

let u = Ulid::from_u128(42)?;

assert_eq!(u.to_non_zero_u128(), NonZero::new(42)?);
Source

pub const fn from_non_zero_u128(non_zero: NonZero<u128>) -> Self

Creates a Ulid from a NonZero<u128> integer.

Because the NonZero<u128> integer cannot be zero, this method always succeed.

§Example
use std::num::NonZero;

use mr_ulid::Ulid;

let n = NonZero::new(2091207293934528941058695985186693122)?;
let u = Ulid::from_non_zero_u128(n);

assert_eq!(u.to_string(), "01JB07NQ643XZXVHZDY0JNYR02");
Source

pub fn try_new() -> Option<Self>

Generates a new Ulid and never panics.

This is a variant of Ulid::new() which never panics (with the STANDARD_ENTROPY_SOURCE).

In the case of problems with the ULID-generator, this function returns None.

§Example
use mr_ulid::Ulid;

let u1 = Ulid::try_new()?;
let u2 = Ulid::try_new()?;

assert!(u1 != u2);
assert!(u1.timestamp() <= u2.timestamp());
Source

pub fn try_datetime(self) -> Option<SystemTime>

Returns the timestamp part of a Ulid as a SystemTime and never panics.

This is a variant of Ulid::datetime() which never panics.

In the case that the timestamp of a Ulid cannot be encoded in a SystemTime, this method returns None.

§Example
use std::time::SystemTime;
use mr_ulid::Ulid;

let u = Ulid::new();

let datetime: Option<SystemTime> = u.try_datetime();
Source

pub fn try_to_string(self) -> Option<String>

Return the string representation of a Ulid and never panics.

While the blanket implementation of std::string::ToString for std::fmt::Display may panic, this method is guaranteed to never panic, but returns None if the string representation cannot be created. One reason this can happen is if the allocation of memory for the string fails.

Source

pub const unsafe fn from_parts_unchecked( timestamp: u64, randomness: u128, ) -> Self

Creates a Ulid from timestamp and randomness parts without checking.

This results in undefined behaviour if timestamp or randomness parts are too large or when both of them are zero.

§Safety
  • Timestamp must be less than 248.
  • Randomness must be less than 280.
  • One part (timestamp or randomness) must be non-zero.
Source

pub const unsafe fn from_u128_unchecked(n: u128) -> Self

Creates a Ulid from a u128 integer without checking whether the value is zero.

This results in undefined behaviour if the value is zero.

§Safety

The value must not be zero.

Source

pub const unsafe fn from_bytes_unchecked(bytes: [u8; 16]) -> Self

Creates a Ulid from a binary byte array without checking whether at least one byte is non-zero.

This results in undefined behaviour if all bytes are zero.

§Safety

At least one byte must be non-zero.

Trait Implementations§

Source§

impl Clone for Ulid

Source§

fn clone(&self) -> Ulid

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 Debug for Ulid

Source§

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

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

impl Default for Ulid

Source§

fn default() -> Self

Returns the “default value” for a type. Read more
Source§

impl<'de> Deserialize<'de> for Ulid

Source§

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

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

impl Display for Ulid

Source§

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

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

impl From<NonZero<u128>> for Ulid

Source§

fn from(non_zero: NonZero<u128>) -> Self

Converts to this type from the input type.
Source§

impl From<Ulid> for [u8; 16]

Source§

fn from(ulid: Ulid) -> Self

Converts to this type from the input type.
Source§

impl From<Ulid> for NonZero<u128>

Source§

fn from(ulid: Ulid) -> Self

Converts to this type from the input type.
Source§

impl From<Ulid> for ZeroableUlid

Source§

fn from(non_zero: Ulid) -> Self

Converts to this type from the input type.
Source§

impl From<Ulid> for u128

Source§

fn from(ulid: Ulid) -> Self

Converts to this type from the input type.
Source§

impl FromStr for Ulid

Source§

type Err = Error

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 Hash for Ulid

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 Ord for Ulid

Source§

fn cmp(&self, other: &Ulid) -> 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 PartialEq for Ulid

Source§

fn eq(&self, other: &Ulid) -> 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 PartialOrd for Ulid

Source§

fn partial_cmp(&self, other: &Ulid) -> 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 Serialize for Ulid

Source§

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

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

impl TryFrom<&[u8]> for Ulid

Source§

type Error = Error

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

fn try_from(bytes: &[u8]) -> Result<Self, Self::Error>

Performs the conversion.
Source§

impl TryFrom<&[u8; 16]> for Ulid

Source§

type Error = Error

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

fn try_from(bytes: &[u8; 16]) -> Result<Self, Self::Error>

Performs the conversion.
Source§

impl TryFrom<[u8; 16]> for Ulid

Source§

type Error = Error

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

fn try_from(bytes: [u8; 16]) -> Result<Self, Self::Error>

Performs the conversion.
Source§

impl TryFrom<ZeroableUlid> for Ulid

Source§

type Error = Error

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

fn try_from(zeroable: ZeroableUlid) -> Result<Self, Self::Error>

Performs the conversion.
Source§

impl TryFrom<u128> for Ulid

Source§

type Error = Error

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

fn try_from(n: u128) -> Result<Self, Self::Error>

Performs the conversion.
Source§

impl Copy for Ulid

Source§

impl Eq for Ulid

Source§

impl StructuralPartialEq for Ulid

Auto Trait Implementations§

§

impl Freeze for Ulid

§

impl RefUnwindSafe for Ulid

§

impl Send for Ulid

§

impl Sync for Ulid

§

impl Unpin for Ulid

§

impl UnwindSafe for Ulid

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