ls lib/
lib
Articles on how languages, libraries and systems work inside, each checked against the source at a stated version and kept up to date.
Posts are dated notes about something I found. These are references: each says which versions it was checked against, and gets updated when those change.
courses
PostgreSQL for the people who write the queries 4/34 lessons
PostgreSQL from the query side: SELECT and joins through window functions, JSONB, transactions, indexes, EXPLAIN, partitioning and row-level security. Small datasets, step-through figures and SQL you can edit and run in the page.
PostgreSQL internals, by building tinypg 4/30 lessons
How PostgreSQL 19.0 stores, logs, versions, indexes, plans and runs your data, read from its source, while a tiny Postgres in Python grows one piece per lesson.
Building a Python in C 4/33 lessons
We write minipy, an interpreter for a subset of Python, in C: from an empty file to a bytecode VM with reference counting and a cycle collector, each piece set beside the way CPython 3.15 does it.
Number theory for competitive programming 4/27 lessons
The number theory that LeetCode, HackerRank and Codeforces problems keep asking for: gcd, primes and sieves, modular arithmetic, counting mod p, and fast factoring, with proofs short enough to remember and tested Python you can paste.
topics
APL 2
- draft How GNU APL sorts and stores arraysInside GNU APL 2.0: 24-byte cells, a value header with room for 12 of them, integers that turn into floats at 9.2 × 10¹⁸, and a heapsort behind ⍋, ⍒, ∪ and ⍳.
- draft The outer product: APL's most elegant way to waste memoryHow much memory +/(∪X)∘.=X really takes in GNU APL, why it stops with WS FULL long before the machine runs out, and two ways to count that don't build the table.
BQN 2
- draft Counting without loops: Group, Classify and Indices in BQNFour ways to count how often each value occurs in a BQN list, what CBQN does inside each one, and why the inverse of Indices beats a hash map by a factor of 80.
- draft How CBQN sorts: choosing an algorithm by element typeCBQN picks insertion sort, counting sort, radix sort, bucket sort or Timsort by looking at how an array is stored, so the same million numbers sort in 0.4 ms or 70 ms.
C 2
- draft qsort is not always quicksort: what C libraries really doWhat qsort runs in glibc, musl, FreeBSD and macOS, from merge sort and smoothsort to two kinds of Bentley-McIlroy quicksort, and what each means for stability, worst case and memory.
- draft Why C programmers write their own hash tablesThe C library has no map, POSIX hsearch gives you one global string table that behaves differently on every libc, and a usable open-addressing table fits in about a hundred lines.
C++ 2
- draft How std::unordered_map works, and why it can't be flatWhat libc++ 22 allocates for every std::unordered_map entry, how it picks bucket counts, why std::hash<int> returns its argument, and which rules in the C++ standard rule out an open-addressing table.
- draft std::sort, partial_sort and nth_element in libc++What libc++ 22 runs for std::sort, std::partial_sort, std::nth_element and std::stable_sort, how many comparisons each makes, and an adversary that makes nth_element quadratic.
Clojure 2
- draft Persistent maps in Clojure: HAMTs and structural sharingHow Clojure 1.12.7 makes assoc return a new map without copying the old one: array maps up to eight entries, a 32-way hash array mapped trie after that, Murmur3 hashes, and path copying measured on a million keys.
- draft Transients: how Clojure mutates in privateHow Clojure 1.12.7's transient maps edit a persistent hash trie in place without anyone noticing: the edit token on every node, what persistent! really does, the eight-entry trap, the thread check that was removed in 1.7, and what it saves.
DuckDB 2
- draft How DuckDB runs GROUP BY: vectorised, parallel hash aggregationWhat happens between the table scan and the result of a DuckDB GROUP BY in 2.0.1: vectors of 2,048 values, one partitioned hash table per thread, partitions merged in parallel, and the cases where there is no hash at all.
- draft ORDER BY ... LIMIT in DuckDB: the TOP_N operatorHow DuckDB 2.0.1 answers ORDER BY ... LIMIT n without sorting: a heap of n sort keys per thread, a shared boundary that lets threads and the table scan skip data, the 5,000-row rule for when it sorts anyway, and the optimizer that turns QUALIFY row_number() <= n into the same idea.
Elixir 1
- draft How Elixir sorts: Enum.sort_by and lists:sortElixir's Enum.sort and Enum.sort_by hand the work to Erlang's lists:sort, a stable natural merge sort; how sort_by keeps :desc stable, why Enum.sort(:desc) doesn't, and what term ordering lets you skip.
Erlang and the BEAM 3
- draft ETS: mutable tables in an immutable languageHow ETS gives Erlang a mutable hash table in Erlang/OTP 29: who owns a table, how update_counter changes a number in place, the linear hash table behind a set, the copies on every read, and what it costs against a map.
- draft How Erlang sorts: lists:sort, keysort and term orderWhat lists:sort does in Erlang/OTP 29: a merge sort written in Erlang that finds runs, a fixed order between all terms, why sorting tuples costs more than sorting integers, and when keysort wins.
- draft Maps on the BEAM: flatmaps, HAMTs and immutabilityWhat an Elixir map is inside Erlang/OTP 29: a sorted key tuple and a value array up to 32 keys, a 16-way hash trie after that, and how an immutable update gets away with copying a few dozen words.
Go 2
- draft How Go maps work: Swiss tables since Go 1.24What go1.27's built-in map does with your keys: 8-slot groups with control bytes, tables capped at 1024 slots, a directory of tables, and an iteration order that is a random rotation of a fixed one.
- draft How Go sorts: pdqsort in the slices packageWhat slices.Sort, slices.SortFunc and sort.Slice do in go1.27: pattern-defeating quicksort with insertion sort and a heapsort fallback, why it isn't stable, and what the stable sort costs instead.
Haskell 2
- draft Data.Map is a tree: how Haskell's containers workWhat containers 0.8 does with your keys: a weight-balanced binary tree for Data.Map, a big-endian Patricia trie for Data.IntMap, path copying on every insert, and how deep the trees really get.
- draft Laziness in practice: foldl, foldl' and thunksWhere lazy evaluation builds chains of thunks in GHC 9.14 programs, when -O2 removes them and when it can't, and the place where laziness saves work: take 3 of a sort.
Java 2
- draft How Java's HashMap works: buckets, treeification and hash spreadingWhat OpenJDK 27's HashMap does with a key: a power-of-two array of buckets, one XOR to spread the hash, chains that turn into red-black trees past eight nodes, doubling that keeps chain order, and why a map of Integer keys iterates in the same order on every run.
- draft Why Java sorts ints and objects differentlyArrays.sort(int[]) runs a dual-pivot quicksort with insertion-sort, run-merging and heap-sort fallbacks, while Arrays.sort(Object[]) and List.sort run TimSort: what each does in OpenJDK 27, why stability decides which one you get, and what the difference costs.
JavaScript 2
- draft How V8 sorts arrays: TimSort in TorqueWhat Array.prototype.sort does in V8 12.9: string comparison by default, holes and undefined set aside, then a TimSort written in Torque with runs, binary insertion, merge invariants and galloping.
- draft Objects vs Map in V8: how keys are stored and orderedWhy a plain object lists integer keys in numeric order and a Map lists them in insertion order, and how V8 12.9 stores each: elements arrays, number dictionaries and a deterministic hash table.
K 2
- draft Dictionaries and grouping in KWhat a K dictionary is inside ngn/k, why looking a key up scans a list, what happens when you update a key that isn't there, and how group keeps keys in first-appearance order.
- draft Reading ngn/k's C: how a tiny interpreter is writtenA guided read through ngn/k, a complete K interpreter in about 2,100 lines of very dense C: its macros, its 64-bit values, its dispatch tables, and the primitives it writes in K.
OCaml 2
- draft How OCaml's Hashtbl and polymorphic hash workOCaml 5.5.2's Hashtbl is a bucket array of linked cells that doubles at load factor 2, hashed by a C function that stops after 10 values, with polymorphic compare for equality and randomization you have to ask for.
- draft OCaml's polymorphic compare: convenient and slowHow OCaml 5.5.2's compare orders any two values by walking their memory, when the compiler quietly replaces it with an integer comparison, and what it costs when it doesn't.
Prolog 2
- draft Counting in Prolog: the dynamic database, assoc trees and clumped/2Three ways to count occurrences in SWI-Prolog 11.0.1, what each does inside (just-in-time hash indexes, a failure-driven loop, a sort, an AVL tree with a brand-new C fast path), and how fast each one is.
- draft Sorting in Prolog: standard order of terms, msort and sort/4How SWI-Prolog 11.0.1 sorts: the standard order of terms that lets sort/2 work without a comparison, the natural merge sort in pl-list.c behind sort/2, msort/2, keysort/2 and sort/4, and the two ways a sort can quietly drop your data.
Python 4
- draft Counter, most_common and heapq: top-k in the standard libraryHow collections.Counter counts, how most_common and heapq.nsmallest pick the top few, and why they break ties in opposite directions, read from the CPython 3.15.2 source.
- draft How a Python dict worksInside CPython 3.15's dict: the index table and entries array, the probe sequence, resizing, deletions, and why counting with a dict is linear.
- draft How Python sorts: runs, galloping and powersortWhat CPython 3.15's list.sort does with your data: natural runs, binary insertion sort, a powersort merge stack, galloping, and type-specialised compares.
- draft Multiplying a list in Python: loops, reduce, operator.mul and math.prodWhat a for loop, functools.reduce with a lambda or operator.mul, and math.prod actually execute in CPython 3.15, how fast each one is, and what changes once the product outgrows a machine word.
Ruby 2
- draft How Ruby sorts: qsort_r, a private introsort and quickselectIn ruby 4.0.10, sort hands the work to the C library, sort_by on numbers runs its own introsort, and max_by(n) runs a quickselect. None of them promises stability.
- draft How Ruby's Hash works: st_table, open addressing and ar_tableWhat ruby 4.0.10 builds when you write {}: a flat array for up to eight entries, an open-addressing table with a separate entries array after that, seeded integer hashes, and why tally hashes each key once.
Rust 2
- draft How Rust sorts: driftsort, ipnsort and select_nth_unstableWhat slice::sort, sort_unstable and select_nth_unstable do in Rust 1.100.1: driftsort and ipnsort since 1.81, insertion sort up to 20 elements, when the stable sort allocates, an O(n) selection with a median-of-medians fallback, and why a bad comparison can now panic.
- draft How Rust's HashMap works: hashbrown, Swiss tables and SipHashWhat std's HashMap in Rust 1.100.1 does with a key: hashbrown's Swiss table with one control byte per slot, 8-byte groups on Apple silicon and 16 on x86, a 7/8 load factor, and SipHash-1-3 under keys that change per thread and per map.
SQL and SQLite 2
- draft How SQLite runs GROUP BY and ORDER BY ... LIMITWhat EXPLAIN QUERY PLAN's "USE TEMP B-TREE" lines really are in SQLite 3.54: GROUP BY is a merge sort, ORDER BY with a LIMIT keeps only LIMIT rows in a small B-tree, and the GROUP BY quietly borrows the ORDER BY's direction.
- draft Multiplying rows in SQL: SQLite has no PRODUCT()SQLite can sum a column but not multiply one. Why the exp(sum(ln(x))) trick got 15% of products of three numbers under 100,000 wrong, how a recursive CTE folds rows exactly, and what SQLite 3.54 does when the integers overflow.
Swift 2
- draft How Swift sortsWhat sort(by:) does in Swift 6.4.2: a Timsort without galloping, insertion sort below 64 elements, a buffer of half the array, a stability guarantee that was true for four years before the documentation said so, and a descending input that costs more than a random one.
- draft How Swift's Dictionary works: open addressing, SipHash and copy-on-writeWhat Swift 6.4.2's Dictionary does with your keys: one allocation holding a bitmap, a key array and a value array, linear probing in a power-of-two table, SipHash-1-3 with a random seed per process and another per table, and copies that happen only on the first write.
Uiua 2
- draft How Uiua runs: stack, arrays and special-cased idiomsWhat the Uiua 0.19.1 interpreter does with a line of glyphs: a tree of nodes, a peephole optimizer that rewrites known idioms, fast paths inside primitives, and one idiom from the docs that misses its fast path.
- draft Numbers in Uiua: everything is a floatUiua shows one number type, the IEEE double, and stores a second one, the byte; what that means for integers, indices, counts, printing, parsing, NaN and hash maps in Uiua 0.19.1.
Unix tools 2
- draft awk's associative arrays: hash tables since 1979How Kernighan's awk stores an associative array, when the table grows, why for-in comes out in the order it does, and how the design changed from Seventh Edition Unix to macOS.
- draft How sort(1) sorts more data than fits in memoryHow the sort on macOS and FreeBSD splits big input into sorted temporary files and merges them back, how much memory it allows itself, and why the locale matters more than the algorithm.
Zig 2
- draft Allocators in Zig: who owns the memoryWhat a std.mem.Allocator is in Zig 0.17.1, which allocator main gets in each build mode, how the page, arena, smp, C and new SafeAllocator differ inside, and what each one costs, measured.
- draft Zig's HashMap: metadata bytes, tombstones and a fixed seedHow std.AutoHashMap in Zig 0.17.1 stores and finds keys: one metadata byte per slot with a 7-bit fingerprint, linear probing, growth at 80% full, Wyhash with seed 0, and tombstones that can make a lookup scan the whole table.