Changeable Sharing: Mutable<T>
Mutable lets a function modify data in place — updating the original array or object directly instead of returning a copy. It’s like Shared, but with write access.
Key benefits
- Change in place. A function can update an array or object without making and returning a duplicate — important on boards with little memory.
- Clear intent. Marking a parameter
Mutableis a readable signal that the function will change the data you pass it.
Safety Enforcements
Error: ownership-borrow-mismatch
You cannot pass an immutable Shared to a function that expects a Mutable. This prevents a “read-only” contract from being violated.
import { Owned, Mutable, Shared } from '@typecad/board';
function clear(buf: Mutable<Uint8Array>) {
buf.fill(0);
}
const data: Shared<Uint8Array> = new Uint8Array(4); // Immutable
clear(data); // ERROR: Cannot pass 'data' (immutable Shared) to 'clear' (Mutable).Lifetime and Scope
Just like Shared, a Mutable is a “borrow” and must not outlive its source.
Error: ownership-dangling-borrow
Occurs if a Mutable in an outer scope persists after the Owned source in an inner scope has been destroyed.
let saved: Mutable<number>;
{
let local: Owned<number> = 42;
saved = local; // ERROR: 'saved' borrows 'local' which goes out of scope.
}API Summary
| Feature | Description |
|---|---|
| Read/Write Access | Allows both reading and modifying the underlying data. |
| C++ Emission | Emits T& for complex types, ensuring in-place modification. |
| Zero-Copy | Shares the existing memory address without duplication. |
When to use Mutable vs Owned
- Use
Mutablewhen you want to modify a buffer that belongs to someone else (the caller). - Use
Ownedwhen you want to take full responsibility for the data (e.g., storing it in a global class instance or a task queue).
On This Page