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

Overview

paged-collections provides sparse sets, maps, a priority queue and stable-address containers whose memory is split into fixed-size pages. The core is a no_std Rust crate (alloc only). The Python package wraps it with PyO3 and exchanges batches with NumPy.

A paged index can leave some pages unallocated. Paged storage can add a page while existing elements stay at their addresses.

Documentation

Two Uses of Paging

  • Paged index. A table indexed by key is split into pages allocated on first use. A write to an isolated key allocates only the page it touches. With the default Flat directory, the pointer table still grows up to the highest page number used. Sparse sets, sparse maps, direct maps and priority queues use a paged index.
  • Paged storage. Growth adds pages while existing elements stay at their addresses. The paged vector, deque and hive use paged storage.

See Paging Model for page sizes, directories and memory behaviour.

Example

A Hive stores elements at stable addresses and returns generational ids. Those ids can index the other maps directly to create side tables:

from paged_collections import Hive, IdMap, id_generation, id_index

hive = Hive()
a = hive.insert("a")
b = hive.insert("b")
score = IdMap([a, b], [10, 20])
hive.pop(a)
c = hive.insert("c")
print("reused slot =", (id_index(c), id_generation(c)))
print("new side entry =", score.get(c))
# Writing the new generation evicts the stale entry from the side table.
score[c] = 30
print("stale hive =", hive.get(a))
print("stale side =", score.get(a))
print("side values =", score.values())
use paged_collections::direct_map::PagedDirectMap;
use paged_collections::hive::Hive;
use paged_collections::id_alloc::Id;

fn main() {
    let mut hive: Hive<&str> = Hive::new();
    let a = hive.insert("a");
    let b = hive.insert("b");
    let mut score: PagedDirectMap<Id, u32> = PagedDirectMap::new();
    score.insert(a, 10);
    score.insert(b, 20);
    hive.remove(a);
    let c = hive.insert("c");
    println!("reused slot = {:?}", (c.index(), c.generation().get()));
    println!("new side entry = {:?}", score.get(c));
    // Writing the new generation evicts the stale entry from the side table.
    score.insert(c, 30);
    println!("stale hive = {:?}", hive.get(a));
    println!("stale side = {:?}", score.get(a));
    let values: Vec<_> = score.range(a..=b).map(|(_, &v)| v).collect();
    println!("range = {values:?}");
}

Python output:

reused slot = (0, 2)
new side entry = None
stale hive = None
stale side = None
side values = [30, 20]

The Rust example queries the direct map by key range and prints range = [30, 20] in place of the last line.

Containers

RustPythonPagingPurpose
PagedSparseSet<K>SparseSetindexInteger set: O(1) insert, remove, contains and clear; dense iteration
PagedSparseMap<K, V>SparseMap, SparseMapF64, …indexSparse set with a dense value array
PagedDirectMap<K, V>DirectMap, DirectMapF64, …indexValues stored in place; key order and range queries
PagedPriorityQueue<K, P>PriorityQueue, PriorityQueueF64indexIndexed heap with priority changes and removal by key
ConcurrentPriorityQueue<K, P>ConcurrentPriorityQueue, ConcurrentPriorityQueueF64indexSharded max-priority queue; relaxed pop, exact pop_exact
PagedVec<T>PagedList, PagedListF64, …storageGrowable vector with stable addresses
PagedDeque<T>PagedDequestorageDouble-ended queue with stable addresses
ConcurrentQueue<T>ConcurrentQueuestorageShared FIFO queue; waits at page boundaries
Hive<T>HivestorageUnordered slots with generational ids
IdAllocatorIdAllocator, IdMapnoneGenerational id allocation for use as keys

Thread-safe variants are listed under Concurrent Containers. The full Rust API is on docs.rs; the Python API is typed in _core.pyi.

Installation

Rust

cargo add paged-collections

Minimum supported Rust version: 1.85 (edition 2024).

FeatureDefaultEffect
stdyesstd-only conveniences. Without it the crate is no_std and needs only alloc.
serdenoSerialize / Deserialize for the collections.
concurrentnoThe concurrent module. Needs pointer-sized and 64-bit atomics on a 32- or 64-bit target; works without std (locks then spin).
[dependencies]
paged-collections = { version = "0.2", default-features = false, features = ["concurrent"] }

Hive, IdAllocator and the concurrent module exist only on 32- and 64-bit targets, because slot indices are u32 and must convert to usize without loss.

Python

pip install paged-collections

Requires Python 3.10 or newer and NumPy 1.24 or newer. Wheels:

InterpreterWheel tag
CPython 3.10+ with the GILabi3
Free-threaded CPython 3.14tversion-specific
Free-threaded CPython 3.15t and newerabi3t

Free-threaded 3.13t is not supported. See Python Threads.

Page Sizes

Python classes take a page_size= keyword. The values a build accepts are fixed at compile time, because each page size is a separate monomorphized Rust type:

import paged_collections as pc

pc.PAGE_SIZES         # (256, 512, 1024, 2048, 4096)
pc.DEFAULT_PAGE_SIZE  # 1024
m = pc.SparseMap(page_size=4096)

BitSet uses the same compiled sizes, measured in 64-bit words. It defaults to DEFAULT_BIT_PAGE_SIZE (512, or DEFAULT_PAGE_SIZE when a custom build leaves 512 out). To build from source with other sizes, set the variables before building:

PAGED_COLLECTIONS_PAGE_SIZES=64,1024,16384 \
PAGED_COLLECTIONS_DEFAULT_PAGE_SIZE=1024 \
pip install --no-binary paged-collections paged-collections

Each extra size adds code for every class, so the extension grows with the list.

From Source

git clone https://github.com/inspiros/paged-collections
cd paged-collections
cargo test                # Rust
uv sync && uv run pytest  # Python (builds the extension with maturin)

cargo build --workspace fails to link the Python crate unless the Python development library is installed; build it through maturin (uv sync or maturin develop). cargo check and cargo clippy work either way.

Paging Model

Paged Index

Keyed collections map each key to a slot index (the integer itself, or the index part of a generational id; see Ids and Side Tables). The slot index splits into a page number and an offset:

page   = index / PAGE
offset = index % PAGE

A directory maps page numbers to pages. A page is a fixed array of PAGE slots, allocated on the first write into it. Lookups into an unallocated page return “absent” without allocating.

The Flat directory has entries for pages 0, 1 and 2. Entries 0 and 2 point to allocated pages, while entry 1 is empty.
With four slots per page, key 9 selects page 2 at offset 1. In this sparse index, that slot stores dense position 3.

What a slot holds depends on the collection:

CollectionSlot contentsSlot size
Sparse set, sparse map, priority queueposition in the dense array (Option<NonZeroU32>)4 bytes
Direct mapthe value and the key’s tag (Option<(K::Tag, V)>)size_of::<Option<(K::Tag, V)>>(); 16 bytes for u32 -> u64

With the default PAGE = 1024, a sparse-set page is 4 KiB and a u32 -> u64 direct-map page is 16 KiB.

Directories

The directory is the last type parameter, for example PagedDirectMap<usize, u32, 1024, page::Radix>.

MarkerStructurePage lookupDirectory memory
page::Flat (default)Vec<Option<Box<[T; PAGE]>>>O(1), one indirectionone pointer per page up to the highest page used
page::Radixflat window for low page numbers, then a path-compressed 64-ary trieO(1) in the window, else at most ceil(usize bits / 6) branchesproportional to the peak allocated page count
page::TreeBTreeMap<usize, Box<[T; PAGE]>>O(log pages)proportional to allocated pages
  • Flat suits keys below a few billion, such as u32 keys. Its directory holds at most ceil(2^32 / PAGE) pointers: 32 MiB at the default page size, plus up to as much again in Vec growth capacity until shrink_to_fit.
  • Radix suits page numbers spread over the 64-bit range, where a flat directory cannot be allocated. Its flat window covers page numbers below about 8 times the allocated page count, so dense low keys cost the same as Flat. The window does not shrink below its highest live page.
  • Tree is a standard B-tree; use it when measurements favour it for your key pattern.

Python classes always use Flat; their keys are below 2**32.

Page Size

PAGE is a const generic, default 1024. Larger pages mean fewer directory entries and fewer allocations for dense keys, and more memory per isolated key. Smaller pages waste less memory on sparse or clustered keys. The page-size sweep in Benchmarks shows the trade for each key pattern. In Python, pass page_size= (see Installation).

Memory Behaviour

  • Each newly touched page costs a full page. Keys spread uniformly over a wide range allocate and zero one page per key. This is the worst case for every paged-index collection; use a hash map for it.
  • Clustered keys fill pages partially. Runs of 64 keys fill about 6% of a 1024-slot page.
  • Pages are not freed when they empty. clear keeps pages for reuse. shrink_to_fit frees empty pages (sparse set and map: all pages, only when empty), reset frees all pages. Removing a random 90% of keys frees almost nothing, because nearly every page stays partly occupied.
  • No automatic compaction. Compaction would move elements and break the address and id guarantees.

Paged Storage

PagedVec, PagedDeque and Hive keep elements in pages of PAGE elements. A page is allocated once and never reallocated. When the container needs more slots, it adds a page and may grow the directory of page pointers.

A and B move when the Vec buffer moves to make room for C. In PagedVec, A and B stay on the first page and C goes on a second page.
A full Vec can move its buffer when it grows. A PagedVec preserves the addresses of existing elements as it adds pages.
  • Pushing preserves the addresses of existing elements, including when a front push changes their logical indices in a deque. Edits such as inserting into the middle of a sequence can move elements.
  • At a page boundary, a push may allocate a page and copy the directory of page pointers.
  • The elements are not one contiguous slice. Slices are available per page (pages() in Rust, page_view() for typed Python lists).

Example

from paged_collections import DirectMap

page_size = 4096
keys = [7, 5000, 4_000_000_000]
values = DirectMap(page_size=page_size)
for key in keys:
    values[key] = key + 1
print("page size =", values.page_size)
print("keys =", list(values))
print("len =", len(values))
print("allocated pages =", values.allocated_pages)
use paged_collections::direct_map::PagedDirectMap;
use paged_collections::page::Radix;

fn main() {
    const PAGE: usize = 4096;
    let keys = [7, 5000, 4_000_000_000usize];
    let mut values: PagedDirectMap<usize, usize, PAGE, Radix> = PagedDirectMap::new();
    for key in keys {
        values.insert(key, key + 1);
    }
    println!("page size = {PAGE}");
    println!("keys = {:?}", values.keys().collect::<Vec<_>>());
    println!("len = {}", values.len());
    println!("allocated pages = {}", values.allocated_pages());
}

Python output:

page size = 4096
keys = [7, 5000, 4000000000]
len = 3
allocated pages = 3

The Rust example prints the same lines.

Choosing a Container

Measured ratios for several containers are in Benchmarks. They come from one machine and serve as a reference.

NeedUseInstead ofAvoid when
Membership in dense integer ranges, ordered queries or range updatesPagedBitSetPagedSparseSetkeys are thinly scattered or you need a contiguous key array
Integer keys in runs or ranges; fast iteration and missesPagedSparseSet, PagedSparseMapHashSet, HashMap, BTreeMapkeys are spread uniformly over a wide range
Key-ordered iteration, range and nearest-key queries over dense rangesPagedDirectMapBTreeMapkeys are sparse inside their pages (iteration scans whole pages)
Entries as contiguous slices or arraysPagedSparseMap (key_slice, value_slice; Python views)HashMap
Priority changes or removal by keyPagedPriorityQueuepriority-queue cratepriorities never change: BinaryHeap is faster
Shared FIFO queueConcurrentQueue (Python ConcurrentQueue)
Shared indexed priority queueConcurrentPriorityQueue (Python ConcurrentPriorityQueue, ConcurrentPriorityQueueF64); relaxed pop, exact pop_exact
References that survive growthPagedVec, PagedDequeVec, VecDequerandom access dominates and addresses need not be stable
Handles that detect removal (stale ids)Hive, or IdAllocator with a paged mapslotmapraw lookup speed matters more than stable addresses
Shared insertion from many threadsconcurrent containersa Mutex around a plain containera single thread mutates: the plain types are faster

Sparse Map or Direct Map

For key 9 the sparse map's page slot points to dense position 1. The direct map's page slot holds the value 90 itself.
With the same keys and values, a sparse map iterates the dense arrays. A direct map visits slots in ascending key order for integer keys.
PagedSparseMapPagedDirectMap
Where values livedense array, parallel to the keysin the page slot
Lookuppage lookup, slot read, dense readpage lookup, slot read
Iterationdense array only, insertion order (changed by swap removal)every allocated slot, key order
clearO(1) for the indexscans allocated pages
Memory per allocated pagePAGE × 4 bytesPAGE × slot size
Range queries in Rustrange, next_occupant, prev_occupantrange, next_occupant, prev_occupant

Prefer the direct map when keys fill a few dense ranges, when you want iteration in key order, or when lookups dominate. Prefer the sparse map when keys are scattered thinly or when you need contiguous slices.

Hive or IdAllocator with a Map

Hive<T> owns the elements. A removed element’s id goes stale. An IdAllocator owns only the ids. Values live in one or more paged maps keyed by Id. Use the allocator when an entity has several components stored in separate tables, and the hive when one value per id is enough.

Directory

KeysDirectory
Below a few billion (u32)Flat (default)
Spread over 64 bitsRadix
Measured to favour a B-treeTree

See Paging Model.

Bit Set

PagedBitSet<K, PAGE = 512, D = Flat> (Python BitSet) stores membership as one bit per slot in each allocated page. Pick it for integer keys that cluster in dense ranges, especially for ordered traversal, range updates or set algebra. A sparse set visits its dense key array in O(len), which can be faster when the occupied pages hold few keys. It also supports generational keys and contiguous access to the keys.

Pages and Costs

PAGE in Rust and page_size in Python count 64-bit words. The default of 512 words uses 4 KiB per allocated page and covers 32,768 keys. Pages are allocated as keys are inserted. Clearing the set or removing keys keeps the pages for reuse. In Rust, shrink_to_fit() frees empty pages and reset() frees all pages.

In a bit set with two 64-bit words per page, key 138 selects page 1, word 0, and bit 10. That bit is set.
Each word stores membership for 64 consecutive keys. In this example, page 1 starts at key 128, so key 138 is 10 bits into its first word.

The Python binding uses the Flat directory and accepts the sizes in PAGE_SIZES. Each directory slot holds one page pointer up to the highest allocated page. At the default size, the full Python key domain needs at most 131,072 directory slots (1 MiB of pointers on a 64-bit platform). Rust can use a different directory for keys spread over a wider domain.

OperationCost with Flat
Membership, insert, removeO(1) per key, plus allocation on first touch
LengthO(1)
Iteration, nearest-key queriesScan directory slots and words in the visited span, then visit set bits
Range addVisit words in the range and allocate newly touched pages
Range discard, countScan directory slots and words in allocated pages that overlap the range
ClearZero the words in all allocated pages
Same-size set algebraScan relevant pages word by word

Rust

Integer key types implement DirectKey<Tag = ()>. Ranges take Rust RangeBounds<K> and refer to the keys’ slot indices. Use explicit upper bounds for narrow integer key types when adding a range. Bit sets with the same PAGE support algebra across directory layouts.

#![allow(unused)]
fn main() {
use paged_collections::bit_set::PagedBitSet;

let mut bits: PagedBitSet<u32> = PagedBitSet::new();
assert_eq!(bits.insert_range(62..67), 5);
assert_eq!(bits.remove_range(64..66), 2);
assert_eq!(bits.range(63..).collect::<Vec<_>>(), [63, 66]);
assert_eq!(bits.next_occupant(64), Some(66));
assert_eq!(bits.pop_first(), Some(62));
}

Python

from paged_collections import BitSet

bits = BitSet([62, 65])
print(bits.add_range(63, 67))
print(list(bits.range(63, 67)))
print(bits.next_occupant(64))
print(bits.to_mask(61, 68).tolist())
print(BitSet.from_mask([True, False, True], offset=62).to_numpy().tolist())
3
[63, 64, 65, 66]
64
[False, True, True, True, True, True, False]
[62, 64]
  • Keys are integers in 0 <= key < 2**32. Membership and discard treat invalid keys as absent. add raises for invalid keys and remove raises KeyError for absent keys.
  • BitSet(keys=None, *, page_size=DEFAULT_BIT_PAGE_SIZE) accepts an initial one-dimensional integer array or sequence.
  • toggle(key) flips membership and returns whether the key is now present. It validates keys the same way as add.
  • first() and last() return the smallest and largest keys. pop_first() and pop_last() remove and return the respective keys. pop() is the same as pop_first(). These methods raise KeyError on an empty set. next_occupant(index) and prev_occupant(index) return the nearest key at or beyond the given key in the respective direction, or None if there is no match. The index must be a valid key.
  • add_range and discard_range return the number of keys changed. count_range counts keys and range iterates over them. Both endpoints of [start, stop) must be integers in 0 <= endpoint <= 2**32. With start >= stop the interval is empty.
  • Iteration is ascending, or descending with reversed(bits). Iterators raise RuntimeError if membership changes during iteration.
  • union, intersection, difference, symmetric_difference, their in-place methods (update for union) and the predicates accept iterable operands. Operators | & - ^, their in-place forms and comparisons take BitSet operands. Two bit sets with the same page size use word-wise algebra. With different sizes, algebra visits keys individually. New algebra results are base BitSet instances using the receiver’s page size. Pickling and copying preserve the page size.
  • add_many and discard_many return the number of keys changed. contains_many returns a boolean NumPy array. to_numpy() returns a new ascending uint32 array.
  • from_mask(mask, offset=0, *, page_size=DEFAULT_BIT_PAGE_SIZE) reads a one-dimensional boolean array or sequence. A true value at position i sets offset + i. The whole mask must fit in the key domain. The page size counts 64-bit words, as in the constructor.
  • to_mask(start, stop) returns a new boolean array with one element per key in the interval, using O(max(0, stop − start)) memory.

API PagedBitSet.

Sparse Set

PagedSparseSet<K, PAGE = 1024, D = Flat> (Python: SparseSet) stores keys in a contiguous dense array and finds them through a paged sparse index from slot index to dense position.

Example

from paged_collections import SparseSet

keys = SparseSet([3, 7, 11])
keys.add(19)
print("inserted =", list(keys))
keys.remove(7)
print("contains 7 =", 7 in keys)
print("dense =", list(keys))
other = SparseSet([11, 23])
print("union =", sorted(keys | other))
print("intersection =", sorted(keys & other))
print("difference =", sorted(keys - other))
keys.clear()
print("cleared len =", len(keys))
use paged_collections::sparse_set::PagedSparseSet;

fn main() {
    let mut keys: PagedSparseSet<usize> = PagedSparseSet::new();
    keys.extend([3, 7, 11]);
    keys.insert(19);
    println!("inserted = {:?}", keys.as_slice());
    keys.remove(7);
    println!("contains 7 = {}", keys.contains(7));
    println!("dense = {:?}", keys.as_slice());
    keys.clear();
    println!("cleared len = {}", keys.len());
}

Python output:

inserted = [3, 7, 11, 19]
contains 7 = False
dense = [3, 19, 11]
union = [3, 11, 19, 23]
intersection = [11]
difference = [3, 19]
cleared len = 0

The Rust example prints the same lines without the set algebra.

Complexity

OperationCost
insert, remove, contains, get, takeO(1) with Flat; O(depth) with Radix; O(log pages) with Tree
clearO(1): pages are kept, stale slots are ignored
iteration, as_slicedense array only, O(len)
sortO(n log n) comparisons, then one index write per key

Lookups follow Briggs and Torczon. A lookup accepts a slot only if it points inside the dense array to a key with the same slot index. This check lets clear leave the index pages untouched.

Order

Iteration follows the dense array in insertion order until a removal. remove swaps the last key into the removed position (O(1)), changing the order. sort and its variants reorder the dense array. Sorted order then lasts until the next removal or insertion out of order.

Removing 9 from the dense keys 11, 9, 2 moves the last key, 2, into the middle slot.
Swap removal updates the sparse index for the moved key. Iteration now yields 11, then 2.

Generational Keys

The set holds at most one key per slot index. With generational keys, insert refuses a key whose slot is held by another generation and returns false; replace evicts the other generation; occupant(index) returns the key holding a slot. get(key) borrows the stored key and take(key) removes and returns it. Both require an exact generation match. See Ids and Side Tables.

Rust and Python

RustPythonNotes
insert(k) -> booladd(k), add_many(keys) -> int
remove(k) -> booldiscard(k), remove(k) (raises KeyError), discard_many(keys)swap removal
contains(k)k in s, contains_many(keys) -> ndarray[bool]
get(k)borrows the stored key
take(k)returns the stored key by swap removal
as_slice()to_array() (copy), view() (zero-copy, read-only)
iter()iter(s)dense order
first(), last()first(), last()smallest and largest keys
pop_first(), pop_last()pop_first(), pop_last()remove and return the smallest and largest keys, respectively
next_occupant, prev_occupantnext_occupant(index), prev_occupant(index)nearest key at or after, or at or before, index
sort*sort()
position(k)dense position
clear() / reset()clear()reset frees pages
allocated_pages()allocated_pages
union, intersection, difference, symmetric_difference, the *_update forms, | & - ^ and in-place operators, issubset, issuperset, isdisjoint, < <= > >=Python set protocol

Python keys are integers in 0 <= key < 2**32. Batch lookups (contains_many, discard_many) treat out-of-range integers as absent; add and add_many raise for them.

Ordered queries use the sparse index, and next_occupant and prev_occupant require a valid key and return None when no key matches. first(), last(), pop_first() and pop_last() raise KeyError on an empty set. Ordered pops use swap removal and raise BufferError while a view() is alive.

Set Algebra

  • Operators take SparseSet operands; methods accept any iterable of keys.
  • Results use the receiver’s page size, keep the receiver’s surviving keys in order, then append new keys in operand iteration order.
  • difference_update and -= use swap removal; other in-place operations keep the receiver’s order.
  • In-place operations raise BufferError while a view() is alive.

API: PagedSparseSet.

Sparse Map

PagedSparseMap<K, V, PAGE = 1024, D = Flat> is a sparse set of keys plus a dense value array kept parallel to the dense keys. The value at position i belongs to the key at position i. Keys and values can be iterated or borrowed as slices without touching the index.

See where sparse and direct maps store their values.

Python: SparseMap holds arbitrary objects. SparseMapF64, SparseMapF32, SparseMapI64, SparseMapI32, SparseMapU64, SparseMapU32 and SparseMapBool store values unboxed; sparse_map(dtype) returns an instance of the class for a NumPy dtype.

Example

from paged_collections import SparseMap, sparse_map

values = sparse_map("float64")
values[7] = 1.5
values[2] = 2.5
values[9] = 3.5
print("get 7 =", values.get(7))
print("removed =", values.pop(2))
print("keys =", list(values))
print("values =", values.values().tolist())
objects = SparseMap()
objects[7] = (4, 5)
print("object =", objects[7])
use paged_collections::sparse_map::PagedSparseMap;

fn main() {
    let mut values: PagedSparseMap<usize, f64> = PagedSparseMap::new();
    values.insert(7, 1.5);
    values.insert(2, 2.5);
    values.insert(9, 3.5);
    println!("get 7 = {}", values.get(7).unwrap());
    println!("removed = {}", values.remove(2).unwrap());
    println!("keys = {:?}", values.keys().collect::<Vec<_>>());
    println!("values = {:?}", values.values().collect::<Vec<_>>());
    let mut objects: PagedSparseMap<usize, (i32, i32)> = PagedSparseMap::new();
    objects.insert(7, (4, 5));
    println!("object = {:?}", objects.get(7).unwrap());
}

Python output:

get 7 = 1.5
removed = 2.5
keys = [7, 9]
values = [1.5, 3.5]
object = (4, 5)

The Rust example prints the same lines.

Complexity

OperationCost
get, removeO(1) with Flat (see directories)
insertas get, amortized over dense-array growth; the first key in a page allocates the page
clearO(1) for the index, plus dropping the values
iteration, key_slice, value_slicedense arrays only
sortO(n log n) comparisons, O(n) swaps, one index write per entry
binary_search_key, binary_search_by, partition_pointO(log n) on entries kept sorted by the caller

Removal swaps the last entry into the removed position, as in the set.

Generational Keys

With plain integer keys the map behaves like HashMap. With generational keys the methods differ when the slot is held by a different key:

MethodSlot held by another generation
insert, get_or_insert_withevicts it
entryreturns Vacant. Inserting through it evicts the other generation in place
replaceevicts it and returns the evicted entry
try_insertrefuses

insert evicts so that get(key) returns the new value afterwards, as with HashMap.

In Rust, entry(key) gives mutable access to an exact key or lets you insert it after a single slot lookup. For example, use *counts.entry(key).or_default() += 1 to update a counter.

Rust and Python

RustPython
insert(k, v)m[k] = v, set_many(keys, values), update(mapping)
get(k), get_mut(k)m[k], get(k, default), get_many(keys, default)
get_or_insert_withsetdefault(k, default)
entry(k)
remove(k)del m[k], pop(k[, default]), popitem(), discard_many(keys)
first_key_value(), last_key_value()first_item(), last_item()
pop_first(), pop_last()pop_first(), pop_last()
next_occupant, prev_occupantnext_occupant(index), prev_occupant(index)
range(a..b)items_range(a, b), keys_range(a, b), values_range(a, b)
contains_key(k)k in m, contains_many(keys)
key_slice()keys() (copy), keys_view() (zero-copy, read-only)
value_slice(), value_slice_mut()typed maps: values() (copy), values_view() (zero-copy; writeable except for SparseMapBool); SparseMap.values() returns a list
sort_keys, sort_by*sort_keys()
allocated_pages()allocated_pages

Python SparseMap, IdMap and their typed variants accept parallel keys and values, one mapping, or one iterable of (key, value) pairs. They validate all input before writing and keep the last value for duplicate keys.

Ordered queries follow the sparse index. first_item() and last_item() return the (key, value) pairs with the smallest and largest slot indices. pop_first() and pop_last() remove and return those pairs by swap removal. All four raise KeyError on an empty map, and ordered pops raise BufferError while a NumPy view is alive.

next_occupant(index) and prev_occupant(index) return the nearest pair at or after, or at or before, the given slot index. They return None when no entry matches. Both accept integers outside the slot domain. A negative index is before the first slot, and an index of 2**32 or higher is past the last slot. For IdMap and its typed variants, pass a slot index and receive a packed ID as the key in the returned pair.

items_range(start=None, stop=None), keys_range and values_range return copies in ascending slot order for the half-open interval [start, stop). None leaves a bound open and integer bounds are clamped to the slot domain. For IdMap, the bounds are slot indices and the returned keys are packed IDs.

Batch methods are described in NumPy Interop.

API: PagedSparseMap.

Direct Map

PagedDirectMap<K, V, PAGE = 1024, D = Flat> stores each entry in the slot its key names, in pages allocated on first use. There is no dense array: a lookup is one page lookup and one slot read, entries never move, and iteration visits entries in ascending slot-index order (key order for integers).

See where sparse and direct maps store their values.

Python: DirectMap (objects) and DirectMapF64, DirectMapF32, DirectMapI64, DirectMapI32, DirectMapU64, DirectMapU32, DirectMapBool; direct_map(dtype) creates an instance of the class for a dtype.

Example

from paged_collections import DirectMap

values = DirectMap([20, 3, 10], [200, 30, 100])
print("get 3 =", values.get(3))
print("default =", values.setdefault(7, 70))
print("existing =", values.setdefault(7, 999))
print("ordered =", values.items())
print("range =", values.items_range(3, 20))
print("removed =", values.pop(10))
print("keys =", list(values))
use paged_collections::direct_map::PagedDirectMap;

fn main() {
    let mut values: PagedDirectMap<usize, i32> = PagedDirectMap::new();
    for (key, value) in [(20, 200), (3, 30), (10, 100)] {
        values.insert(key, value);
    }
    println!("get 3 = {}", values.get(3).unwrap());
    println!("default = {}", values.entry(7).or_insert(70));
    println!("existing = {}", values.entry(7).or_insert(999));
    println!("ordered = {:?}", values.iter().collect::<Vec<_>>());
    println!("range = {:?}", values.range(3..20).collect::<Vec<_>>());
    println!("removed = {}", values.remove(10).unwrap());
    println!("keys = {:?}", values.keys().collect::<Vec<_>>());
}

Python output:

get 3 = 30
default = 70
existing = 70
ordered = [(3, 30), (7, 70), (10, 100), (20, 200)]
range = [(3, 30), (7, 70), (10, 100)]
removed = 100
keys = [3, 7, 20]

The Rust example prints the same lines, using the entry API in place of setdefault.

Complexity

OperationCost
get, insert, removeO(1) with Flat; the first key in a page allocates the page
iteration, clear, retainO(allocated pages × PAGE), plus with Flat O(directory length) to skip unallocated pages
range, next_occupant, prev_occupant, first_key_value, last_key_value, pop_first, pop_lasta seek to the first page (O(1) with Flat, O(depth) with Radix and Tree), then a scan of the allocated slots up to the entry; with Flat, unallocated directory entries in between are also skipped one by one
lenO(1)

Iteration and clear scan every allocated slot, occupied or not, and every allocated slot takes the space of an entry. Keys that fill their pages sparsely make both expensive; see Choosing a Container.

What a Slot Stores

A slot holds the value and the key’s DirectKey::Tag, the part of the key its slot index does not give. Integer keys have the tag (), so a slot of a u32 -> u64 map is 16 bytes and a slot of a u32 -> Box<T> map is 8 bytes (niche optimization). Iterators rebuild each key from slot index and tag and yield keys by value: (K, &V).

Ordered Queries

Entries are ordered by slot index, so the map answers ordered-map queries without a tree:

  • range(a..b), range_mut: entries between two keys.
  • first_key_value, last_key_value, pop_first, pop_last: the ends.
  • next_occupant(i), prev_occupant(i): the nearest entry at or after, or at or before, slot index i.

A generational key bounds a range by its index only: range(id..=id) yields whichever generation holds the slot.

Entry API

entry(k) returns Occupied only when the slot holds k itself. A vacant entry’s insert evicts another generation held in the slot. The usual combinators exist: or_insert, or_insert_with, or_insert_with_key, or_default, and_modify, insert_entry.

Generational Keys

As in the sparse map: insert and get_or_insert_with evict another generation, replace evicts and returns it, try_insert refuses. Keys must implement DirectKey (the Key slot index plus the tag); u8, u16, u32, u64, usize and Id implement it.

Memory

Pages are not freed when they empty. shrink_to_fit frees every page without entries and shrinks the directory; reset frees all pages.

Rust and Python

RustPython
insert(k, v)m[k] = v, set_many(keys, values), update(mapping)
get(k)m[k], get(k, default), get_many(keys, default)
get_or_insert_with, entrysetdefault(k, default)
remove(k)del m[k], pop(k[, default]), popitem(), discard_many(keys)
keys(), values(), iter()keys() (uint32 array), values(), items()
range(a..b)keys_range(a, b), values_range(a, b), items_range(a, b) (stop exclusive)
first_key_value, last_key_valuefirst_item(), last_item()
pop_first, pop_lastpop_first(), pop_last()
next_occupant, prev_occupantnext_occupant(i), prev_occupant(i)
shrink_to_fit, resetshrink_to_fit()

Python DirectMap and its typed variants accept parallel keys and values, one mapping, or one iterable of (key, value) pairs. They validate all input before writing and keep the last value for duplicate keys.

Python direct maps have no zero-copy views: values are in pages, not in one array.

API: PagedDirectMap.

Priority Queue

PagedPriorityQueue<K, P, PAGE = 1024, D = Flat> is an indexed max-heap: keys map to priorities, the greatest priority comes out first, and a key’s priority can be changed or the key removed in O(log n). Use core::cmp::Reverse for a min-queue. Keys and priorities live in parallel contiguous arrays in heap order (a four-way heap); a paged index finds a key’s heap position.

Python: PriorityQueue (int64 priorities) and PriorityQueueF64 (float64); min=True makes either a min-queue. Pushing a present key changes its priority.

In a four-way max-heap, key 7 has the highest priority, 80. The paged index locates key 9 at heap position 2.
pop takes the root of the heap. Updating key 9 starts at position 2, and the entry moves if its new priority requires it.

Example

from paged_collections import PriorityQueue, PriorityQueueF64

queue = PriorityQueue()
for key, priority in [(7, 10), (2, 30), (9, 20), (4, 15)]:
    queue.push(key, priority)
# Pushing an existing key changes its priority and returns the old priority.
print("old priority =", queue.push(7, 40))
print("removed =", queue.remove(9))
print("pop order =", [queue.pop() for _ in range(len(queue))])

floats = PriorityQueueF64(min=True)
floats.push(7, 1.5)
floats.push(2, 0.5)
floats.push(9, 2.5)
floats.push(7, 0.25)
floats.remove(9)
print("float min order =", [floats.pop() for _ in range(len(floats))])
use paged_collections::priority_queue::PagedPriorityQueue;

fn main() {
    let mut queue: PagedPriorityQueue<usize, i32> = PagedPriorityQueue::new();
    for (key, priority) in [(7, 10), (2, 30), (9, 20), (4, 15)] {
        queue.push(key, priority);
    }
    println!("old priority = {}", queue.change_priority(&7, 40).unwrap());
    println!("removed = {}", queue.remove(&9).unwrap().1);
    let mut order = Vec::new();
    while let Some(item) = queue.pop() {
        order.push(item);
    }
    println!("pop order = {order:?}");
}

Python output:

old priority = 10
removed = 20
pop order = [(7, 40), (2, 30), (4, 15)]
float min order = [(7, 0.25), (2, 0.5)]

The Rust example prints the first three lines.

Complexity

OperationCost
push, pop, change_priority, removeO(log n) comparisons
peek, priority, contains_keyO(1)
into_sorted_vecO(n log n)

Equal priorities come out in unspecified order.

In Rust, try_reserve(additional) reserves room in both dense arrays. If capacity overflows or allocation fails, the queue keeps its entries, array addresses and capacity.

Generational Keys

A slot holds one key. push evicts another generation of the key’s slot; try_push refuses. Lookups check the whole key.

Panic Safety

If a priority comparison or a change_priority_with closure panics, every remaining entry stays findable and paired with its priority, but heap order may be broken: later pop and sorted results are unspecified. The same applies when a stored priority’s ordering changes through interior mutability. Neither causes undefined behaviour.

Rust and Python

RustPython
push(k, p) -> Option<P>push(k, p), q[k] = p
try_push
push_increase, push_decreasepush_increase(k, p), push_decrease(k, p)
pop(), peek()pop(), peek() (raise IndexError when empty)
change_priority(&k, p), change_priority_withpush(k, p), q[k] = p
priority(&k)q[k], get(k, default)
remove(&k)remove(k), del q[k]
into_sorted_vec, into_sorted_itersorted()
keys, priorities, key_slice, priority_slicekeys(), items()
reserve, try_reserve

Python push_increase and push_decrease insert an absent key or update its priority only when the new numeric value is strictly greater or strictly smaller, respectively. Both return whether the queue changed. With min=True, pop() selects the lowest priority and these methods keep their numeric meanings.

API: PagedPriorityQueue.

Paged Vector

PagedVec<T, PAGE = 1024> is a growable vector stored in fixed-size pages. A page is allocated once and never reallocated, so pushing never moves or copies existing elements.

See how paged storage grows.

Python: PagedList (objects) and PagedListF64, PagedListF32, PagedListI64, PagedListI32, PagedListU64, PagedListU32, PagedListBool. These classes implement the list protocol. paged_list(dtype) creates an instance of the class for a dtype.

Example

from paged_collections import PagedList

values = PagedList([1, 2, 3])
values.extend(range(4, 10_001))
print("len =", len(values))
print("first =", values[0])
print("last =", values[-1])
print("popped =", values.pop())
values.insert(1, 99)
print("removed =", values.pop(1))
print("prefix =", list(values[:3]))
use paged_collections::paged_vec::PagedVec;

fn main() {
    let mut values: PagedVec<i32> = PagedVec::new();
    values.extend([1, 2, 3]);
    let first: *const i32 = &values[0];
    for value in 4..=10_000 {
        values.push(value);
    }
    println!("len = {}", values.len());
    println!("first = {}", values[0]);
    println!("last = {}", values[values.len() - 1]);
    println!("same address = {}", std::ptr::eq(first, &values[0]));
    println!("popped = {}", values.pop().unwrap());
    values.insert(1, 99);
    println!("removed = {}", values.remove(1));
    println!("prefix = {:?}", values.iter().take(3).collect::<Vec<_>>());
}

Python output:

len = 10000
first = 1
last = 10000
popped = 10000
removed = 99
prefix = [1, 2, 3]

The Rust example also prints same address = true. Element 0 kept its address through 10,000 pushes.

Address Stability

  • An element keeps its address while it stays at the same index, through any number of push, extend and reserve calls.
  • Operations that change which element sits at an index (insert, remove, swap, swap_remove, retain, dedup, drain, extract_if) move elements, as in a Vec.
  • split_off at a page boundary transfers whole pages without moving their elements.

Complexity

OperationCost
get, indexing, popO(1)
pushamortized O(1): one page allocation every PAGE pushes, rare directory growth
insert, removeO(len − index)
truncate, clearO(removed) drops; pages are kept
extract_ifO(visited), plus shifting the tail after a removal. No allocation.
split_offO(transferred pages) at a page boundary, else O(len − at)
binary_search, partition_pointO(log n), no allocation
sort and variantsthe slice sort, plus moving all elements out to a temporary buffer and back

The worst-case push costs one page allocation plus a copy of the page directory, which is PAGE times shorter than the elements. A Vec instead copies all elements on growth.

In Rust, extract_if(range, filter) visits that range in order and yields the elements for which the filter returns true. The filter can mutate each element. Dropping the iterator early keeps the unvisited elements in order. If the filter panics, the current element is kept with its mutations.

No Contiguous Slice

There is no as_slice or Deref<Target = [T]>. Use pages() and pages_mut() for per-page slices, or with_contiguous_mut to run a slice algorithm on all elements through a temporary buffer. Typed Python lists expose pages as NumPy views (page_view(i), page_views()) and copy everything with to_numpy().

Rust and Python

RustPython
push, extendappend, extend, +=
pop, insert, removepop([i]), insert(i, v), del l[i]; remove(value) searches by value
indexing, rangel[i], l[a:b] (slices copy)
extract_if(range, filter)
sort*sort(key=, reverse=) (typed lists: reverse= only)
pages()typed: page_view(i), page_views()
typed: get_many(indices), set_many(indices, values), to_numpy(), np.asarray(l)
reserve, shrink_to_fit, capacitysame names; capacity, allocated_pages are properties

API: PagedVec.

Deque

PagedDeque<T, PAGE = 1024> is a double-ended queue stored in fixed-size pages. An element keeps its address for as long as it stays in the deque, through pushes and pops at either end, reserve and shrink_to_fit. Spare pages are kept at the back and reused at either end.

Python: PagedDeque follows collections.deque (CPython 3.12 semantics), including maxlen, rotate and the comparison operators.

A two-page deque with existing elements A, B, C and D. A front push puts L before A, and a back push puts R after D.
Each push uses a free slot at its end of the deque. A push across a page boundary uses another page.

Example

from paged_collections import PagedDeque

values = PagedDeque([1, 2, 3])
values.appendleft(0)
values.append(4)
print("values =", list(values))
print("index 2 =", values[2])
print("front =", values.popleft())
print("back =", values.pop())
print("remaining =", list(values))
values.rotate(1)
print("rotated =", list(values))
use paged_collections::paged_deque::PagedDeque;

fn main() {
    let mut values: PagedDeque<i32> = PagedDeque::new();
    values.extend([1, 2, 3]);
    values.push_front(0);
    values.push_back(4);
    println!("values = {:?}", values.iter().collect::<Vec<_>>());
    println!("index 2 = {}", values[2]);
    println!("front = {}", values.pop_front().unwrap());
    println!("back = {}", values.pop_back().unwrap());
    println!("remaining = {:?}", values.iter().collect::<Vec<_>>());
}

Python output:

values = [0, 1, 2, 3, 4]
index 2 = 2
front = 0
back = 4
remaining = [1, 2, 3]
rotated = [3, 1, 2]

The Rust example prints the same lines without the rotation.

Complexity

OperationCost
pops, access, indexing, swappingO(1)
pushesamortized O(1), occasional page allocation and directory growth
insert, removeO(min(index, len − index)) moves
truncate, clearO(removed) drops; pages are kept
binary_search, partition_pointO(log len)
reserve, shrink_to_fitO(allocated or freed pages)

Front operations change indices without moving the remaining elements. Insertion, removal, swapping and retention can move elements.

Elements are not contiguous. pages() returns the initialized part of each used page, and the first and last slices can be partial.

Rust and Python

RustPython
push_back, push_frontappend, appendleft
pop_back, pop_frontpop, popleft
extendextend, extendleft
front, back, indexingd[0], d[-1], d[i]
insert, removeinsert(i, v), del d[i]; remove(value) searches by value
rotate(n), reverse(), count, index, maxlen
reserve, shrink_to_fitsame names

API: PagedDeque.

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.

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.

Concurrent Containers

Rust feature concurrent (see Installation). The module uses core atomics and alloc; it does not need std.

Model: Grow Shared, Shrink Exclusive

Shared access (&self) may install pages and recycle slots. Allocated pages and directory chunks stay at stable addresses until exclusive access (&mut self) or destruction, so memory reclamation needs no epochs or hazard pointers. Removal of pages, conversion to plain types and shrink_to_fit need &mut self.

Example

use paged_collections::concurrent::{ConcurrentAppendHive, ConcurrentSparseSet};

// ANCHOR: queue
fn fifo_example() {
    use paged_collections::concurrent::ConcurrentQueue;

    let queue = ConcurrentQueue::<_, 2>::new();
    queue.push("first");
    queue.push("second");
    assert_eq!(queue.pop(), Some("first"));
    assert_eq!(queue.pop(), Some("second"));
}
// ANCHOR_END: queue

// ANCHOR: priority_queue
fn priority_example() {
    use paged_collections::concurrent::ConcurrentPriorityQueue;

    let queue = ConcurrentPriorityQueue::<u32, i32, 4>::with_shards(3);
    queue.push(1, 10);
    queue.push(5, 20);
    assert_eq!(queue.change_priority(&1, 30), Some(10));
    assert_eq!(queue.pop_exact(), Some((1, 30)));
    assert_eq!(queue.pop(), Some((5, 20)));
}
// ANCHOR_END: priority_queue

fn main() {
    fifo_example();
    priority_example();
    let hive: ConcurrentAppendHive<usize> = ConcurrentAppendHive::new();
    let keys: ConcurrentSparseSet<usize> = ConcurrentSparseSet::new();
    std::thread::scope(|scope| {
        for worker in 0..4 {
            let (hive, keys) = (&hive, &keys);
            scope.spawn(move || {
                for value in worker * 4..(worker + 1) * 4 {
                    hive.insert(value);
                    keys.insert(value);
                }
            });
        }
    });
    println!("hive count = {}", hive.len());
    println!("set count = {}", keys.len());
    let mut values: Vec<_> = hive.into_hive().values().copied().collect();
    values.sort_unstable();
    let mut contents: Vec<_> = keys.iter().copied().collect();
    contents.sort_unstable();
    println!("hive values = {values:?}");
    println!("set keys = {contents:?}");
}
hive count = 16
set count = 16
hive values = [0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15]
set keys = [0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15]

Containers

TypeShared (&self)Exclusive (&mut self)Lookups return
ConcurrentHive<T>insert, remove, takeiteration with &mut, drain, shrink_to_fit, into_hiveRef guard (two atomic writes per lookup)
ConcurrentAppendHive<T>insertremove, mutable access, shrink_to_fit, into_hive&T (one Acquire load)
ConcurrentPagedVec<T>pushremoval, editing, shrink_to_fit, conversion&T
ConcurrentQueue<T> (Python ConcurrentQueue)push, popclear, drain, shrink_to_fitowned value from pop
ConcurrentPriorityQueue<K, P> (Python ConcurrentPriorityQueue, ConcurrentPriorityQueueF64)push, change priority, remove, popclear, drain, shrink_to_fitcloned priority or closure
ConcurrentSparseSet<K>, ConcurrentSparseMap<K, V>insertremoval, clear, drain, shrink_to_fit, conversion&K, &V
ConcurrentDirectMap<K, V>insert, replace, remove, entry (per-page RwLock)drain, shrink_to_fit, reset, into_innerclosures (with), clones (get_cloned), entry guards
AtomicDirectMap (usize -> u64)lock-free insert, update, removeshrink_to_fitcopied u64
AtomicIdMap (Id -> u32)lock-free insert, update, removeshrink_to_fitcopied u32
ConcurrentIdAllocatorallocate, free, occupant, iterclearcopied Id

Notes per type:

  • ConcurrentHive: a lookup guard pins its value until dropped; hot values contend even between readers. Prefer the plain Hive when shared mutation is not needed.
  • ConcurrentAppendHive: iteration may miss insertions in flight. From<Hive> and into_hive keep live ids and stale-id history, in O(index bound).
  • Sparse set and map: entries cannot be removed or changed while shared. shrink_to_fit frees index pages with no entry and dense pages beyond the last entry; stored entries keep their addresses. Inserts of the same slot wait for its writer; other slots proceed independently. An occupied slot refuses other generations. Each try_insert reserves a dense position from one shared counter; under contention use try_insert_many, which reserves once per batch. extend and collect keep the first occupant of each slot, including existing occupants when extending. drain yields owned items in dense order and keeps allocated pages for reuse.
  • ConcurrentDirectMap: neighbouring keys share a page lock and contend. Release guards and entries before locking the same page again. Ordered shared traversals are consistent per page only. drain yields owned entries in key-index order and keeps allocated pages for reuse.
  • AtomicDirectMap, AtomicIdMap: prefer them over ConcurrentDirectMap when values fit: u64 values below u64::MAX, or any u32 value keyed by Id. Traversals copy values in index order.

The direct map and both atomic maps release empty pages with shrink_to_fit. Flat directory chunks stay allocated. Radix collapses branches with only one remaining child. Shared insertion can reinstall released pages.

Use for item in &collection on containers with iter and for item in &mut collection on containers with iter_mut. These loops use the same item types, order and consistency as the respective iterator methods.

ConcurrentPagedVec

Concurrent pushes can finish out of order. A point lookup can read a published element beyond the first pending slot. Length, iteration and page slices all use the contiguous published prefix.

Slots 0 and 1 are published while slot 2 is pending. Slot 3 already contains D. The length is 2, but get(3) can read D.
When slot 2 finishes publishing, the visible prefix can advance through slot 3. An iterator created earlier retains the prefix it started with.

shrink_to_fit frees pages wholly beyond the vector’s length.

ConcurrentQueue

ConcurrentQueue is an unbounded multi-producer, multi-consumer FIFO queue, adapted from Crossbeam’s SegQueue. It recycles pages through a free stack and waits at page boundaries. A pop can also wait for a push that has claimed a slot to publish its value. Shared peeking, iteration, cloning, snapshots and serialization are unavailable; an owned queue can be converted to a PagedDeque for serialization. The Python ConcurrentQueue holds Python objects and drains into a list. See Python Threads and the Python FIFO benchmarks.

A pop takes A from the head page. A push writes E into the next free slot after D on the tail page.
Producers claim slots at the tail and consumers take them from the head. A drained head page can be recycled for future pushes.
#![allow(unused)]
fn main() {
fn fifo_example() {
    use paged_collections::concurrent::ConcurrentQueue;

    let queue = ConcurrentQueue::<_, 2>::new();
    queue.push("first");
    queue.push("second");
    assert_eq!(queue.pop(), Some("first"));
    assert_eq!(queue.pop(), Some("second"));
}
}

ConcurrentPriorityQueue

ConcurrentPriorityQueue is an indexed max-priority queue split into shards by key page. Its pop is relaxed: it chooses the greatest of up to two sampled shard tops, with a fallback scan, and does not guarantee the global maximum. Use pop_exact to select the global maximum. Per-key operations lock one shard; pop_exact locks all shards. Callbacks and user trait implementations run under shard locks and must not call back into the same queue. The Python classes ConcurrentPriorityQueue and ConcurrentPriorityQueueF64 store numeric priorities and also support min queues. See Python Threads and the Python priority-queue benchmarks.

Four shard tops have priorities 45, 70, 95, and 35. A pop that samples the first two takes 70. An exact pop from the same state takes 95.
In this max-queue, the sampled shards determine which entry pop returns. pop_exact locks all shards and selects the global maximum.
#![allow(unused)]
fn main() {
fn priority_example() {
    use paged_collections::concurrent::ConcurrentPriorityQueue;

    let queue = ConcurrentPriorityQueue::<u32, i32, 4>::with_shards(3);
    queue.push(1, 10);
    queue.push(5, 20);
    assert_eq!(queue.change_priority(&1, 30), Some(10));
    assert_eq!(queue.pop_exact(), Some((1, 30)));
    assert_eq!(queue.pop(), Some((5, 20)));
}
}

Directories

The sparse types, ConcurrentDirectMap and AtomicDirectMap take a SharedDirectory parameter: Flat (default; O(1) page lookup, finite index range) or Radix (any usize index, memory proportional to installed pages, O(depth) lookup). AtomicIdMap is Flat-only; Tree has no concurrent form.

Id Allocation Under Contention

With std, freed slots go to one of 32 per-thread shards (no_std builds use one shared stack), each with its own free stack and block of fresh indices; a thread steals from other shards only when its own is empty. A single-threaded caller takes an inline fast path. Measured scaling is in Benchmarks.

occupant(index) reads the live generation at one index. Iterating over &allocator scans live ids in index order up to the bound read at the start. The scan takes no snapshot. Allocations and frees during iteration may or may not be reflected, and a yielded id can already have been freed.

Element Invariance

Shared insertion requires every element type to be invariant: shortening a stored reference’s lifetime would let a shorter-lived reference be inserted while the owner still expects 'static. The containers are invariant in their element types; compile-fail tests check this for each type.

Without std

Under no_std, the per-page locks of ConcurrentDirectMap spin. Lock guards are !Send there.

API: concurrent.

Python Threads

Concurrent Classes

ConcurrentSparseSet, the typed ConcurrentSparseMap* classes (F64, F32, I64, I32, U64, U32, Bool) and the typed ConcurrentDirectMap* classes support shared access from threads.

Sparse set and mapsDirect maps
Shared insertsset: insert, insert_many; maps: try_insert, get_or_insert, insert_manym[k] = v, insert, try_insert, get_or_insert, setdefault, set_many
Shared removalnodel m[k], remove, remove_many
Exclusive (conflicts raise)remove, remove_many, clear, shrink_to_fitclear, shrink_to_fit

On a direct map, assignment, insert and set_many replace a stored value. get_or_insert(key, value) and setdefault(key, value) atomically insert if the key is absent and return the stored value. shrink_to_fit() (on every concurrent set and map) frees pages with no live entries. Concurrent sparse map insertions keep existing values.

  • Default page size and Flat directory only; the constructors take no page_size=.
  • Equality and hashing are by identity, unlike the other classes.
  • Batch methods (*_many) release the GIL; single-key calls do not.
  • Results are copies (arrays, lists); there are no guards or views.
  • A conflicting exclusive call raises RuntimeError("Already borrowed").
  • Iteration visits a snapshot of keys with the same order and consistency as keys(). The maps’ contains_many(keys) returns a boolean array, treating invalid keys as absent just as key in m does.
  • Direct-map snapshots are in ascending key order. items_range(start=None, stop=None), keys_range and values_range cover the half-open interval [start, stop). Bounds are optional and clamped to the key domain. Like items(), each call is consistent within a page and weakly consistent across pages.
  • len() is exact only when no write is in flight.
  • ConcurrentSparseSet(keys) and ConcurrentSparseMapF64(keys, values) accept NumPy arrays or sequences, validated before any write. Later duplicate keys win, even in the insert-only sparse maps.
  • pickle, copy.copy, copy.deepcopy and copy() take one snapshot, with the same consistency as items(): entries inserted or removed during the call may or may not be included, but keys and values always pair up.

Example

from concurrent.futures import ThreadPoolExecutor

import numpy as np
from paged_collections import ConcurrentSparseMapF64

values = ConcurrentSparseMapF64()


def insert_chunk(worker):
    keys = np.arange(worker * 1000, (worker + 1) * 1000, dtype=np.uint32)
    return values.insert_many(keys, keys.astype(np.float64))


with ThreadPoolExecutor(max_workers=4) as pool:
    inserted = list(pool.map(insert_chunk, range(4)))
print("inserted =", sum(inserted))
print("len =", len(values))
print("checksum =", float(values.values().sum()))
inserted = 4000
len = 4000
checksum = 7998000.0

ConcurrentQueue

ConcurrentQueue(iterable=None) holds Python objects in FIFO order. Threads can share push, push_many, pop and pop_many. pop raises IndexError when empty, and pop_many(n) returns up to n items, stopping at the first empty pop. Length and truthiness are approximate during concurrent use and exact when no operation is in flight.

clear(), drain() and shrink_to_fit() require exclusive access. If another call holds a borrow, they raise RuntimeError("Already borrowed"). allocated_pages counts all allocated pages, including those pooled for reuse. shrink_to_fit() frees pages the current values do not need and preserves FIFO order. The queue has no iteration, peek, copy or pickle support. Use drain() to move the items into a list in FIFO order before copying or pickling. Python’s garbage collector cannot collect reference cycles through a queue.

Concurrent Priority Queues

ConcurrentPriorityQueue stores int64 priorities and ConcurrentPriorityQueueF64 stores float64 priorities, with NaN rejected. Both take integer keys in 0 <= key < 2**32. Pass min=True to prefer the lowest priority and shards= to choose a shard count from 1 to 65536. The initial items can be a mapping or iterable of pairs. Later duplicate keys win. concurrent_priority_queue(dtype, items, min, shards=...) selects the class by dtype.

push_increase(key, priority) and push_decrease(key, priority) insert an absent key or update its priority only when the new numeric value is strictly greater or strictly smaller, respectively, in either queue direction. The methods return whether the queue changed.

pop() uses relaxed ordering. With multiple shards, the entry it returns can rank below the global best. pop_exact() removes the global best and peek_exact() reads it. Both exact operations lock all shards. Ties have unspecified order. All three methods raise IndexError when they find no entry.

items(), sorted(), repr(), copying and pickling each read one snapshot. It is consistent within each shard and weakly consistent across shards. sorted() lists the best priorities first. The repr includes the class, min, shards and up to 20 entries. Copies and pickles preserve min and shards. Length and truthiness are exact when no write is in flight.

clear(), drain() and shrink_to_fit() require exclusive access and raise RuntimeError("Already borrowed") if another call holds a borrow. drain() returns all (key, priority) pairs in arbitrary order and keeps allocated pages. shrink_to_fit() shrinks shard storage and frees the index pages of empty shards.

Free-threaded CPython

Wheels exist for free-threaded 3.14t and 3.15t+ (see Installation). Importing the package keeps the GIL disabled, and the concurrent classes run in parallel.

The other classes are safe to share but are not designed for it: a call that conflicts with another thread’s call on the same object raises RuntimeError("Already borrowed"), or BufferError while views exist. Guard shared use of those classes with a lock.

Zero-copy views (view(), keys_view(), values_view()) are not covered by those checks: NumPy reads and writes their memory directly and may release the GIL while doing so. Writing through a view while another thread reads or writes the collection, or reading a view while another thread writes the collection, is a data race, with or without the GIL. Hold the same lock for the views as for the collection, or work on copies (keys(), values()).

Free-threaded 3.13t is not supported.

Scaling

benchmarks/python/concurrent_scaling.py measures batch throughput over thread counts; results are in Benchmarks.

NumPy Interop

Keys

Integer-keyed classes (SparseSet, SparseMap*, DirectMap*, priority queues) take keys in 0 <= key < 2**32 (KEY_LIMIT). IdMap* takes packed uint64 ids. Keys may be Python ints or objects with __index__.

  • Batch lookups (contains_many, discard_many, get_many) treat out-of-range integers as absent, including arbitrarily large ints inside Python sequences or (for integer-keyed classes) object arrays. IdMap* batches reject object-dtype arrays.
  • Batch insertion (add_many, set_many) rejects out-of-range keys.
  • The concurrent maps’ contains_many accepts an iterable or a one-dimensional array and reports invalid elements, including floats, as absent. Other batch lookup methods reject float key arrays.

Batch Methods

MethodInputResult
add_many(keys) (set)array-like of keysnumber added
set_many(keys, values)keys, and values: typed maps take an array-like or a scalar to broadcast; object maps take an iterablenumber of new keys
get_many(keys, default)keystyped maps: array of the value dtype; object maps: list. Without a default, an absent key raises KeyError
contains_many(keys)keysbool array
discard_many(keys)keysnumber removed
keys(), values()arrays (copies); object maps return values as a list

Batch methods run in one call into Rust. Native numeric arrays can avoid creating a Python object per element.

Typed Values

SparseMapF64, DirectMapF64, PagedListF64, IdMapF64 and the other typed classes store values unboxed in the dtype named by the suffix: F64, F32, I64, I32, U64, U32, Bool. sparse_map(dtype), direct_map(dtype), id_map(dtype), paged_list(dtype), concurrent_sparse_map(dtype), concurrent_direct_map(dtype) and priority_queue(dtype) create an instance of the class for a dtype.

A dtype argument takes anything numpy.dtype accepts: "float64", np.float64, np.dtype("f8") and float all select F64. Python’s int means NumPy’s default integer, which is int32 on Windows with NumPy 1.x, so name the width ("int64") for portable code.

Typed containers store values, not objects, so NaN != NaN as in NumPy: a typed container holding NaN does not compare equal even to itself.

Zero-Copy Views

MethodArrayWriteable
SparseSet.view()dense keys, uint32no
keys_view() (sparse and id maps)dense keysno
values_view() (typed sparse and id maps)dense valuesyes, except Bool
page_view(i), page_views() (typed lists)one page of elements eachyes, except Bool

Writes through a writeable view update the container. While any view is alive, operations that would move or resize the underlying buffer raise BufferError. Delete the view (or let it go out of scope) to release it. A view’s base is an ExportGuard that keeps the container alive. NumPy arrays are not tracked by Python’s garbage collector, so storing a view inside the container it views (m[k] = m.keys_view()) makes a cycle that is never freed.

Views bypass the borrow checks described in Python Threads: synchronise access to a view with access to its container when threads share them.

Direct maps have no views: their values live in pages, not one array.

Example

import numpy as np
from paged_collections import sparse_map

values = sparse_map("float64")
keys = np.array([7, 2, 9], dtype=np.uint32)
print("inserted =", values.set_many(keys, np.array([1.5, 2.5, 3.5])))
print("lookup =", values.get_many([9, 99, 7], default=-1.0).tolist())
view = values.values_view()
view *= 2
print("write through =", values.get_many(keys).tolist())
try:
    values[100] = 4.5
except BufferError as error:
    print("resize with view =", type(error).__name__)
del view
values[100] = 4.5
print("len after release =", len(values))
inserted = 3
lookup = [3.5, -1.0, 1.5]
write through = [3.0, 5.0, 7.0]
resize with view = BufferError
len after release = 4

Protocols

Pickle and Copy

Plain containers, concurrent maps and sets, and concurrent priority queues support pickle, copy.copy and copy.deepcopy. Use ConcurrentQueue.drain() to move FIFO contents into a list for copying or pickling.

  • The page size is part of the pickled state. Pickles made before page_size= existed load with page size 1024.
  • Hive and IdAllocator pickles keep generations and free slots, so ids stay valid across a round trip. A Hive rebuilds its free lists on load, so the slot the next insert takes can differ from the original. Restoring an older pickle revives ids removed since it was taken (see Hive).
  • Concurrent maps, sets and priority queues pickle a snapshot of their contents (see Python threads).

Loading a pickle whose page size the running build does not include raises ValueError (see page sizes).

Weak References

Every container class supports weakref.ref.

Subclassing

All container classes except the concurrent ones can be subclassed. Pickle and copy keep the subclass, its __dict__ and its __slots__ values (on 3.10 too, which lacks object.__getstate__).

Equality and Hashing

Plain containers compare by contents with ==. Concurrent containers compare by identity. Concurrent maps, sets and FIFO queues hash by identity. Plain containers and concurrent priority queues are unhashable. Lists and deques also support <, <=, >, >= against the same class, as list and deque do.

Collection ABCs

The package registers these classes with collections.abc for isinstance and issubclass checks. Virtual registration keeps each class’s native methods and return types.

ABCClasses
MutableMappingSparseMap, DirectMap, IdMap and their typed variants
MappingTyped concurrent sparse and direct maps
MutableSetSparseSet and BitSet
MutableSequencePagedList and its typed variants

Example

import pickle
import weakref

from paged_collections import SparseMap


class TaggedMap(SparseMap):
    __slots__ = ("tag",)


values = SparseMap([7, 2], [10, 20], page_size=256)
restored = pickle.loads(pickle.dumps(values))
print("page size =", restored.page_size)
print("items =", restored.items())
reference = weakref.ref(values)
print("weakref alive =", reference() is values)
del values
print("weakref cleared =", reference() is None)
tagged = TaggedMap([9], [30], page_size=256)
tagged.tag = "scores"
restored_tagged = pickle.loads(pickle.dumps(tagged))
print("subclass =", type(restored_tagged).__name__)
print("slot =", restored_tagged.tag)
print("subclass page size =", restored_tagged.page_size)
print("subclass items =", restored_tagged.items())
page size = 256
items = [(7, 10), (2, 20)]
weakref alive = True
weakref cleared = True
subclass = TaggedMap
slot = scores
subclass page size = 256
subclass items = [(9, 30)]

Rust and Python Names

RustPythonPython variants
bit_set::PagedBitSet<u32>BitSetDEFAULT_BIT_PAGE_SIZE (64-bit words)
sparse_set::PagedSparseSet<u32>SparseSet
sparse_map::PagedSparseMap<u32, V>SparseMapSparseMapF64, F32, I64, I32, U64, U32, Bool; sparse_map(dtype)
sparse_map::PagedSparseMap<Id, V>IdMapIdMapF64, …; id_map(dtype)
direct_map::PagedDirectMap<u32, V>DirectMapDirectMapF64, …; direct_map(dtype)
priority_queue::PagedPriorityQueue<u32, P>PriorityQueue (int64), PriorityQueueF64min=True; priority_queue(dtype)
paged_vec::PagedVec<T>PagedListPagedListF64, …; paged_list(dtype)
paged_deque::PagedDeque<T>PagedDeque
hive::Hive<T>Hive
id_alloc::IdAllocator, IdIdAllocator, packed int idsid_index, id_generation, make_id, id_indices
concurrent::ConcurrentSparseSet<u32>ConcurrentSparseSet
concurrent::ConcurrentSparseMap<u32, V>ConcurrentSparseMapF64, …typed only; concurrent_sparse_map(dtype)
concurrent::ConcurrentDirectMap<u32, V>ConcurrentDirectMapF64, …typed only; concurrent_direct_map(dtype)
concurrent::ConcurrentHive, ConcurrentAppendHive, ConcurrentPagedVec, AtomicDirectMap, AtomicIdMap, ConcurrentIdAllocatorRust only
PAGE const genericpage_size= keywordPAGE_SIZES, DEFAULT_PAGE_SIZE
page::Flat, Radix, Treealways Flat

Module constants: KEY_LIMIT (232), MAX_GENERATION (231), MAX_INDICES.

Reference documentation:

Benchmarks

These measurements come from one machine at the source revisions listed in Setup and Reproduction.

How to Read the Results

MetricWhat each value measuresBetter
ns/key or ns/elementMedian timed workload divided by the input size, n. Some workloads perform more or fewer than n calls.Lower
ns/queryMedian time per ordered query. A range query can visit many entries.Lower
Bytes/key or MBLive bytes requested from Rust’s global allocator at the stated checkpoint. MB is 1,000,000 bytes.Lower
ThroughputThe stated unit of work divided by median elapsed wall time, in millions per second. See each table for what counts as one unit.Higher
SpeedupThroughput at the stated worker count divided by throughput for the same workload on one thread.Higher

In each timing table, n is the number of input entries or the starting container size. A dash means no measurement is reported. Bold highlights the lowest time in the Rust timing tables and the highest throughput in the Python FIFO table. Small gaps on this machine are weak evidence of a performance difference.

Comparison Implementations

WorkloadBaselines
Keyed maps and setshashbrown::HashMap and hashbrown::HashSet (0.17.1) with rustc_hash::FxHasher (2.1.3), plus Rust’s BTreeMap and BTreeSet.
Direct indexingVecOption and VecBool are benchmark wrappers around Vec<Option<u64>> and Vec<bool>, respectively. They allocate one slot per index through the highest key and run only where that fits the harness’s size limit.
Rust priority queuepriority_queue::PriorityQueue (2.7.0), an indexed heap, and BinaryHeap, a standard-library heap with push and pop.
SequencesRust’s Vec and VecDeque.
Generational idsSlotMap and DenseSlotMap (1.1.1), slab::Slab (0.4.12), and thunderdome::Arena (0.6.1). IdAllocatorIdMap is this package’s IdAllocator paired with a PagedSparseMap<Id, u64>. A slab uses reusable integer keys.
Python FIFOCPython’s collections.deque and queue.SimpleQueue.
Python priority queuesCPython’s heapq on (priority, key) tuples, with a dictionary for lazy invalidation in the update workload or a threading.Lock for the multi-worker workload.

Keyed Collections

These tables compare sparse maps, sparse sets, and direct maps with the linked baseline implementations. PagedDirectMapFlat and PagedDirectMapRadix use the same map with different page directories.

WorkloadTimed work
InsertBuild from n keys in pattern order, including allocation.
HitLook up each present key once in shuffled order.
MissLook up n absent keys from a disjoint part of the same pattern.
IterateTraverse the entries and fold them into a checksum.
RemoveRemove all keys from a prebuilt container in shuffled order.

Dense keys are 0..n. Clustered keys form runs of 64 consecutive integers with run starts spread across the u32 range. Uniform keys come from a pseudo-random permutation of u32. The harness skips the 10⁷-key uniform cases because of the cost of allocating and initializing many pages.

For 10⁵ dense keys, the flat direct map took 4.25 ns/hit against 10.9 for hashbrown, and the sparse map iterated at 0.265 ns/entry against 1.84. For 10⁵ uniform keys, hashbrown inserted at 33.1 ns/key in the sparse-map comparison, against 3,345 for the sparse map. Use the key pattern closest to your workload when reading the tables.

Sparse Map (u32 -> u64)

Dense keys (ns/key)
n, opPagedSparseMapHashMapBTreeMapVecOption
10³ insert6.4424.175.24.7
10³ hit2.85.2645.61.15
10³ miss1.244.1324.40.779
10³ iterate0.1552.022.760.578
10³ remove8.0210.493.51.05
10⁵ insert6.0533.999.86.42
10⁵ hit8.94111322.57
10⁵ miss1.18842.80.803
10⁵ iterate0.2651.843.050.699
10⁵ remove23.216.817819.8
10⁷ insert1413014514.2
10⁷ hit47.942.345014.5
10⁷ miss1.188.4266.50.826
10⁷ iterate0.9073.868.872.27
10⁷ remove194141543107
Clustered keys (ns/key)
n, opPagedSparseMapHashMapBTreeMapVecOption
10³ insert41.125.875.657.4
10³ hit2.945.2349.61.15
10³ miss1.224.1528.60.762
10³ iterate0.1551.822.7518,291
10³ remove24.410.493.520.4
10⁵ insert21232.6116–
10⁵ hit15.611.3134–
10⁵ miss1.537.7335–
10⁵ iterate0.2631.833.23–
10⁵ remove10922179–
10⁷ insert56.8140147–
10⁷ hit60.341.5467–
10⁷ miss2.8913.251.5–
10⁷ iterate0.8943.99.91–
10⁷ remove307129573–
Uniform keys (ns/key)
n, opPagedSparseMapHashMapBTreeMapVecOption
10³ insert82526.883.6–
10³ hit5.45.2446.9–
10³ miss1.225.0224.7–
10³ iterate0.1551.83.06–
10³ remove28610.493.8–
10⁵ insert3,34533.1113–
10⁵ hit24.911.4133–
10⁵ miss410.778.8–
10⁵ iterate0.2651.843.68–
10⁵ remove81322.6172–

Sparse Set (u32)

Dense keys (ns/key)
n, opPagedSparseSetHashSetBTreeSetVecBool
10³ insert6.221.963.93.47
10³ hit2.694.8248.70.967
10³ miss1.014.4724.70.878
10³ iterate0.2071.682.780.571
10³ remove4.661185.30.906
10⁵ insert5.6928.589.33.32
10⁵ hit6.79.821281.24
10⁵ miss0.9957.8342.70.872
10⁵ iterate0.2111.572.930.558
10⁵ remove11.716.41575.78
10⁷ insert9.49571203.55
10⁷ hit31.136.13663.88
10⁷ miss1.017.9366.50.887
10⁷ iterate0.3411.934.910.565
10⁷ remove12811343321.5
Clustered keys (ns/key)
n, opPagedSparseSetHashSetBTreeSetVecBool
10³ insert41.523.864.11,557
10³ hit2.744.8348.60.952
10³ miss0.9994.4824.30.878
10³ iterate0.2071.542.7817,803
10³ remove20.71178.91.43
10⁵ insert2072791.3–
10⁵ hit11.810.1130–
10⁵ miss1.267.6734.8–
10⁵ iterate0.211.783.02–
10⁵ remove99.821.9157–
10⁷ insert46.575148–
10⁷ hit42.138.1394–
10⁷ miss2.6312.255–
10⁷ iterate0.3432.39.31–
10⁷ remove238109437–
Uniform keys (ns/key)
n, opPagedSparseSetHashSetBTreeSetVecBool
10³ insert83724.469.9–
10³ hit4.494.8148.9–
10³ miss0.9995.2324.7–
10³ iterate0.2071.543.11–
10³ remove27011.179.1–
10⁵ insert3,30027.7103–
10⁵ hit22.910.1128–
10⁵ miss3.7410.576.2–
10⁵ iterate0.211.773.63–
10⁵ remove79722.4151–

Direct Map (u32 -> u64)

Dense keys (ns/key)
n, opPagedDirectMapFlatPagedDirectMapRadixHashMapBTreeMapVecOption
10³ insert4.697.324.780.14.62
10³ hit2.372.38545.11.15
10³ miss1.211.24.1124.40.764
10³ iterate2.252.551.722.760.564
10³ remove2.312.610.493.91.06
10⁵ insert5.137.6633.91116.41
10⁵ hit4.254.2610.91312.56
10⁵ miss1.191.18842.80.801
10⁵ iterate2.252.541.613.080.692
10⁵ remove4.14.5317.117819.7
10⁷ insert716.313114714.2
10⁷ hit19.219.342.145114.6
10⁷ miss1.21.28.0166.30.828
10⁷ iterate2.562.823.839.542.26
10⁷ remove29.330.4140539106
Clustered keys (ns/key)
n, opPagedDirectMapFlatPagedDirectMapRadixHashMapBTreeMapVecOption
10³ insert50.838.526.481.356.4
10³ hit2.49174.9145.11.15
10³ miss1.22.624.1224.40.763
10³ iterate60.239.91.552.7418,305
10³ remove19.118.210.39420.8
10⁵ insert24999.232.6115–
10⁵ hit10.537.711133–
10⁵ miss1.53137.4935.1–
10⁵ iterate75.139.91.793.25–
10⁵ remove84.141.522.1179–
10⁷ insert161200128142–
10⁷ hit26.710841.5468–
10⁷ miss2.8516.512.749.3–
10⁷ iterate33.247.43.9110.3–
10⁷ remove177196125569–
Uniform keys (ns/key)
n, opPagedDirectMapFlatPagedDirectMapRadixHashMapBTreeMapVecOption
10³ insert8,6876,4012785.3–
10³ hit4.61215.1647–
10³ miss1.192.62524.7–
10³ iterate1,2082,4891.563.04–
10³ remove1,06580710.694.4–
10⁵ insert10,97411,03333113–
10⁵ hit23.369.111.1132–
10⁵ miss3.9526.110.478–
10⁵ iterate2,0933,0011.793.67–
10⁵ remove1,4841,06222.6173–

Ordered Queries

The input is dense. Each measurement issues 1,000 queries from shuffled starting keys and reports ns/query. next finds the first entry at or after the starting key, using BTreeMap::range(k..).next() for the baseline. range_1000 visits entries within a 1,000-key window. Windows near the end of the input can contain fewer entries.

n, queryPagedDirectMapFlatPagedDirectMapRadixBTreeMap
10³ next18.739.552.2
10⁵ next20.242.4129
10⁷ next21.944.9270
10³ range_10003,9672,9701,324
10⁵ range_10007,9305,7992,989
10⁷ range_10008,0125,8633,252

At 10⁵ keys, a flat direct-map next query took 20.2 ns versus 129 ns for the B-tree. At the same size, scanning the window took 7,930 ns for the flat direct map and 2,989 ns for the B-tree.

Memory

Tables report bytes/key after building the container: live allocator bytes above the pre-build baseline divided by n. Input key arrays are allocated before that baseline. RSS, allocator bookkeeping and temporary peak allocations are outside this metric.

Sparse Map

pattern, nPagedSparseMapHashMapBTreeMapVecOption
dense 10³16.434.826.416
dense 10⁵19.822.326.316
dense 10⁷24.128.526.316
clustered 10³34334.826.4506,344
clustered 10⁵41922.325.8–
clustered 10⁷87.528.525.8–
uniform 10³6,27934.824.3–
uniform 10⁵4,45922.319.7–

Sparse Set

pattern, nPagedSparseSetHashSetBTreeSetVecBool
dense 10³8.2210.311.71
dense 10⁵9.276.5511.61
dense 10⁷10.78.3911.61
clustered 10³33510.311.731,647
clustered 10⁵4096.5511.3–
clustered 10⁷74.18.3911.3–
uniform 10³6,27110.310.7–
uniform 10⁵4,4496.558.53–

Direct Map

pattern, nPagedDirectMapFlatPagedDirectMapRadixHashMapBTreeMapVecOption
dense 10³16.416.434.826.416
dense 10⁵16.116.122.326.316
dense 10⁷161628.526.316
clustered 10³52726334.826.4506,344
clustered 10⁵59625722.325.8–
clustered 10⁷25926028.525.8–
uniform 10³18,55516,43534.824.3–
uniform 10⁵16,73116,63922.319.7–

In this run a sparse index page used 4 bytes per slot and a direct-map page used 16 bytes per slot (u32 -> u64). A single 64-key run fills 6% of a 1,024-slot page. Widely scattered keys leave many pages with just a few live slots. The directory and any dense arrays also contribute to the total.

Removal and Shrinking

The harness builds each container, randomly removes 90% of its entries, then calls shrink_to_fit where available. The three columns show live allocations in MB at those checkpoints. BTreeMap frees nodes during removal. The Hive row also includes the benchmark’s vector of ids kept for removal.

ContainerPatternnBuiltAfter removalAfter shrink
PagedSparseMapuniform10⁵445.9445.9443.3
PagedDirectMapFlatuniform10⁵1,673.11,673.1197.4
PagedDirectMapRadixuniform10⁵1,663.91,663.9170.1
HashMapuniform10⁵2.22.20.3
BTreeMapuniform10⁵2.00.20.2
PagedSparseMapdense10⁷241.5241.552.1
PagedDirectMapFlatdense10⁷160.1160.1160.1
PagedDirectMapRadixdense10⁷160.1160.1160.1
HashMapdense10⁷285.2285.235.7
BTreeMapdense10⁷262.922.722.7
PagedSparseMapclustered10⁷875.3875.3685.6
PagedDirectMapFlatclustered10⁷2,594.02,594.02,590.6
PagedDirectMapRadixclustered10⁷2,603.62,603.62,592.8
HashMapclustered10⁷285.2285.235.7
BTreeMapclustered10⁷257.722.722.7
Hivesequential10⁷240.7240.8240.5

For uniform keys at 10⁵ entries, the flat direct map dropped from 1,673.1 MB to 197.4 MB after shrinking. For dense 10⁷ keys, almost every page still contained survivors, and memory held at 160.1 MB. The sparse map can shrink its dense arrays even when index pages remain allocated.

Page Size

The sweep changes the number of slots per page with Flat at 10⁵ keys. Timing is the median of seven samples divided by n. Bytes/key uses the live size after construction, also divided by n.

Sparse Map

PatternMeasurePAGE=64PAGE=256PAGE=1024PAGE=4096PAGE=16384
denseinsert ns/key11.311.110.610.410.5
densehit ns/key11.811.611.411.411.4
denseiterate ns/key0.2660.2670.2660.2660.267
densebytes/key19.919.819.819.820.3
clusteredinsert ns/key2,63266918740602
clusteredhit ns/key17.518.11919.218.1
clusterediterate ns/key0.2660.2660.2660.2670.267
clusteredbytes/key5,4521,3904193571,061
uniforminsert ns/key3,6431,2782,5369,92626,248
uniformhit ns/key27.528.92825.624
uniformiterate ns/key0.2670.2670.2660.2670.267
uniformbytes/key5,8102,4254,45916,48842,988

Direct Map

PatternMeasurePAGE=64PAGE=256PAGE=1024PAGE=4096PAGE=16384
denseinsert ns/key6.045.195.025.025.47
densehit ns/key5.855.725.675.675.67
denseiterate ns/key2.242.242.252.252.25
densebytes/key16.216.116.116.418.4
clusteredinsert ns/key2,6156632105922,384
clusteredhit ns/key10.111.912.312.410.4
clusterediterate ns/key1,00226287.8136481
clusteredbytes/key5,4481,4225961,1094,119
uniforminsert ns/key3,7973,2519,69537,356–
uniformhit ns/key26.527.123.721.8–
uniformiterate ns/key1,5048992,1067,753–
uniformbytes/key6,5625,48116,73165,624–

Small pages waste less memory per partly filled page, but with Flat the directory holds one pointer for each page up to the highest key: for keys spread over the u32 range, PAGE = 64 makes a 512 MiB directory, which dominates the memory column. 1024 is the default because it is close to the best across patterns. On dense keys the page size barely matters.

Priority Queue

The Rust paged priority queue and the priority-queue crate both support priority changes by key. BinaryHeap runs only the push and pop cases. Each value is ns per input element.

WorkloadTimed work
pushBuild by pushing n entries into an empty heap.
change_priorityChange n/2 priorities in a prebuilt heap. The table divides by n; multiply by two for ns per update.
pop_allDrain a prebuilt heap in priority order, stopping at empty.
n, opPagedPriorityQueuepriority-queueBinaryHeap
10³ push18.1647.74
10⁵ push17.81119.72
10⁷ push28.939020.7
10³ change_priority7.3928.7–
10⁵ change_priority18.485.4–
10⁷ change_priority145551–
10³ pop_all71.110948.3
10⁵ pop_all161319155
10⁷ pop_all6322,329564

At 10⁵ entries, the paged heap took 17.8 ns/element to push versus 111 for the indexed crate and 9.72 for BinaryHeap. Its priority changes took 18.4 ns per input element versus 85.4 for the indexed crate.

Paged Vector and Deque

Timings are ns per input element. The vector’s random_get and the deque’s random_index each look up n shuffled positions. One queue_churn step is a front pop followed by a back push, repeated n times on a full deque.

Vector

n, opPagedVecVec
10³ push2.852.29
10⁵ push2.951.68
10⁷ push7.965.09
10³ random_get2.231.21
10⁵ random_get2.231.21
10⁷ random_get3.221.4
10³ iterate0.3940.381
10⁵ iterate0.3940.372
10⁷ iterate0.3950.372
10³ sum0.4870.155
10⁵ sum0.5120.266
10⁷ sum1.050.9

Deque

n, opPagedDequeVecDeque
10³ push_front4.963.84
10⁵ push_front5.623.34
10⁷ push_front9.789.73
10³ queue_churn8.84.98
10⁵ queue_churn8.274.94
10⁷ queue_churn9.049.17
10³ random_index2.521.74
10⁵ random_index2.511.73
10⁷ random_index2.681.87

Iteration matches Vec. Indexing costs one extra indirection (1 to 2 ns). At 10⁷ elements the deque is level with VecDeque, whose growth copies every element; at small sizes VecDeque is faster.

Generational Ids

Timings are ns per input element. insert builds n entries, get looks up all ids in shuffled order, and iterate visits the live entries. remove_half_reinsert removes half the original entries and inserts as many again. See the baseline descriptions for the different handle types.

n, opHiveIdAllocatorIdMapSlotMapDenseSlotMapSlabArena
10³ insert9.319.37.7312.97.766.37
10⁵ insert15.618.18.2712.37.977.93
10⁷ insert24.335.920.129.519.719.9
10³ get4.194.842.923.371.72.61
10⁵ get6.9411.55.27.193.334.08
10⁷ get315922.436.916.918.3
10³ iterate0.8840.1561.40.460.8850.882
10⁵ iterate0.9850.2641.40.5010.8840.931
10⁷ iterate2.340.8952.361.052.322.36
10³ remove_half_reinsert8.615.83.716.53.734.92
10⁵ remove_half_reinsert12.13413.129.513.214.5
10⁷ remove_half_reinsert41.929367.117967.772.2

Hive keeps elements at stable addresses and pays for it on raw lookup speed against slotmap, slab and thunderdome, which store values in one growable vector. IdAllocator + PagedSparseMap also keeps values in a dense vector, so removal can move the last value; its cost is the extra index lookup.

Concurrent Scaling

Rust

The Rust scaling harness uses 2 million shuffled keys as work items and splits them across workers. The table divides the count of work items by the median of seven wall times. One item is one key or id processed, or one increment in the shared-counter reference. Churn counts insertions or allocations, with removal or freeing included in the timer. A batch call counts each key it processes.

Throughput in millions of work items/s. Each workload uses its own one-thread run as the speedup baseline.

Workload1 thread2 threads4 threads8 threads4-thread speedup
sparse try_insert (fresh)9.44.43.53.30.38x
sparse try_insert_many (fresh)19.137.372.7119.23.81x
sparse get31.461.0115.8229.23.68x
direct insert (fresh)18.827.846.685.42.48x
direct insert (overwrite)23.635.861.5109.02.60x
direct get15.823.139.972.82.52x
atomic direct insert (fresh)25.047.191.3178.63.66x
hive insert (fresh)19.740.278.2143.63.97x
hive remove6.612.824.748.43.74x
hive churn (64 live per thread)12.621.732.152.82.54x
append hive insert (fresh)22.940.677.2141.23.37x
id allocate (fresh)28.656.4114.7216.54.01x
id free10.119.337.371.23.71x
id churn (64 live per thread)12.621.830.652.12.43x
shared counter fetch_add only141.149.150.251.40.36x

Single-key try_insert into a fresh sparse map does not scale: every insert reserves a dense-array position from one shared counter, so threads contend on it. try_insert_many takes one reservation per batch and scales. The last row is a single shared fetch_add counter, as a reference for cache-line contention.

Python

The Python scaling harness splits 2 million shuffled keys among workers using typed float64 maps and batch calls. The median of seven elapsed wall times includes dispatch, NumPy copies and creation of the returned arrays. Speedup compares the same map and operation against one worker on the same Python build.

Free-threaded CPython 3.14.10 (GIL disabled)

ClassOperationThreadsMedian (s)Throughput (M keys/s)Speedup
ConcurrentDirectMapF64get_many10.19265110.381.00x
ConcurrentDirectMapF64get_many20.11169717.911.72x
ConcurrentDirectMapF64get_many40.06103132.773.16x
ConcurrentDirectMapF64get_many80.03971750.364.85x
ConcurrentDirectMapF64set_many10.11738317.041.00x
ConcurrentDirectMapF64set_many20.08190024.421.43x
ConcurrentDirectMapF64set_many40.04836141.362.43x
ConcurrentDirectMapF64set_many80.02762572.404.25x
ConcurrentSparseMapF64get_many10.10508319.031.00x
ConcurrentSparseMapF64get_many20.05544036.081.90x
ConcurrentSparseMapF64get_many40.03705753.972.84x
ConcurrentSparseMapF64get_many80.02555978.254.11x
ConcurrentSparseMapF64insert_many10.13817314.471.00x
ConcurrentSparseMapF64insert_many20.06285631.822.20x
ConcurrentSparseMapF64insert_many40.03427358.364.03x
ConcurrentSparseMapF64insert_many80.02156992.736.41x

CPython 3.12.16 (GIL enabled)

ClassOperationThreadsMedian (s)Throughput (M keys/s)Speedup
ConcurrentDirectMapF64get_many10.17440511.471.00x
ConcurrentDirectMapF64get_many20.10915418.321.60x
ConcurrentDirectMapF64get_many40.06631830.162.63x
ConcurrentDirectMapF64get_many80.04894740.863.56x
ConcurrentDirectMapF64set_many10.14160114.121.00x
ConcurrentDirectMapF64set_many20.09227621.671.53x
ConcurrentDirectMapF64set_many40.05661935.322.50x
ConcurrentDirectMapF64set_many80.03975950.303.56x
ConcurrentSparseMapF64get_many10.09224721.681.00x
ConcurrentSparseMapF64get_many20.05060439.521.82x
ConcurrentSparseMapF64get_many40.04650543.011.98x
ConcurrentSparseMapF64get_many80.02880769.433.20x
ConcurrentSparseMapF64insert_many10.14212414.071.00x
ConcurrentSparseMapF64insert_many20.06602130.292.15x
ConcurrentSparseMapF64insert_many40.04070649.133.49x
ConcurrentSparseMapF64insert_many80.03612455.373.93x

With the GIL, batch calls still overlap because they release it while in Rust; the free-threaded build also runs the Python-side dispatch in parallel.

Python Queues

The queue harness uses 1 million input items and reports throughput from the median of five wall times. 3.12 is CPython 3.12.16 with the GIL enabled. 3.14t is CPython 3.14.10 with the GIL disabled. Throughput units differ across workloads.

FIFO

Millions of items/s. Each item counts once for a push followed by a pop. The single-thread case fills the queue then drains it. Multi-thread cases use equal numbers of producers and consumers working concurrently. SimpleQueue consumers block in get(). The other consumers retry an empty queue. The batch column uses push_many and pop_many in batches of up to 1,024 items.

CasePythondequeSimpleQueueConcurrentQueueConcurrentQueue batch
1 thread3.1216.2912.246.0512.64
1 thread3.14t8.907.305.2011.75
4 + 4 threads3.123.494.491.816.23
4 + 4 threads3.14t3.493.322.895.58
8 + 8 threads3.123.894.552.196.08
8 + 8 threads3.14t0.420.711.755.62

At 8 producers and 8 consumers on free-threaded CPython, the per-item ConcurrentQueue path processed 1.75 M items/s and the batch path processed 5.62 M items/s. For single-threaded scalar calls, deque led on both builds.

Priority Queues

All runs use distinct integer keys with random float priorities in min-queue mode. PriorityQueueF64 and ConcurrentPriorityQueueF64 update existing keys in place. The concurrent queue’s pop uses relaxed ordering. Use the pop_exact column when comparing global-priority removal with heapq in the single-thread push-and-drain workload.

Push and Drain

Millions of items/s. A single thread pushes all items, then drains the queue. Each item counts once across both phases.

PythonheapqPriorityQueueF64Concurrent popConcurrent pop_exact
3.120.210.700.640.22
3.14t0.230.890.830.24

Update Existing Priorities

Millions of writes/s. The numerator counts the initial n pushes and n/2 priority changes. Elapsed time also includes draining the queue. heapq pushes a new tuple for each change and skips stale tuples during the drain using a dictionary of current priorities.

Pythonheapq + lazy invalidationPriorityQueueF64Concurrent pop
3.120.161.010.92
3.14t0.171.131.01

Shared Queue Across Workers

Millions of calls/s. Workers each push their share of the keys and wait at a barrier before draining the shared queue. Each successful push and pop counts separately. The lock-based heapq baseline uses one shared threading.Lock. The paged queue uses relaxed pop. The one-worker row here uses the same lock-based harness and units as the multi-worker rows.

WorkersPythonheapq + lockConcurrent pop
13.14t0.401.50
43.14t0.174.19
83.120.130.89
83.14t0.155.34

Setup and Reproduction

ItemConfiguration
Machine4 × Intel Xeon E7-8860 v4 at 2.20 GHz (72 cores, 144 hardware threads), 503 GB RAM, Linux 5.15, glibc 2.35
Rust resultsb814a0e, rustc 1.100.0, release mode, no target-cpu flags
Rust timingCriterion 0.5.1 medians from one run. The largest cases use 10 samples and a 3-second measurement target. Different groups ran on separate physical cores. The scaling run used eight physical cores on one NUMA node and ran alone.
LoadOther users idle (load average 0.0 at the start)
Python queue resultsPackage built from 0989af0. The later commit 267f4c3 contains the benchmark script. Runs were pinned to 32 hardware threads with taskset -c 64-95.

From the repository, run the Rust harness with the source revision above to reproduce the Rust setup:

cargo bench -p paged-collections-bench --bench sparse
cargo run --release -p paged-collections-bench --bin memory
cargo run --release -p paged-collections-bench --bin churn
cargo run --release -p paged-collections-bench --bin page_sweep
cargo run --release -p paged-collections-bench --bin concurrent_scaling -- 2000000 7

The other Criterion groups are direct, ids, seq and pq. The largest cases can require tens of GiB. To select a smaller case, pass a Criterion filter, for example -- /1000/.

Run the Python scripts from the repository root with a release build of paged-collections installed in the chosen Python environment:

python benchmarks/python/concurrent_scaling.py --n 2000000 --threads 1 2 4 8 --repeat 7
python benchmarks/python/queues.py --n 1000000 --threads 1 2 4 8 --repeat 5

Testing and Soundness

Where unsafe Is Used

ModuleWhy
paged_dequeuninitialized slots in pages; elements are moved in and out manually
concurrentatomics publish slots and pages to other threads; guards hand out references to shared slots
Python bindingsNumPy views over container memory (guarded by export counts)

The other single-threaded containers (sparse set and map, direct map, priority queue, hive, id allocator, page directories) use no unsafe code.

Test Layers

LayerWhat it checksWhere
Unit and doctestsAPI contracts, documented examples (including the README)crates/paged-collections/src, cargo test
Model tests (proptest)random operation sequences against a standard-library oracle (Vec, VecDeque, HashMap, BTreeMap, BinaryHeap)crates/paged-collections/tests/*_model.rs
Panic safetyinvariants after panicking Drop, Ord and user closuresunit tests per container
Miriundefined behaviour in the Rust tests, including concurrent testsBefore release, outside CI
loomexhaustive interleavings (preemption bound 2) of the concurrent protocols: publication, free-stack sharding, page installation, guardssrc/concurrent/loom_*.rs
ThreadSanitizerdata races in the concurrent stress testsmanual
Compile-fail doctestslifetime invariance of every concurrent element typeconcurrent module docs
Python testsCPython protocol parity (list, deque, set, dict), batch methods, views, pickling, free threadingtests/

Running Them

cargo test --all-features
cargo +nightly miri nextest run -p paged-collections --all-features -E 'not binary(rayon)'
MIRIFLAGS="-Zmiri-tree-borrows -Zmiri-ignore-leaks" cargo +nightly miri nextest run -p paged-collections --all-features --test rayon
MIRIFLAGS="-Zmiri-tree-borrows -Zmiri-ignore-leaks" cargo +nightly miri test -p paged-collections --all-features --doc
RUSTFLAGS="--cfg loom" cargo test -p paged-collections --features concurrent --lib --release loom
cargo build -p paged-collections --no-default-features          # no_std
uv sync && uv run pytest

Miri over the full suite is slow. cargo miri nextest run runs tests in parallel. The rayon tests and doctests run under Tree Borrows because rayon’s crossbeam-epoch dependency fails the default Stacked Borrows check. The loom suite takes several minutes in release mode.