Sub topic 8
Persistent hash maps with HAMTs
This chapter assumes you have read the previous chapters on path copying and persistent vectors. You should also know the basics of hash tables and bitwise operations (&, >>, <<).
From vector tries to hash maps
A persistent vector uses slices of an integer index to walk down a wide trie. A hash array mapped trie (HAMT) uses the same idea for maps. It takes slices of the key's hash instead of an index. Each 5-bit slice picks one of 32 branches, so a lookup needs at most a handful of steps. An update copies only the nodes on that path, and the rest of the map is shared with the old version.
Compressed nodes
A node with 32 array slots would waste memory when most are empty. A HAMT node stores two things:
- A 32-bit bitmap. Bit
iis set if branchiis occupied. - A compact array holding only the occupied entries.
To find the array position for branch i, count the set bits below bit i. This count is a popcount.
A working implementation
This version supports put and lookup. Entries are (key, value) tuples, and a slot holds either an entry or a child node. It needs Python 3.10 or later for int.bit_count.
BITS = 5
MASK = 0b11111
class Node:
__slots__ = ("bitmap", "slots")
def __init__(self, bitmap=0, slots=()):
self.bitmap = bitmap
self.slots = slots
def h32(key):
return hash(key) & 0xFFFFFFFF
def lookup(node, key, default=None, shift=0):
h = h32(key)
while True:
bit = 1 << ((h >> shift) & MASK)
if not node.bitmap & bit:
return default
slot = node.slots[(node.bitmap & (bit - 1)).bit_count()]
if isinstance(slot, Node):
node, shift = slot, shift + BITS
else:
return slot[1] if slot[0] == key else default
def put(node, key, value, shift=0):
if shift > 32:
raise ValueError("full 32-bit hash collision is not handled")
h = h32(key)
bit = 1 << ((h >> shift) & MASK)
idx = (node.bitmap & (bit - 1)).bit_count()
if not node.bitmap & bit:
slots = node.slots[:idx] + ((key, value),) + node.slots[idx:]
return Node(node.bitmap | bit, slots)
slot = node.slots[idx]
if isinstance(slot, Node):
new = put(slot, key, value, shift + BITS)
elif slot[0] == key:
new = (key, value)
else:
child = put(Node(), slot[0], slot[1], shift + BITS)
new = put(child, key, value, shift + BITS)
return Node(node.bitmap, node.slots[:idx] + (new,) + node.slots[idx + 1:])
m1 = Node()
for k in range(1, 101):
m1 = put(m1, k, k)
m2 = put(m1, 50, "new")
assert lookup(m1, 50) == 50 # old version unchanged
assert lookup(m2, 50) == "new"
assert m1.slots[1] is m2.slots[1] # branch for keys 1, 33, 65, 97 is shared
assert m1.slots[18] is not m2.slots[18] # branch holding key 50 was copiedThe put function never changes an existing node. It builds a new Node at each level on the path back up, so the old root still describes the old map.
Following one update
Updating key 50 goes like this:
- The first 5 bits of the hash are 18, so the root's bit 18 is checked.
- That slot holds a child node, because keys 18, 50 and 82 share the same first slice. The code recurses into it with the next 5 bits.
- The matching entry is replaced in a new copy of the child node.
- A new root is built that points to the new child. The other 31 root slots are reused as they are.
When two different keys land in the same slot, the code pushes the old entry down into a new child node. It does this until their hash slices differ.
Costs and limits
| Operation | Cost |
|---|---|
| lookup | O(log32 n) steps, at most 7 here |
| put | O(log32 n) nodes copied, each up to 32 slots wide |
| memory per update | one new node per level |
Real libraries add several things this sketch leaves out:
- Proper collision buckets for keys with equal full hashes.
- Deletion that collapses single-entry nodes.
- Cached hashes and transients for batch building.
Exercise
A root node has bitmap 0b10110 (bits 1, 2 and 4 set). A key's current 5-bit slice is 4. Which array index holds its slot?
Show answer
Count the set bits below bit 4. Bits 1 and 2 are set, so the popcount is 2 and the slot is at index 2 of the compact array.