Struct ulid::Ulid

source ·
pub struct Ulid(pub u128);
Expand description

A Ulid is a unique 128-bit lexicographically sortable identifier

Canonically, it is represented as a 26 character Crockford Base32 encoded string.

Of the 128-bits, the first 48 are a unix timestamp in milliseconds. The remaining 80 are random. The first 48 provide for lexicographic sorting and the remaining 80 ensure that the identifier is unique.

Tuple Fields§

§0: u128

Implementations§

source§

impl Ulid

source

pub fn new() -> Ulid

Creates a new Ulid with the current time (UTC)

Using this function to generate Ulids will not guarantee monotonic sort order. See [ulid::Generator] for a monotonic sort order.

§Example
use ulid::Ulid;

let my_ulid = Ulid::new();
source

pub fn with_source<R: Rng>(source: &mut R) -> Ulid

Creates a new Ulid using data from the given random number generator

§Example
use rand::prelude::*;
use ulid::Ulid;

let mut rng = StdRng::from_entropy();
let ulid = Ulid::with_source(&mut rng);
source

pub fn from_datetime(datetime: SystemTime) -> Ulid

Creates a new Ulid with the given datetime

This can be useful when migrating data to use Ulid identifiers.

This will take the maximum of the [SystemTime] argument and [SystemTime::UNIX_EPOCH] as earlier times are not valid for a Ulid timestamp

§Example
use std::time::{SystemTime, Duration};
use ulid::Ulid;

let ulid = Ulid::from_datetime(SystemTime::now());
source

pub fn from_datetime_with_source<R>( datetime: SystemTime, source: &mut R, ) -> Ulid
where R: Rng + ?Sized,

Creates a new Ulid with the given datetime and random number generator

This will take the maximum of the [SystemTime] argument and [SystemTime::UNIX_EPOCH] as earlier times are not valid for a Ulid timestamp

§Example
use std::time::{SystemTime, Duration};
use rand::prelude::*;
use ulid::Ulid;

let mut rng = StdRng::from_entropy();
let ulid = Ulid::from_datetime_with_source(SystemTime::now(), &mut rng);
source

pub fn datetime(&self) -> SystemTime

Gets the datetime of when this Ulid was created accurate to 1ms

§Example
use std::time::{SystemTime, Duration};
use ulid::Ulid;

let dt = SystemTime::now();
let ulid = Ulid::from_datetime(dt);

assert!(
    dt + Duration::from_millis(1) >= ulid.datetime()
    && dt - Duration::from_millis(1) <= ulid.datetime()
);
source§

impl Ulid

source

pub const TIME_BITS: u8 = 48u8

The number of bits in a Ulid’s time portion

source

pub const RAND_BITS: u8 = 80u8

The number of bits in a Ulid’s random portion

source

pub const fn from_parts(timestamp_ms: u64, random: u128) -> Ulid

Create a Ulid from separated parts.

NOTE: Any overflow bits in the given args are discarded

§Example
use ulid::Ulid;

let ulid = Ulid::from_string("01D39ZY06FGSCTVN4T2V9PKHFZ").unwrap();

let ulid2 = Ulid::from_parts(ulid.timestamp_ms(), ulid.random());

assert_eq!(ulid, ulid2);
source

pub const fn from_string(encoded: &str) -> Result<Ulid, DecodeError>

Creates a Ulid from a Crockford Base32 encoded string

An DecodeError will be returned when the given string is not formatted properly.

§Example
use ulid::Ulid;

let text = "01D39ZY06FGSCTVN4T2V9PKHFZ";
let result = Ulid::from_string(text);

assert!(result.is_ok());
assert_eq!(&result.unwrap().to_string(), text);
source

pub const fn nil() -> Ulid

The ‘nil Ulid’.

The nil Ulid is special form of Ulid that is specified to have all 128 bits set to zero.

§Example
use ulid::Ulid;

let ulid = Ulid::nil();

assert_eq!(
    ulid.to_string(),
    "00000000000000000000000000"
);
source

pub const fn timestamp_ms(&self) -> u64

Gets the timestamp section of this ulid

§Example
use std::time::{SystemTime, Duration};
use ulid::Ulid;

let dt = SystemTime::now();
let ulid = Ulid::from_datetime(dt);

assert_eq!(u128::from(ulid.timestamp_ms()), dt.duration_since(SystemTime::UNIX_EPOCH).unwrap_or(Duration::ZERO).as_millis());
source

pub const fn random(&self) -> u128

Gets the random section of this ulid

§Example
use ulid::Ulid;

let text = "01D39ZY06FGSCTVN4T2V9PKHFZ";
let ulid = Ulid::from_string(text).unwrap();
let ulid_next = ulid.increment().unwrap();

assert_eq!(ulid.random() + 1, ulid_next.random());
source

pub fn to_str<'buf>( &self, buf: &'buf mut [u8], ) -> Result<&'buf mut str, EncodeError>

👎Deprecated since 1.2.0: Use the infallible array_to_str instead.

Creates a Crockford Base32 encoded string that represents this Ulid

§Example
use ulid::Ulid;

let text = "01D39ZY06FGSCTVN4T2V9PKHFZ";
let ulid = Ulid::from_string(text).unwrap();

let mut buf = [0; ulid::ULID_LEN];
let new_text = ulid.to_str(&mut buf).unwrap();

assert_eq!(new_text, text);
source

pub fn array_to_str<'buf>(&self, buf: &'buf mut [u8; 26]) -> &'buf mut str

Creates a Crockford Base32 encoded string that represents this Ulid

§Example
use ulid::Ulid;

let text = "01D39ZY06FGSCTVN4T2V9PKHFZ";
let ulid = Ulid::from_string(text).unwrap();

let mut buf = [0; ulid::ULID_LEN];
let new_text = ulid.array_to_str(&mut buf);

assert_eq!(new_text, text);
source

pub fn to_string(&self) -> String

Creates a Crockford Base32 encoded string that represents this Ulid

§Example
use ulid::Ulid;

let text = "01D39ZY06FGSCTVN4T2V9PKHFZ";
let ulid = Ulid::from_string(text).unwrap();

assert_eq!(&ulid.to_string(), text);
source

pub const fn is_nil(&self) -> bool

Test if the Ulid is nil

§Example
use ulid::Ulid;

let ulid = Ulid::new();
assert!(!ulid.is_nil());

let nil = Ulid::nil();
assert!(nil.is_nil());
source

pub const fn increment(&self) -> Option<Ulid>

Increment the random number, make sure that the ts millis stays the same

source

pub const fn from_bytes(bytes: [u8; 16]) -> Ulid

Creates a Ulid using the provided bytes array.

§Example
use ulid::Ulid;
let bytes = [0xFF; 16];

let ulid = Ulid::from_bytes(bytes);

assert_eq!(
    ulid.to_string(),
    "7ZZZZZZZZZZZZZZZZZZZZZZZZZ"
);
source

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

Returns the bytes of the Ulid in big-endian order.

§Example
use ulid::Ulid;

let text = "7ZZZZZZZZZZZZZZZZZZZZZZZZZ";
let ulid = Ulid::from_string(text).unwrap();

assert_eq!(ulid.to_bytes(), [0xFF; 16]);

Trait Implementations§

source§

impl Clone for Ulid

source§

fn clone(&self) -> Ulid

Returns a copy 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

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

source§

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

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

impl From<[u8; 16]> for Ulid

source§

fn from(bytes: [u8; 16]) -> Self

Converts to this type from the input type.
source§

impl From<(u64, u64)> for Ulid

source§

fn from((msb, lsb): (u64, u64)) -> 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 (u64, u64)

source§

fn from(ulid: Ulid) -> (u64, u64)

Converts to this type from the input type.
source§

impl From<Ulid> for String

source§

fn from(ulid: Ulid) -> String

Converts to this type from the input type.
source§

impl From<Ulid> for u128

source§

fn from(ulid: Ulid) -> u128

Converts to this type from the input type.
source§

impl From<u128> for Ulid

source§

fn from(value: u128) -> Ulid

Converts to this type from the input type.
source§

impl FromStr for Ulid

§

type Err = DecodeError

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

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

impl PartialEq for Ulid

source§

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

This method tests for self and other values to be equal, and is used by ==.
1.0.0 · source§

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

This method 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

This method 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

This method 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

This method 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

This method tests greater than or equal to (for self and other) and is used by the >= operator. Read more
source§

impl TryFrom<&str> for Ulid

§

type Error = DecodeError

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

fn try_from(value: &str) -> 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§

default unsafe fn clone_to_uninit(&self, dst: *mut T)

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

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

source§

unsafe fn clone_to_uninit(&self, dst: *mut T)

🔬This is a nightly-only experimental API. (clone_to_uninit)
Performs copy-assignment from self to dst. 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,

§

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§

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

§

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

§

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<V, T> VZip<V> for T
where V: MultiLane<T>,

source§

fn vzip(self) -> V