Skip to main content

Crate typedflake

Crate typedflake 

Source
Expand description

Snowflake-style IDs as distinct, validated newtypes.

Declare an ID type with #[typedflake], install a node once with init, and generate IDs anywhere:

use typedflake::typedflake;

#[typedflake(epoch = "2025-01-01")]
pub struct UserId(i64);

#[typedflake(epoch = "2025-01-01")]
pub struct OrderId(i64);

// Once, during application startup.
typedflake::init(17)?;

// Anywhere in the application.
let user_id = UserId::generate()?;
let order_id = OrderId::generate()?;

assert_eq!(user_id.parts().node, 17);
assert_eq!(order_id.to_string().parse::<OrderId>()?, order_id);

UserId and OrderId are separate types: they cannot be mixed up, and each keeps its own generation state.

§Uniqueness

IDs of one type are unique as long as no two running processes use the same node for it, and the system clock does not move backwards across a restart. This crate does not assign nodes or coordinate deployments.

§Features

FeatureEnables
serdeSerde and SerdeEncoded derives
sqlx-postgresSqlxPostgres derive
postgresPostgres derive for postgres-types
tokiogenerate_async methods

Structs§

Alphabet
The characters an ID is written with, one per digit.
BitLayout
Number of bits given to each part of an ID.
Encoded
An ID written in its alphabet. Returned by encode.
Epoch
Instant that ID timestamps are measured from.
Format
Persistent format of an ID type: its epoch and bit allocation.
Generator
Generates IDs of type I for one node.
NodeError
A node field holds a value too large for its width.
Parts
The timestamp, node, and sequence of an ID.
TimestampError
An ID’s creation time does not fit in a u64 of Unix milliseconds.

Enums§

DecodeIdError
A string could not be decoded as an ID.
FormatError
Reason a Format cannot be used by an ID type.
GenerateError
An ID could not be generated.
GeneratorError
A generator could not be created for a node.
InitError
A default node could not be installed.
InvalidId
A raw value or set of parts is not a valid ID for the format.
ParseIdError
A string could not be parsed as an ID.

Traits§

EncodedId
An ID type with an alphabet, declared with the alphabet option of #[typedflake].
Id
An ID type declared with #[typedflake].
Node
A value that fills the node field of an ID.
Repr
Integer an ID is stored in: i64 or u64.

Functions§

init
Installs the node used by the static generate methods of every ID type with this kind of node.

Attribute Macros§

typedflake
Declares a Snowflake-style ID type.

Derive Macros§

Postgres
Implements postgres-types’ ToSql and FromSql for an i64 ID type, stored as BIGINT.
Serde
Implements Serde’s Serialize and Deserialize for an ID type.
SerdeEncoded
Implements Serde’s Serialize and Deserialize for an ID type, using its encoded text.
SqlxPostgres
Implements SQLx’s PostgreSQL Type, Encode, Decode, and array support for an i64 ID type, stored as BIGINT.
TypedNode
Splits the node field of an ID into named parts.