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.
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,
reserveandshrink_to_fitleave it in place. Onlysortand 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_fitfrees 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: aftersort, an id names whatever element moved into its slot.
Complexity
| Operation | Cost |
|---|---|
insert, remove | amortized O(1) |
get, contains, occupant | O(1) |
| iteration | O(len) on full pages; skips empty pages, scans free slots in partial pages |
retain, clear, drain, extract_if | O(pages + len) plus the scan |
reserve, shrink_to_fit | O(pages) |
id_of | O(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
| Rust | Python |
|---|---|
insert(v) -> Id | insert(v) -> int, insert_many(values) -> ndarray[uint64] |
get(id), get_mut(id), indexing | h[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, reserve | same names |
h.keys() and h.ids() each return a new uint64 array of live ids in slot
order.
API: Hive.