Skip to main content

Crate ttid

Crate ttid 

Source
Expand description

Typed, readable IDs on top of UUIDv8.

TTID combines:

  • a 48-bit millisecond timestamp,
  • a 16-bit user-defined type id,
  • 58-bit randomness,
  • into a UUIDv8-compatible bit layout.

The human-facing string format is: "<type-name>_<shortuuid>"

where shortuuid is encoded with the short-uuid crate’s default base58 alphabet.

§Motivation

Plain UUIDs are globally unique but not ergonomic in logs and APIs. TTIDs keep UUID interoperability while adding:

  • explicit type context,
  • compact text form,
  • embedded time for quick debugging and coarse ordering.

The binary packing is timestamp-first (most significant payload bits), which improves locality for UUID-sorted database indexes.

§Example

use std::str::FromStr;
use ttid::{IdType, Ttid};

#[derive(Clone, Copy, Debug, PartialEq, Eq)]
enum MyType {
    User,
    Session,
}

impl IdType for MyType {
    fn to_type_id(self) -> u16 {
        match self {
            Self::User => 1,
            Self::Session => 2,
        }
    }

    fn from_type_id(id: u16) -> Option<Self> {
        match id {
            1 => Some(Self::User),
            2 => Some(Self::Session),
            _ => None,
        }
    }

    fn as_type_name(self) -> &'static str {
        match self {
            Self::User => "user",
            Self::Session => "session",
        }
    }

    fn from_type_name(name: &str) -> Option<Self> {
        match name {
            "user" => Some(Self::User),
            "session" => Some(Self::Session),
            _ => None,
        }
    }
}

let id = Ttid::<MyType>::new(MyType::User).unwrap();
let text = id.to_string();
let parsed = Ttid::<MyType>::from_str(&text).unwrap();

assert_eq!(parsed, id);
assert_eq!(parsed.id_type(), MyType::User);

Structs§

Ttid
Typed TTID wrapper around uuid::Uuid.

Enums§

ParseTtidError
Errors returned when parsing <type-name>_<shortuuid> strings.
TtidError
Errors returned when constructing or decoding raw TTID values.

Traits§

IdType
Maps a Rust type enum to a compact numeric id and readable type name.