pub struct Eids<IndexT>where
IndexT: Ord,{ /* private fields */ }
Expand description
Stands for Entity Id generator (ids are redeemable). Basically a counter with a B-tree based free “set” (list).
Use case
- you want to recycle ids due to frequent entity removal
- you want to use custom data structure but need id management
- ids start from zero
Example
use stable_id::Eids;
let mut entities: Eids<u8> = Default::default();
let id = entities.claim();
entities.unclaim(id);
See Self::coalesce()
if you want to pack ids together, like when you’re trying to tighten up an array and
saving it into a database/save file (i.e. when game players are saving their progress).
Implementations§
source§impl<IndexT> Eids<IndexT>where
IndexT: Successor + Predecessor + Clone + Copy + Ord + Maximum,
impl<IndexT> Eids<IndexT>where IndexT: Successor + Predecessor + Clone + Copy + Ord + Maximum,
pub fn claim(&mut self) -> IndexT
pub fn unclaim(&mut self, val: IndexT)
sourcepub fn coalesce<F>(&mut self, f: F)where
F: FnMut(IndexT, IndexT),
pub fn coalesce<F>(&mut self, f: F)where F: FnMut(IndexT, IndexT),
Pack up recycled ids from the freed list while you deal with the change through f(old_id, new_id)
.
use stable_id::Eids;
let mut entities: Eids<u8> = Default::default();
(0..255).for_each(|i| {
assert_eq!(entities.claim(), i);
});
entities.unclaim(27);
entities.unclaim(15);
// free up 254 to 251, so that coalescing would be 15 & 27 to takeover 249, 250
entities.unclaim(254);
entities.unclaim(252);
entities.unclaim(251);
entities.unclaim(253);
let mut records_old = Vec::new();
let mut records_new = Vec::new();
entities.coalesce(|old_id, new_id| {
records_old.push(old_id);
records_new.push(new_id);
// update all data that reference the old_id and replace them with new_id
});
assert_eq!(records_old, [250,249]); // reclaiming from the last-issued
assert_eq!(records_new, [27,15]); // note: larger ids come first