Crate stable_id

source ·
Expand description

This crate mainly deals with issuing and maintaining stability of indices. It provides 4 structs and each helps in different area.

This library was created for my game development endeavor. Not going great on that front as I kept restarting the project. However, I saw these utility structures coming back multiple times so I’m making a crate for them.

In version 0.2.0, you can supply custom Id tuple structs that are based on unsigned integers (from 8bit to 64bits). The id type needs to be derived with the following:

// Minimal needed for all traits that are introduced by this crate.
#[derive(derive_stable_id::StableId)]
struct Id(u8);


// These are needed under normal circumstances.
#[derive(derive_stable_id::StableId)]
struct Id32(u32);

let x: stable_id::Eids<Id32> = Default::default();
let x: stable_id::Sequence<Id32> = Default::default();
let x: stable_id::SparseEntities<Id32, String> = Default::default();
let x: stable_id::Entities<Id32, String> = Default::default();
let x: stable_id::Tec<Id32, String> = Default::default();

Use cases

StructTypeSuggestionDescription
EidsIdDense dataYou want a way to create ids, and do care about recovering ids.
SequenceIdSparse dataYou want a way to create ids, and don’t care about recovering ids, but you don’t want to use the HashMap-based Entities struct.
EntitiesCollectionDense dataThe go-to collection of this library.
SparseEntitiesCollectionSparse dataYou want mix sequence (ids not recycled) and HashMap together.
TecCollectionDense dataYou want to use a vec to store data, but need constant entity removal. Tec reclaims the spaces for you as you insert more new items.

Structs

  • Stands for Entity Id generator (ids are redeemable). Basically a counter with a B-tree based free “set” (list).
  • This is a lazily memory-compact version of SparseEntities. Use cases are the same but there are different tradeoffs.
  • An abstracted monotonically increasing counter structure. Once you claim an id you can’t go back.
  • This is a sandwich of HashMap and Sequence.
  • Short for tombstone-based vector. Inspired by generational-arena, but without the generation stuff.

Traits

  • Trait for casting between an unsigned integer to a usize, and vice versa. Note: to() would panic if the value is greater or equal to the type’s max.
  • Trait for projecting the inner value of the Id’s tuple, i.e. returning u32 for Id(u32).
  • A trait that describes the max value of an unsigned integer. This trait is used to detect overflow. Also, it’s used like a NULL terminator for the free list in [Tec].
  • Predecessor trait for numbers.
  • Successor trait for numbers.

Derive Macros

  • Derives all traits introduced by the stable-id-traits crate. The struct should be a tuple which contains an unsigned numeric primitive type.