跳过正文

目录

uuid
#

https://docs.rs/uuid/latest/uuid/

UUID 是 128-bit 的值,常使用十六进制字符串进行格式化(分为 5 个部分),例如:67e55044-10b1-426f-9247-bb680e5fe0c8。

uuid 通过 feature 来指定使用的版本:

  1. v1 - Version 1 UUIDs using a timestamp and monotonic counter.
  2. v3 - Version 3 UUIDs based on the MD5 hash of some data.
  3. v4 - Version 4 UUIDs with random data.
  4. v5 - Version 5 UUIDs based on the SHA1 hash of some data.
  5. v6 - Version 6 UUIDs using a timestamp and monotonic counter.
  6. v7 - Version 7 UUIDs using a Unix timestamp.
  7. v8 - Version 8 UUIDs using user-defined data.

一般情况下如果要获得唯一值,使用 v4,如果要使用排序的唯一值,使用 v7。

UUID 可以被格式化为几种格式:

  1. simple: a1a2a3a4b1b2c1c2d1d2d3d4d5d6d7d8.
  2. hyphenated: a1a2a3a4-b1b2-c1c2-d1d2-d3d4d5d6d7d8.
  3. urn: urn:uuid:A1A2A3A4-B1B2-C1C2-D1D2-D3D4D5D6D7D8.
  4. braced: {a1a2a3a4-b1b2-c1c2-d1d2-d3d4d5d6d7d8}.

示例:

let my_uuid = Uuid::parse_str("a1a2a3a4b1b2c1c2d1d2d3d4d5d6d7d8")?;
println!("{}", my_uuid.urn());

// Note that this requires the `v4` feature to be enabled.
let my_uuid = Uuid::new_v4();
println!("{}", my_uuid);

let my_uuid = Uuid::parse_str("a1a2a3a4b1b2c1c2d1d2d3d4d5d6d7d8")?;
println!("{}", my_uuid.urn());

uuid 通过 serde 的 with attribute 来支持和 serde 的集成:https://docs.rs/uuid/latest/uuid/serde/compact/index.html

#[derive(serde_derive::Serialize, serde_derive::Deserialize)]
struct StructA {
    // This will change both serailization and deserialization
    #[serde(with = "uuid::serde::simple")]
    id: uuid::Uuid,
}

#[derive(serde_derive::Serialize, serde_derive::Deserialize)]
struct StructB {
    // This will be serialized as uuid::fmt::Simple and deserialize from all valid formats
    #[serde(serialize_with = "uuid::serde::simple::serialize")]
    id: uuid::Uuid,
}

diesel 等 ORM 也支持 uuid 类型:https://docs.diesel.rs/2.1.x/diesel/sql_types/struct.Uuid.html