Skip to main content

GrainId

Struct GrainId 

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

Grain id struct

§Examples

// Generate random value.
let random = GrainId::random();

// Parse from string.
let from_str: GrainId = "012abcd".parse()?;

// Parse from integer.
let from_int: GrainId = 35990925u64.try_into()?;

assert_eq!(from_str, from_int);

Implementations§

Source§

impl GrainId

Source

pub const BITS: u32 = 35

The number of significant bits of a GrainId.

The value is stored in a u64, but only the lower 35 bits are used.

Source

pub const NIL: GrainId

The smallest value that can be represented by GrainId.

§Examples
assert_eq!(GrainId::NIL, "0000000".parse::<GrainId>()?);
assert_eq!(GrainId::NIL, GrainId::try_from(0)?);
Source

pub const MAX: GrainId

The largest value that can be represented by GrainId.

§Examples
assert_eq!(GrainId::MAX, "zzzzzzz".parse::<GrainId>()?);
assert_eq!(GrainId::MAX, GrainId::try_from((1 << GrainId::BITS) - 1)?);
Source

pub const fn is_nil(&self) -> bool

Test if the GrainId is nil.

§Examples
assert!("0000000".parse::<GrainId>()?.is_nil());
Source

pub const fn is_max(&self) -> bool

Test if the GrainId is max.

§Examples
assert!("zzzzzzz".parse::<GrainId>()?.is_max());
Source

pub const fn from_u64_lossy(int: u64) -> GrainId

Converts an unsigned integer to GrainId by truncating bits that exceed the valid range.

This is a lossy conversion that keeps only the lower BITS bits (i.e. the value modulo 235). If you need to detect out-of-range values, use from_u64 instead.

§Examples
// Values within range are preserved
let valid_int = 123;
let id = GrainId::from_u64_lossy(valid_int);
assert_eq!(u64::from(id), valid_int);

// Values exceeding 35 bits are truncated (MSBs dropped)
let oversized_int = valid_int + (1 << GrainId::BITS);
let overflowed_id = GrainId::from_u64_lossy(oversized_int);
assert_eq!(u64::from(overflowed_id), valid_int)
Source

pub const fn from_u64(value: u64) -> Result<GrainId, Error>

Attempts to convert a u64 to GrainId.

Returns an error if the value is larger than GrainId::MAX. If you don’t need to detect out-of-range values, use from_u64_lossy.

§Examples
assert_eq!(GrainId::from_u64(0x7FFFFFFFF)?, GrainId::MAX);
assert!(GrainId::from_u64(0x800000000).is_err());
Source

pub const fn as_u64(&self) -> &u64

👎Deprecated since 0.17.0:

Use to_u64() (or u64::from(id)) to get the value instead.

Returns a reference of internal 64bit integer.

Source

pub const fn to_u64(self) -> u64

Returns an internal 64bit integer value.

§Examples
let id = GrainId::from_u64(0x123456789)?;
assert_eq!(id.to_u64(), 0x123456789);
Source

pub const fn from_duration(duration: Duration) -> GrainId

Creates a GrainId from a Duration based on decisecond precision.

This method converts the given duration into deciseconds (0.1 second units) and generates a GrainId from it. The resulting 35-bit identifier can represent approximately 109 years worth of deciseconds.

§Timestamp Format

The entire 35 bits are used to represent the timestamp in deciseconds, allowing for chronological sorting while maintaining a compact 7-character BASE32 representation.

§Overflow Behavior

If the duration exceeds the maximum representable value (2^35 deciseconds, approximately 109 years), the timestamp will wrap around. This is generally not a concern for personal applications within a human lifespan.

§Examples
use std::time::Duration;

let duration = Duration::new(5, 730_023_852);
let id = GrainId::from_duration(duration);
assert_eq!(id, GrainId::from_u64(57)?);
Source

pub const fn wrapping_sub(self, rhs: GrainId) -> GrainId

Wrapping (modular) subtraction. Computes self - rhs, wrapping around at the boundary of the type.

§Examples
assert_eq!(
    GrainId::from_u64(100)?.wrapping_sub(GrainId::from_u64(100)?),
    GrainId::NIL
);
assert_eq!(
    GrainId::from_u64(100)?.wrapping_sub(GrainId::from_u64(101)?),
    GrainId::MAX
);
Source

pub const fn increment(self) -> GrainId

Increments the value by 1, wrapping around to GrainId::NIL on overflow.

§Examples
assert_eq!(GrainId::from_u64(100)?.increment(), GrainId::from_u64(101)?);
assert_eq!(GrainId::MAX.increment(), GrainId::NIL);
Source

pub const fn from_byte_prefix(bytes: &[u8; 5]) -> GrainId

Creates a GrainId from the leading (most significant) 35 bits of a 5-byte array.

This is useful for generating a compact identifier from a pre-computed hash, public key, or any arbitrary byte sequence.

§Examples
// Extract leading 35 bits from a byte array
let bytes = [0xFF, 0xFF, 0xFF, 0xFF, 0xFF];
let id = GrainId::from_byte_prefix(&bytes);
assert_eq!(id, GrainId::MAX);

// For longer data, slice the first 5 bytes
let hash: [u8; 32] = [0; 32];
let id = GrainId::from_byte_prefix(hash[..5].try_into().unwrap());
assert_eq!(id, GrainId::NIL);
Source

pub const fn from_byte_suffix(bytes: &[u8; 5]) -> GrainId

Creates a GrainId from the trailing (least significant) 35 bits of a 5-byte array.

This is the counterpart to from_byte_prefix. The upper 5 bits of the first byte are ignored.

§Examples
// Extract trailing 35 bits from a byte array
let bytes = [0xFF, 0xFF, 0xFF, 0xFF, 0xFF];
let id = GrainId::from_byte_suffix(&bytes);
assert_eq!(id, GrainId::MAX);

// Upper 5 bits of the first byte are ignored
let bytes = [0xF8, 0x00, 0x00, 0x00, 0x00];
let id = GrainId::from_byte_suffix(&bytes);
assert_eq!(id, GrainId::NIL);
Source

pub const fn to_byte_prefix(self) -> [u8; 5]

Returns a 5-byte array with the GrainId value stored in the leading (most significant) 35 bits.

This is the counterpart to from_byte_prefix. The lower 5 bits of the last byte are always zero.

§Examples
let bytes = GrainId::from_u64(0x123456789)?.to_byte_prefix();
assert_eq!(bytes, [0x24, 0x68, 0xAC, 0xF1, 0x20]);

// Round-trip
let id = GrainId::from_u64(0x123456789)?;
assert_eq!(GrainId::from_byte_prefix(&id.to_byte_prefix()), id);
Source

pub const fn to_byte_suffix(self) -> [u8; 5]

Returns a 5-byte array with the GrainId value stored in the trailing (least significant) 35 bits.

This is the counterpart to from_byte_suffix. The upper 5 bits of the first byte are always zero.

§Examples
let bytes = GrainId::from_u64(0x123456789)?.to_byte_suffix();
assert_eq!(bytes, [0x01, 0x23, 0x45, 0x67, 0x89]);

// Round-trip
let id = GrainId::from_u64(0x123456789)?;
assert_eq!(GrainId::from_byte_suffix(&id.to_byte_suffix()), id);
Source§

impl GrainId

Source

pub fn from_timestamp_unix<T>(timestamp: T) -> GrainId
where T: Into<SystemTime>,

Creates a GrainId from a Duration from UNIX_EPOCH to timestamp based on decisecond precision.

See GrainId::from_duration and GrainId::from_timestamp_since for more details.

§Examples
use jiff::Timestamp;
use std::time::SystemTime;

let timestamp = Timestamp::now();
let id = GrainId::from_timestamp_unix(SystemTime::try_from(timestamp).unwrap());
assert_eq!(id.to_u64(), ((timestamp.as_millisecond() / 100) as u64));
Source

pub fn from_timestamp_since<T, U>(timestamp: T, base_time: U) -> GrainId
where T: Into<SystemTime>, U: Into<SystemTime>,

Creates a GrainId from a Duration from base_time to timestamp based on decisecond precision.

See GrainId::from_duration for more details.

§Behavior when timestamp is earlier than base_time

If timestamp is earlier than base_time, Returns the value obtained by wrapping substracting the absolute value of the duration from NIL

§Examples
use jiff::Timestamp;
use std::time::SystemTime;

let base_time: Timestamp = "2025-01-01T00:00:00Z".parse().unwrap();
let timestamp: Timestamp = "2025-11-28T12:34:56.000789Z".parse().unwrap();
let id = GrainId::from_timestamp_since(
    SystemTime::try_from(timestamp).unwrap(),
    SystemTime::try_from(base_time).unwrap(),
);
assert_eq!(
    id.to_u64(),
    ((timestamp.duration_since(base_time).as_millis() / 100) as u64)
);
Source

pub fn now_unix() -> GrainId

Creates a GrainId from a Duration from UNIX_EPOCH to SystemTime::now() based on decisecond precision.

See GrainId::from_duration and GrainId::from_timestamp_since for more details.

Source

pub fn now_since<T>(base_time: T) -> GrainId
where T: Into<SystemTime>,

Creates a GrainId from a Duration from base_time to SystemTime::now() based on decisecond precision.

See GrainId::from_duration and GrainId::from_timestamp_since for more details.

Source§

impl GrainId

Source

pub fn random() -> GrainId

Generate a new random GrainId.

Every value, including NIL and MAX, is equally likely. Uses rand::rng(); to use another generator, sample StandardUniform with it instead (e.g. rng.random::<GrainId>()).

§Examples
let id = GrainId::random();
assert!(id <= GrainId::MAX);

Trait Implementations§

Source§

impl AsRef<u64> for GrainId

Source§

fn as_ref(&self) -> &u64

Converts this type into a shared reference of the (usually inferred) input type.
Source§

impl Clone for GrainId

Source§

fn clone(&self) -> GrainId

Returns a duplicate of the value. Read more
1.0.0 (const: unstable) · Source§

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

Performs copy-assignment from source. Read more
Source§

impl Copy for GrainId

Source§

impl Debug for GrainId

Source§

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

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

impl<'de> Deserialize<'de> for GrainId

Source§

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

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

impl Display for GrainId

Source§

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

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

impl Eq for GrainId

Source§

impl FromStr for GrainId

Source§

fn from_str(s: &str) -> Result<GrainId, <GrainId as FromStr>::Err>

Parses a 7-character grain-id string.

Decoding is case-insensitive and accepts the aliases described in alphabet.

§Examples
assert_eq!("012ABCD".parse::<GrainId>()?, "o12abcd".parse::<GrainId>()?);
assert_eq!("0123".parse::<GrainId>(), Err(Error::InvalidLength(4)));
// Non-ASCII input is rejected, never panics.
assert!("ab€cd".parse::<GrainId>().is_err());
Source§

type Err = Error

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

impl Hash for GrainId

Source§

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

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 GrainId

Source§

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

This method returns an Ordering between self and other. Read more
1.21.0 (const: unstable) · Source§

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

Compares and returns the maximum of two values. Read more
1.21.0 (const: unstable) · Source§

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

Compares and returns the minimum of two values. Read more
1.50.0 (const: unstable) · Source§

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

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

fn clamp_to<R>(self, range: R) -> Self
where Self: Sized, R: ClampBounds<Self>,

🔬This is a nightly-only experimental API. (clamp_to)
Restrict a value to a certain range. Read more
Source§

impl PartialEq for GrainId

Source§

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

Equality operator ==. Read more
1.0.0 (const: unstable) · Source§

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

Inequality operator !=. Read more
Source§

impl PartialOrd for GrainId

Source§

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

This method returns an ordering between self and other values if one exists. Read more
1.0.0 (const: unstable) · 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 (const: unstable) · 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 (const: unstable) · 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 (const: unstable) · 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 GrainId

Serializes as a 7-character string in human-readable formats and as a u64 otherwise.

Source§

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

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

impl StructuralPartialEq for GrainId

Source§

impl TryFrom<u64> for GrainId

Source§

fn try_from(value: u64) -> Result<GrainId, <GrainId as TryFrom<u64>>::Error>

Attempts to convert a u64 to GrainId.

See GrainId::from_u64 for details.

§Examples
assert!(GrainId::try_from(GrainId::MAX.to_u64()).is_ok());
assert!(GrainId::try_from(GrainId::MAX.to_u64() + 1).is_err());
Source§

type Error = Error

The type returned in the event of a conversion error.

Auto Trait Implementations§

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> DeserializeOwned for T
where T: for<'de> Deserialize<'de>,

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 = !

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

fn try_from(value: U) -> Result<T, !>

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.