1 个不稳定版本

0.1.0 2023年12月9日

#165 in #identifier


用于 stringid

LGPL-3.0-only

15KB
278

stringid

stringid 库是一套辅助工具(宏、结构体、特质),用于有效地管理标识符,既可以以人类可读的字符串形式,也可以以唯一的数字形式。对于使用在整个应用程序生命周期中存在的不可变字符串,它可能很有用。

唯一的标识符允许进行轻量级的存储、快速的比较和复制操作。而人类可读的字符串则允许在UI、序列化、调试等场景下方便地使用。

为什么要使用 StringId 呢?

您可以将 StringId 用于您希望使用不可变的 String(或 str)作为标识符的地方。特别是当这个标识符在数据中被多处使用时。使用 StringId 的两个优点是:

  • 不会重复字符串数据。
  • 比较、赋值和复制 Id 时不会使用字符串。

警告

StaticStrStore 一起使用 StringId 可能(安全地)会 泄露内存。为 str 分配的内存将不会在程序结束前释放,就像一个 'static 变量。因此,如果您认为标识符(String/str)可能会经常更改,则应避免使用 StringId 与不可变的 String,或者有意识地这样做。

典型用途包括:

  • 标签。
  • 跨资源引用,特别是当您需要序列化/反序列化数据时。

技术设计

StringId 变量仅存储标识符(一个唯一的数字)。而 [str] 被单独存储,每个 Id 只在内存中存储一次,并通过专用类型访问。

《stringid》组件被设计为与新类型模式一起使用。因此,可以通过模块macros访问一些宏,以帮助定义自定义类型。

要存储StringId与对应的 [str] 之间的对应关系,可以使用StrLookup的实现。 StrLookupHashMap通过std::collections::HashMap和一个StaticStrStore实现StrLookup

有关更多详细信息,请参阅相应的文档。

快速开始

use std::{mem::size_of, str::FromStr};
use stringid::macros::{strlookup_hashmap, StringIdImpl};
use stringid::{create_hash_map, BufferStrStore, StringId};

// Create a struct type `CustomIdLookup`
// as a `str` lookup with `BufferStrStore` as StrStore.
#[strlookup_hashmap(key = u32, store = BufferStrStore)]
struct CustomIdLookup;

// Create a `StringId` type who use the type `CustomIdLookup`
// as `StrLookup`.
#[derive(Debug, Clone, Copy, StringIdImpl)]
struct CustomId(StringId<u32, CustomIdLookup>);

// Create instances of CustomId from str
let id_1 = CustomId::from_str("Id1").unwrap();
let id_2 = CustomId::from_str("Id2").unwrap();
let id_1_bis = id_1;
let id_1_ter = CustomId::from_str("Id1").unwrap();

// CustomId size is the size of the Id (u32 here)
assert_eq!(size_of::<u32>(), size_of::<CustomId>());

// The Id1 and Id2 are not equal
assert_ne!(id_1,id_2);
// But the id_1 and id_1_bis are
assert_eq!(id_1,id_1_bis);
// as well as id_1 and id_1_ter
assert_eq!(id_1,id_1_ter);

许可证:LGPL-3.0-only

依赖项

~255–700KB
~17K SLoC