15 个不稳定版本 (5 个重大更改)

0.5.1 2024年6月10日
0.5.0 2024年1月8日
0.4.1 2023年12月26日
0.4.0 2023年11月4日
0.0.0 2023年2月12日

#303 in 网页编程

Download history 18/week @ 2024-04-22 8/week @ 2024-05-06 26/week @ 2024-05-13 17/week @ 2024-05-20 2/week @ 2024-05-27 65/week @ 2024-06-03 312/week @ 2024-06-10 52/week @ 2024-06-17 38/week @ 2024-06-24 5/week @ 2024-07-01 14/week @ 2024-07-08 95/week @ 2024-07-15 46/week @ 2024-07-22 29/week @ 2024-07-29

每月下载量 172

MIT 许可证

42KB
722

pxid

前缀全局唯一标识符

Crates.io Documentation Build Clippy Formatter

动机

通过添加前缀功能并支持通过适应前缀位来使用 u16 类型,扩展 rs/xid 实现。

本库灵感来源于 Stripe IDs,这些 IDs 具有友好的表示法且非常短。这些 ID 前缀最多包含 4 字节,属于其背后的实体。

使用方法

use pxid::Pxid;

fn main() -> 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
}

为了提高内存使用(减少分配),并重用所需的依赖项,还可以使用 Factory 结构体来构建 Pxid 实例。

这是构建 Pxid 实例的推荐方法,因为资源初始化一次后,就可以重复使用。

use pxid::Factory;

fn main() -> Result<(), Box<dyn std::error::Error>> {
    let factory = Factory::new_without_prefix()?;
    let id = factory.with_prefix("acct");

    println!("{}", id); // acct_9m4e2mr0ui3e8a215n4g

    let factory_with_prefix = Factory::new("acct")?;
    let id = factory_with_prefix.generate();

    println!("{}", id); // acct_9m4e2mr0ui3e8a215n4g
}

GraphQL 支持

您可以通过 async-graphql crate 在 GraphQL 中使用 async-graphql。确保已启用 graphql 功能,并导入 Pxid 以供 GraphQL 使用。

use async_graphql::{Context, InputObject, Result, SimpleObject};
use pxid::graphql::Pxid;

// -- snip --

#[derive(Debug, InputObject)]
pub struct PostCreateInput {
    pub title: String,
    pub content: String,
    pub parent_id: Option<Pxid>,
}

impl PostCreate {
    pub async fn exec(ctx: &Context<'_>, input: PostCreateInput) -> Result<Self> {
// -- snip --

查看完整的示例 这里

布局

由于数据格式紧凑,前缀 XID 在 16 字节切片上非常适合。

0 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15
前缀 时间戳 机器 ID 进程 ID 计数器

总计 16 字节。

前缀允许最多 4 个 UTF-8 字符,这使得 ID 可以提供一些关于其作用域的上下文。

acct_9m4e2mr0ui3e8a215n4g
ordr_9m4e2mr0ui3e8a215n4g
usr_9m4e2mr0ui3e8a215n4g

这样,ID 不仅更难以发生冲突,而且还可以为记录关联提供一些上下文。

许可证

本项目采用 MIT 许可证

依赖项

~0.6–12MB
~156K SLoC