Keyboard shortcuts

Press ← or → to navigate between chapters

Press S or / to search in the book

Press ? to show this help

Press Esc to hide this help

Ids and Side Tables

Keys and Slots

Every keyed collection stores at most one key per slot, and Key::index names the slot. For integers the slot is the integer. For generational ids (an index plus a generation counter) the slot is the index part, so all generations of an id share one slot. A lookup with a generational id matches only the generation stored in that collection.

What happens when an insert meets a slot held by another generation is documented per method: insert evicts, replace evicts and returns, try_insert refuses (see Sparse Map).

IdAllocator

IdAllocator hands out Ids and recycles freed ones without storing values. Freed indices are reused last freed first, with the next generation. index_bound() is at most the peak number of live ids plus the retired indices, which keeps the paged indices of the maps compact.

OperationCost
alloc, freeamortized O(1)
is_alive, occupantO(1)
iter, retain, clearO(index_bound)

Each index issues at most MAX_GENERATION (231) ids, then retires. The stale-id guarantee has the same scope as for the hive: one allocation history.

Side Tables

Use the same id as a key in separate maps when each entity has several associated values. The allocator and each map manage their own entries.

Freeing id (0, 1) and allocating again produces id (0, 2). The score map still holds score 10 for (0, 1), so looking up (0, 2) misses.
The allocator increments the generation when it reuses a slot. Remove the old entry from each side table explicitly, or replace it when inserting the new generation.

Example

from paged_collections import IdAllocator, IdMap, id_generation, id_index

ids = IdAllocator()
a, b = ids.alloc(), ids.alloc()
scores = IdMap([a, b], [10, 20])
print("freed =", ids.free(a))
c = ids.alloc()
print("reused slot =", (id_index(c), id_generation(c)))
# The side table is independent of the allocator; replace its old generation.
scores[c] = 30
print("stale alive =", ids.is_alive(a))
print("stale side =", scores.get(a))
print("scores =", scores.values())
print("live ids =", len(ids))
use paged_collections::id_alloc::{Id, IdAllocator};
use paged_collections::sparse_map::PagedSparseMap;

fn main() {
    let mut ids = IdAllocator::new();
    let (a, b) = (ids.alloc(), ids.alloc());
    let mut scores: PagedSparseMap<Id, i32> = PagedSparseMap::new();
    scores.insert(a, 10);
    scores.insert(b, 20);
    println!("freed = {}", ids.free(a));
    let c = ids.alloc();
    println!("reused slot = {:?}", (c.index(), c.generation().get()));
    // The side table is independent of the allocator: writing the new generation evicts the stale entry.
    scores.insert(c, 30);
    println!("stale alive = {}", ids.is_alive(a));
    println!("stale side = {:?}", scores.get(a));
    println!("scores = {:?}", scores.values().collect::<Vec<_>>());
    println!("live ids = {}", ids.len());
}

Python output:

freed = True
reused slot = (0, 2)
stale alive = False
stale side = None
scores = [30, 20]
live ids = 2

The Rust example prints the same lines.

Custom Id Types

Implement Key (and DirectKey for direct maps) for your own id:

#![allow(unused)]
fn main() {
use paged_collections::key::Key;

/// Low 24 bits: index; high 8 bits: generation.
#[derive(Clone, Copy, PartialEq, Eq, Debug)]
struct Entity(u32);

impl Key for Entity {
    fn index(self) -> usize {
        (self.0 & 0x00ff_ffff) as usize
    }
}
}

DirectKey adds type Tag (the bits the index does not give, here the generation), tag(self) and from_parts(index, tag).

Python Ids

Python ids are integers generation << 32 | index.

FunctionResult
id_index(id), id_generation(id)the parts
make_id(index, generation)a packed id (generations 1 to 2**32 − 1)
id_indices(ids)vectorized id_index, uint32 array

IdMap and its typed variants (IdMapF64, …, id_map(dtype)) are sparse maps keyed by these ids. They accept ids from IdAllocator and Hive. Their ordered queries use slot indices and return packed ids as keys.

RustPython
IdAllocator::allocalloc(), alloc_many(n)
freefree(id), free_many(ids)
is_aliveis_alive(id), id in a, is_alive_many(ids)
iteriter(a), ids()
index_bound, free_len, retired_lenproperties of the same names

API: IdAllocator, Key.