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

Hive

Hive<T, PAGE = 1024> is an unordered container with stable addresses, reusable slots and generational ids. Inserting returns an Id: a u32 slot index plus a generation. Removing an element frees its slot; the next element there gets the next generation, so a stale id of a removed element never matches a live one. Comparable in purpose to C++26 std::hive.

Python: Hive; ids are integers packed as generation << 32 | index.

Removing A vacates slot 5. Inserting B reuses slot 5 with generation 2.
The original id for slot 5 and generation 1 is stale. Looking it up misses even after B occupies the same slot.

Example

from paged_collections import Hive, id_generation, id_index

hive = Hive()
a = hive.insert(30)
b = hive.insert(10)
print("removed =", hive.pop(a))
c = hive.insert(20)
print("reused slot =", (id_index(c), id_generation(c)))
print("stale =", hive.get(a))
ordered = hive.sorted_ids()
print("sorted indices =", [id_index(key) for key in ordered])
print("sorted values =", [hive[key] for key in ordered])
print("slots before sort =", hive.values())
# Sorting moves values between slots; ids continue to name slots.
hive.sort()
print("slots after sort =", hive.values())
print("reused id now names =", hive[c])
use paged_collections::hive::Hive;

fn main() {
    let mut hive: Hive<i32> = Hive::new();
    let a = hive.insert(30);
    let b = hive.insert(10);
    println!("removed = {}", hive.remove(a).unwrap());
    let c = hive.insert(20);
    println!("reused slot = {:?}", (c.index(), c.generation().get()));
    println!("stale = {:?}", hive.get(a));
    println!("id_of index = {}", hive.id_of(&hive[b]).unwrap().index());
    let ordered = hive.sorted_ids();
    let indices: Vec<_> = ordered.iter().map(|id| id.index()).collect();
    println!("sorted indices = {indices:?}");
    let sorted_values: Vec<_> = ordered.iter().map(|&id| hive[id]).collect();
    println!("sorted values = {sorted_values:?}");
    println!(
        "slots before sort = {:?}",
        hive.values().collect::<Vec<_>>()
    );
    // Sorting moves values between slots; ids continue to name slots.
    hive.sort();
    println!("slots after sort = {:?}", hive.values().collect::<Vec<_>>());
    println!("reused id now names = {}", hive[c]);
}

Python output:

removed = 30
reused slot = (0, 2)
stale = None
sorted indices = [1, 0]
sorted values = [10, 20]
slots before sort = [20, 10]
slots after sort = [10, 20]
reused id now names = 10

The Rust example also prints id_of index = 1, the id recovered from the address of hive[b].

Guarantees

  • Stable addresses. An element does not move while it is in the hive: inserts, removals of other elements, reserve and shrink_to_fit leave it in place. Only sort and its variants move elements.
  • Slot reuse. Inserts fill one page with room at a time; within a page the last freed slot is reused first. A page with room is used before a new page is allocated, so memory follows the peak element count, not the number of inserts.
  • Iteration is in slot order (page by page), not insertion order.
  • Memory return. shrink_to_fit frees every empty page except pages holding a retired slot, scanning the slots of each empty page to check. A freed page keeps a record of its highest generation, so earlier ids stay dead when the page is reused.

Finding and Sorting

  • id_of(&element) returns the id of an element from its address, in O(pages).
  • sorted_ids() (and _by, _by_key) returns live ids in element order and moves nothing.
  • sort() (and _by, _by_key, _by_cached_key, sort_unstable*) reorders elements across the occupied slots, so iteration yields them sorted. Ids name slots: after sort, an id names whatever element moved into its slot.

Complexity

OperationCost
insert, removeamortized O(1)
get, contains, occupantO(1)
iterationO(len) on full pages; skips empty pages, scans free slots in partial pages
retain, clear, drain, extract_ifO(pages + len) plus the scan
reserve, shrink_to_fitO(pages)
id_ofO(pages)

Limits and Stale Ids

Slot indices are below MAX_INDICES (u32::MAX). Each slot issues at most MAX_GENERATION (231) ids; after that the slot is retired and never reused, so generations never wrap. A page with a retired slot is never freed. is_exhausted reports when no slot can be issued.

The stale-id guarantee holds within one history of one hive. Ids carry no hive identity: another hive or a clone accepts them, and restoring an older state (an older clone, an older serialized snapshot, an older pickle) revives ids removed since.

Side Tables

Id implements Key and DirectKey, so PagedSparseMap<Id, V> and PagedDirectMap<Id, V> hold extra data per element. In Python use IdMap. See how side tables handle recycled ids.

Rust and Python

RustPython
insert(v) -> Idinsert(v) -> int, insert_many(values) -> ndarray[uint64]
get(id), get_mut(id), indexingh[id], get(id, default), get_many(ids)
remove(id)pop(id[, default]), del h[id], discard(id), discard_many(ids)
contains(id)id in h, contains_many(ids)
ids(), values(), iter()ids() (also keys()), values(), items(), iter(h) (ids)
id_of(&v)
sorted_ids*sorted_ids(key=, reverse=)
sort*sort(key=, reverse=)
retain, shrink_to_fit, reservesame names

h.keys() and h.ids() each return a new uint64 array of live ids in slot order.

API: Hive.