THIS IS ALPHA RELEASE PLEASE DO NOT USE
Small Type Id
This crate provides trait HasTypeId with associated constant TYPE_ID and derive macro to implement it for your types.
There are 4 guarantees:
TYPE_IDis a constant.- Size is 32 bit.
TypeIdcannot be zero which allows niche optimizations (size_of::<Option<TypeId>>()is 4 bytes).- Most significant bit (MSB) is guaranteed to be zero:
- Allows users to use this bit to distinguish with some other kind of id in a union (e.g. Runtime types from some scripting engine).
- Does not allow niche optimizations on current version of Rust yet.
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 them.
Comparison with std::any::TypeId
With std::any::TypeId as at Rust 1.87.
Advantages
TYPE_IDis a constant.- Size of
small_type_id::TypeIdis guaranteed to be 32 bits. - Size of
small_type_id::TypeIdis significantly smaller(4 vs 16 bytes), allowing better performance due to less usage of CPU cache. small_type_id::TypeIdsupports niche optimization forOption<small_type_id::TypeId>.small_type_id::TypeIdguarantees that MSB is zero, allowing creating 32 bit identifiers by users usingunions:
- Since user types would need to set MSB to 1, resulting value is still cannot be zero, allowing niche optimization.
Downsides
small_type_id::HasTypeIdneeds to be derived for supported types, it doesn't work automatically.small_type_id::HasTypeIddoesn't support generic types.
Comparison with typeid::ConstTypeId
With typeid version 1.0.3
Advantages
- Has smaller size (32 bit vs 64 bit on 64-bit targets).
- Has defined internal representation that can be utilized by users.
Disadvantages
- Doesn't support every type.
How it works and how to use API.
Example:
use HasTypeId as _;
// Check that they are different:
assert_ne!;
// Or even in compile time:
const ;
More examples and implementation explanation are available in documentation.