Introducing thetos (θετός, "placed, fixed"), a library of persistent immutable data structures for Nim. It's modeled on the C++ library immer.
Containers in thetos are value types backed by a 32-way trie: hash tries for maps and sets, radix-balanced trees for vectors. Copying is O(1) because copies share the whole trie. An update copies only the path to the change and shares the rest, so every older version stays valid.
Nodes use atomic reference counts and are never mutated while shared, so versions can be handed between threads without locks, under --mm:arc, --mm:orc or --mm:atomicArc! I've wanted this for a while and finally got around to having our new overlords err.. friendly helpers to make a library based on the design of immer.
A quick taste
Let's start with mutable-looking code using in-place operations on a var variable. Any copy you made earlier keeps its version:
import thetos
var m = toTrieMap({"one": 1})
let snapshot = m # O(1) copy
m["two"] = 2
m.del("one")
assert m.len == 1 and m["two"] == 2
assert snapshot.len == 1 and "one" in snapshot
var s = toTrieSet([1, 2])
s.incl 3
s.excl 1
assert s == toTrieSet([2, 3])
You can also use the functional style that returns the updated copy:
import thetos
var a = initTrieMap[string, int]()
a["one"] = 1 # in place: only this variable changes
let b = a.put("two", 2) # functional update; `a` is unchanged
assert a.len == 1 and b.len == 2
var v = toTrieVec([1, 2, 3])
let w = v.pushBack(4)
v[0] = 10
assert w[0] == 1 # `w` still sees the old element
Easy cross-thread shared editing and reading:
let config = newAtomRef(toTrieMap({"mode": "fast"}))
let handle = config # O(1) copy; both share one atom
handle.updateIt(it.put("mode", "safe"))
assert config.load()["mode"] == "safe" # every holder sees the update
What's included
TrieMap[K, V] and TrieSet[T]: hash map and set (CHAMP tries, 32-way).TrieVec[T]: indexed vector with O(log₃₂ n) indexing and amortized O(1) appends.FlexVec[T]: a relaxed radix-balanced (RRB) vector, after immer::flex_vector, adding O(log n) concatenation, slicing, drop, insert, erase and pushFront.Box[T]: one immutable value behind a reference count. copyWith and boxAccessors make a boxed plain object work as an immutable record.Atom[T] and AtomRef[T]: lock-free cells for publishing new versions between threads. AtomRef is a copyable handle to a shared atom.diff(a, b) for maps and sets: lists added, removed and changed entries, skipping every subtree the two versions still share. Comparing a version with one derived from it costs time proportional to the number of changes.
Convenience extras include updateIt templates in the style of mapIt (m.updateIt("hits", it + 1)), and non-raising get (returning an Option) and getOrDefault for maps, vectors and boxes.
Note that I've used both Claude Opus 5.5 and OpenAI Astra/Sol to review the code several times fixing bugs and checking for concurrency issues. Given that it's also based on the designed of the well establied immer it should be ready to use. Issues and PRs welcome of course!
Sharing state between threads
import std/typedthreads
import thetos
var state: Atom[TrieMap[int, string]]
proc worker(id: int) {.thread.} =
for i in 0 ..< 1000:
state.updateIt(it.put(id * 1000 + i, $i))
var threads: array[4, Thread[int]]
for i in 0 ..< threads.len:
createThread(threads[i], worker, i)
joinThreads(threads)
assert state.load().len == 4000
Atom is lock-free. It uses split reference counting, so a reader can never see a value freed out from under it. load returns a snapshot that never changes, and update is a compare-and-swap loop. See also AtomRef[T].
Compile-time safety checks
Copying a Nim ref or closure under --mm:arc or --mm:orc changes a non-atomic reference count, so sharing one between threads is a data race. Atom checks its payload type at compile time, at any depth and including inside thetos containers. If the payload holds refs or closures and the build isn't --mm:atomicArc, the program doesn't compile.
When you don't need atomics
Atomic reference counts cost a little on every copy and update. For data that never leaves one thread, thetos/local provides the same containers with plain integer counts (local.TrieMap, local.TrieVec and so on). They are distinct types, so you can use them alongside the shared ones. On an Apple M3 Pro, plain counts made persistent updates of shared maps and sets about 20% faster. Atom rejects thread-local containers at compile time. A program built with --threads:off gets plain counts automatically.
Getting it
thetos requires Nim 2.2.12 or later. With either Atlas or Nimble:
atlas use https://github.com/elcritch/thetos
nimble install https://github.com/elcritch/thetos
CI runs the test suite under arc, orc and atomicArc on both amd64 and arm64 Linux. The suite includes randomized tests against the standard library containers, leak tracking, and multi-threaded stress tests of Atom.