tagid - Typed Unique Identifiers for Rust Entities
tagid provides a robust system for defining and managing typed unique identifiers in Rust.
It supports multiple ID generation strategies (CUID, UUID, Snowflake) and integrates seamlessly with
serde, sqlx, and other frameworks.
Features
- Typed Identifiers: Define entity-specific IDs with compile-time safety.
- Multiple ID Generators:
- CUID (
cuidfeature) - Compact, collision-resistant IDs. - UUID (
uuidfeature) - Universally unique identifiers. - Snowflake (
snowflakefeature) - Time-based, distributed IDs.
- CUID (
- Entity Labeling: Labels provide contextual meaning to identifiers.
- Serialization & Database Support:
- [
serde] integration for JSON and binary serialization (serdefeature). - [
sqlx] integration for database storage (sqlxfeature).
- [
- Custom Labeling: Define custom label formats for entities, which can be useful to disambiguate ids in logging.
Installation
Add tagid to your Cargo.toml, enabling the desired features:
[]
= { = "0.3.1", = ["uuid", "serde", "sqlx"] }
Optional Features
| Feature | Description |
|---|---|
"derive" |
Enables #[derive(Label)] macro for automatic labeling. |
"cuid" |
Enables the [CuidGenerator] for CUID-based IDs. |
"uuid" |
Enables the [UuidGenerator] for UUID-based IDs. |
"snowflake" |
Enables the [SnowflakeGenerator] for distributed IDs. |
"serde" |
Enables serialization support via serde. |
"sqlx" |
Enables database integration via sqlx. |
"disintegrate" |
Enables tagid identifiers in disintegrate. |
"envelope" |
Provides an envelope struct for wrapping IDs with metadata. |
Usage
Defining an Entity with a Typed ID
use ;
;
Labeling System
Labels help associate an identifier with an entity, improving clarity in logs and databases. The Label trait provides a way to define a unique label for each entity type.
use ;
;
let order_label = labeler.label;
assert_eq!;
This ensures that IDs are self-descriptive when displayed, stored, or logged.
Working with Different ID Types
Using CUIDs
Enable the cuid feature in Cargo.toml:
[]
= { = "0.2", = ["cuid"] }
Example usage:
use ;
;
Using UUIDs
Enable the uuid feature:
[]
= { = "0.2", = ["uuid"] }
Example usage:
use ;
;
Using Snowflake IDs
Enable the snowflake feature:
[]
= { = "0.2", = ["snowflake"] }
Example usage:
use ;
;
Serialization & Database Integration
JSON Serialization with serde
Enable the serde feature in Cargo.toml
[]
= { = "0.2", = ["serde", "derive"] }
= { = "1.0", = ["derive"] }
= "1"
Then serialize an ID:
use ;
use ;
;
SQL Database Integration with sqlx
Enable sqlx support in Cargo.toml:
[]
= { = "0.2", = ["sqlx", "derive"] }
= { = "0.7", = ["postgres"] }
Then use `Is<T, ID> in a database model:
use ;
use FromRow;
;
Benchmarking
To measure the performance of difference ID generators, run:
cargo bench
Contributing
Contributions are welcome! Open an issue or submit a pull request on GitHub.
License
This project is licensed under the MIT License. See the LICENSE file for details.