- Notifications
You must be signed in to change notification settings - Fork0
An extended version of XID (Globally Unique Identifiers) which supports prefixes and is stored in 16 bytes
License
whizzes/pxid
Folders and files
Name | Name | Last commit message | Last commit date | |
---|---|---|---|---|
Repository files navigation
Extend thers/xid implementation by adding capability to havea prefix and at the same time have au16
type support by fitting prefix bits.
This library is inspired in Stripe IDs which have a friendly notation and arevery short IDs. These IDs are prefixed with a maximum of 4 bytes belonging tothe entity behind them.
use pxid::Pxid;fnmain() ->Result<(),Box<dyn std::error::Error>>{// Given that some of the dependencies to build// an instance of the Pxid may fail.// - Getting current timestamp// - Getting machine id// - Getting process id//// A `Result<Pxid, Error>` is returned.let id =Pxid::new("acct".as_bytes())?;println!("{}", id);// acct_9m4e2mr0ui3e8a215n4g}
To improve memory usage (reduce allocations), and reuse dependencies required,theFactory
struct can also be used to buildPxid
instances.
This is the recommended way to buildPxid
instances, given that resources areinitialized once, and then reused.
use pxid::Factory;fnmain() ->Result<(),Box<dyn std::error::Error>>{let factory =Factory::new_without_prefix()?;let id = factory.with_prefix("acct");println!("{}", id);// acct_9m4e2mr0ui3e8a215n4glet factory_with_prefix =Factory::new("acct")?;let id = factory_with_prefix.generate();println!("{}", id);// acct_9m4e2mr0ui3e8a215n4g}
You can usePxid
on GraphQL via theasync-graphql
crate.Make sure thegraphql
feature is enabled and importPxid
for GraphQL.
use async_graphql::{Context,InputObject,Result,SimpleObject};use pxid::graphql::Pxid;// -- snip --#[derive(Debug,InputObject)]pubstructPostCreateInput{pubtitle:String,pubcontent:String,pubparent_id:Option<Pxid>,}implPostCreate{pubasyncfn exec(ctx:&Context<'_>,input:PostCreateInput) ->Result<Self>{// -- snip --
Check out the full examplehere.
A prefixed XID fits nicely on a 16 bytes slice thanks to its packed data format.
0 | 1 | 2 | 3 | 4 | 5 | 6 | 7 | 8 | 9 | 10 | 11 | 12 | 13 | 14 | 15 |
Prefix | Timestamp | Machine ID | Process ID | Counter |
For a total of 16 bytes.
The prefix allows up to 4 UTF-8 Characters, this allows the ID to provide somecontext about its scope.
acct_9m4e2mr0ui3e8a215n4gordr_9m4e2mr0ui3e8a215n4gusr_9m4e2mr0ui3e8a215n4g
This way IDs are not only even harder to collide, but they also provides a bitof context on record association.
This project is licensed under the MIT License
About
An extended version of XID (Globally Unique Identifiers) which supports prefixes and is stored in 16 bytes