Crates.io | small_type_id |
lib.rs | small_type_id |
version | 0.1.1 |
created_at | 2025-06-21 18:38:23.878341+00 |
updated_at | 2025-08-03 22:23:57.561422+00 |
description | Crate for generation constant 32 bit nonzero unique identifiers for types. |
homepage | |
repository | https://github.com/AngelicosPhosphoros/small_type_id |
max_upload_size | |
id | 1721007 |
size | 74,009 |
This crate provides trait HasTypeId
with associated constant TYPE_ID
and derive macro to implement it for your types.
There are 4 guarantees:
TYPE_ID
is a constant.TypeId
cannot be zero which allows niche optimizations (size_of::<Option<TypeId>>()
is 4 bytes).Those guarantees would never be removed (even in semver breaking releases) so you can update dependency on this crate without validating your code that rely on that guarantees.
Uniqueness of TypeIds
is enforced by running code before fn main()
using ctor
crate.
std::any::TypeId
With std::any::TypeId
as at Rust 1.87.
TYPE_ID
is a constant.small_type_id::TypeId
is guaranteed to be 32 bits.small_type_id::TypeId
is significantly smaller(4 vs 16 bytes), allowing better performance due to less usage of CPU cache.small_type_id::TypeId
supports niche optimization for Option<small_type_id::TypeId>
.small_type_id::TypeId
guarantees that MSB is zero, allowing creating 32 bit identifiers by users using union
s:
small_type_id::HasTypeId
needs to be derived for supported types, it doesn't work automatically.small_type_id::HasTypeId
doesn't support generic types.typeid::ConstTypeId
With typeid
version 1.0.3
Example:
use small_type_id::HasTypeId as _;
#[derive(small_type_id::HasTypeId)]
pub struct Struct {
pub a: u32,
pub b: usize,
}
#[derive(small_type_id::HasTypeId)]
pub enum Enum {
A(u32), B(String)
}
// Check that they are different:
assert_ne!(Struct::TYPE_ID, Enum::TYPE_ID);
// Or even in compile time:
const { assert!(Struct::TYPE_ID.as_u32() != Enum::TYPE_ID.as_u32()); };
More examples and implementation explanation are available in documentation.
Uniqueness is tested before running fn main()
(unless opt-out), so code can rely on type ids being unique.
Code is tested in CI on following platforms:
There is also some testing with Address-Sanitizer.
ctor
used for implementing this crate.linkme
which helped to learn me about using
link sections for gathering statics.