CowBox

public struct CowBox[T] where T: Cloneable { /* private fields */ }

Copy-on-write wrapper around RcBox[T].

Mutable owners use CowBox; read-only shared owners (like StringSlice) hold the inner RcBox directly via shareBox(). The mutation protocol is write() → modify → setValue().

Examples

var box = CowBox(MyStorage()); var s = box.write(); // COW barrier — clones if shared s.len = s.len + 1; box.setValue(s); // write back

Representation

A single RcBox[T] field.

Memory Model

Same as RcBox: non-atomic refcount. Cloning bumps the count; write splits off a private copy when shared.

Associated Types

type Target = T

Initializers

public init(consuming T)

Allocates fresh storage holding value with refcount 1.

public init(inner: RcBox[T])

Adopts an existing RcBox without allocating.

Methods

public func isUnique() -> Bool

Returns true when no other clone shares this storage.

public mutating func modify[R]((T) -> R) -> R

In-place mutation barrier: ensures unique storage (deep-copying if shared), then passes the heap value to body as a mutating argument to mutate directly — no per-call clone or write-back. This is the O(1) replacement for the read() → modify → setValue() dance.

public func pointeeRef() -> &T
public func read() -> T

Read access — clones the value so the caller gets an independent copy. getValue() returns a raw bitwise copy from the heap; cloning ensures owned resources (byte buffers, etc.) are properly duplicated.

public func setValue(consuming T)

Writes value into the storage in place. Only valid after a preceding write() call (which ensures uniqueness). Takes value by consuming so the drop pass sees the caller's local as moved (Dead) — prevents double-free of shared buffers.

public func shareBox() -> RcBox[T]

Returns a shared RcBox pointing at the same storage (refcount bumped). Use this to hand read-only access to types like StringSlice.

public func valuePtr() -> Pointer[T]

Returns a pointer to the wrapped value on the heap, bypassing the clone that read() / getValue() would create. Use this to read individual scalar fields without triggering T.deinit.

public mutating func write() -> T

Write access — clones storage if shared, then returns the (now unique) value. Caller modifies and calls setValue.

ImplementsCloneable

Methods

public func clone() -> CowBox[T]

Shares storage with the returned clone (refcount bump).

ImplementsMutableIndirection

Methods

public mutating func pointeeMutRef() -> &mutating T

Defined in lang/std/memory/cowbox.ks