On this page

0041. Vector append guarantee

Context

Vectors are immutable values (ADR-0040), yet accumulating with v = v.push(x) must not copy the vector each time. The guarantee has to survive record fields and helper calls, where uniqueness is hard to prove statically.

Decision

v.push(x) returns a new vec<T>; a discarded result is E0711. A buffer with cap != 0 stores a used-length word before its data, as for strings (ADR-0038). Push extends in place only when the buffer lies in the destination region, used == len and there is room; otherwise it copies into a buffer of max(2 * len, 8) in the destination region. Stale snapshots and forks fail the check and copy; views and vector literals have cap zero. The region test compares the address with the destination arena, from the scope's mark up. Ret has no mark in the callee, so it tests the arena alone, and a ret arena shared with an older frame by colour wrap-around can still extend; that costs a copy, never soundness. So uniquely held accumulators are amortized O(1), in locals, record fields and helpers, without any uniqueness analysis, and all values stay correct.

Regions keep push sound and linear:

The plan's hrt_vec_push(region, &tmp, sizeof(T), f, l, c), now with the mark after the region, returns the new slot and the caller writes the item, so Push is emitted as statements. The interpreter has no regions: it models the used-length check only, and Promote remains identity there. Outputs cannot differ, since copying is always a legal result of the check.

Alternatives considered

Consequences

A copy on a failed check goes to the destination region and is not reclaimed before that region ends. A push into a younger region, such as a scratch probe or a read-only helper, therefore costs O(n) time and is freed with its region, and the accumulator keeps its tip and its O(1) appends. A probe cannot be cheaper: while it lives, it and the next append both need the slot after len.

A push into the base's own region whose result dies still advances used, so alternating such a transient fork with an append is O(n) per pair and each copy is retained in that region, bounded by HRT_MEMORY_LIMIT. Replaced items stay until their region ends, like other carry garbage (ADR-0037). vec<str> elements cost 24 bytes each.

The tip rule does not authorize in-place set: equal-length snapshots share existing slots. ADR-0040's separate, conservative whole-function no-alias proof alone permits direct local self-set reuse; forks still copy.