Learn · 11

Copy-on-Write Value Semantics

Understand Ochre's thread-safe Arc Copy-on-Write memory model, deep immutability, nested updates, and evaluate-once lvalue guarantees.

In many languages, assigning a list or struct copies a mutable reference: changing one variable silently mutates every other variable pointing to the same data. Ochre avoids aliasing bugs entirely by giving Lists, Maps, and Structs Copy-on-Write (CoW) value semantics.

How Copy-on-Write Works

Every List, Map, and Struct in Ochre is wrapped in an atomic reference-counted pointer (Arc<T>):

  1. Assigning or passing a value is O(1): let snapshot = items only increments the reference count — no data is copied.
  2. Unshared mutation is in-place: If items has a reference count of 1, mutating items[0] = 99 updates memory in place.
  3. Shared mutation clones transparently: If snapshot still holds a reference (refcount > 1), mutating items clones only the modified path so snapshot stays 100% intact.
struct Config {
    host: Str,
    port: Int,
}

fn main() {
    var base = Config { host: "localhost", port: 8080 }
    let prod = base
    base.port = 9090

    var matrix = [[1, 2], [3, 4]]
    let saved = matrix
    matrix[0][1] = 77

    println("base={base.port}, prod={prod.port}")
    println("matrix={matrix}")
    println("saved={saved}")
}

Expected Output

base=9090, prod=8080
matrix=[[1, 77], [3, 4]]
saved=[[1, 2], [3, 4]]

Evaluate-Once Guarantee on Nested Assignments

When you write a nested assignment or compound assignment like rows[row_idx()][col_idx()] += 5, Ochre evaluates every object and index expression exactly once before applying the Copy-on-Write write-back up to the root var:

fn pick_row() -> Int {
    println("pick_row called")
    return 0
}

fn pick_col() -> Int {
    println("pick_col called")
    return 1
}

fn main() {
    var rows = [[10, 20]]
    rows[pick_row()][pick_col()] += 5
    println("result={rows[0][1]}")
}

Expected Output

pick_row called
pick_col called
result=25

Deep Immutability on let Bindings

Copy-on-Write pairs with let to guarantee that immutable variables cannot be mutated at any nesting depth:

fn main() {
    let rows = [[1, 2], [3, 4]]
    rows[0][1] = 99
}

The compiler rejects this with cannot mutate immutable variable 'rows'.

Practical Use Case: Undo Stacks & Safe Concurrency

Because taking a snapshot (let prev = state) is O(1) and immutable, implementing undo/redo history or passing state into a spawn { ... } background task requires zero defensive cloning and carries zero risk of data races.

Exercise

Create a var board = [[0, 0], [0, 0]], take a let initial = board, update board[1][1] = 1, and verify with assert that board[1][1] == 1 while initial[1][1] == 0.

Show Solution
fn main() {
    var board = [[0, 0], [0, 0]]
    let initial = board
    board[1][1] = 1
    assert(board[1][1] == 1)
    assert(initial[1][1] == 0)
    println("board={board}, initial={initial}")
}