cli: add safe owning deque standard module

Embed std.deque with eleven generic operations implemented entirely in
safe Aji over initialized Option<T> buffer slots. Bounded pushes and
moving pops work at both ends; full pushes, out-of-bounds replacements
and nonempty free return ownership to the caller. Explicit reserve
preserves order and all state on allocation failure, charges the old
and new slot capacities at the allocation peak, and rotates whole
values after successful growth. No AIR, verifier or runtime change.

Specify the visible representation invariant, tag-inclusive allocation
accounting and empty-only cleanup. Add RFC 0025, a runnable owning
example, source/CLI conformance and CI coverage. Complete STD-6c;
HashMap, HashSet and BinaryHeap remain STD-6d.

Validation: unit tests and 785 full conformance cases; 28 deque fixtures;
focused collection after every instruction and 12 schedule seeds over
four quanta; 136 source/package/hosted CLI checks; an independent Python
deque oracle for 128 operations and 71 small growth configurations;
93/93 source coverage; Zig formatting, staged whitespace and bundles.

Reference cost: full source excluding AIR grows 52,384 -> 53,993 cl100k
tokens (+3.1%); Quick Reference 7,667 -> 7,747 (+1.0%). AIR stays at
175,736 bytes. Construction/growth still incur interpreter prefix-copy
overhead; no native performance or empirical MCC benefit is claimed.
This commit is contained in:
dev committed 2026-10-07 00:08:42 +03:00
1 parent 4138a52af6
commit 93405f69ce
46 files changed
+1789 -7

No files matched your search

+2
View File
@@ -109,3 +109,5 @@ RFC 0022 explicit generics (cl100k, relative to modules): Quick Reference 6,501
RFC 0023 whole-value linear aggregates (cl100k, relative to generics): Quick Reference 6,948 → 7,225 (+4.0%); other source docs 41,086 → 42,364 (+3.1%); full source docs excluding AIR 48,034 → 49,589 (+3.2%). New on-demand `language/linear-aggregates.md` is 1,133 tokens; `library/std.md` is 8,398. AIR grows to 168,336 bytes (+4.7%). Whole unpack/exhaustive match/explicit swap/allocation failure expose ownership without per-field holes, cleanup or new transfer state. Cumulative source growth is approximately +45.9%; Quick Reference remains beyond its 4–6k target. RFC 0023 justifies the added contracts; consolidation remains separate work and no MCC improvement is claimed.
RFC 0024 initialized buffers and safe Vec (cl100k, relative to linear aggregates): Quick Reference 7,225 → 7,667 (+6.1%); other source docs 42,364 → 44,717 (+5.6%); full source excluding AIR 49,589 → 52,384 (+5.6%). New on-demand language/buffers.md is 1,175 tokens; library/std.md is 9,432. AIR grows to 175,736 bytes (+4.4%). Initialized prefixes, explicit reserve, returned failure ownership and empty-only free permit safe resource containers without per-slot verifier state. Cumulative full source growth is +54.2%, with the RFC's owner-review justification; Quick Reference consolidation remains separate work and no empirical MCC improvement is claimed.
RFC 0025 safe owning Deque (cl100k, relative to buffer/Vec): Quick Reference 7,667 → 7,747 (+1.0%); other source docs 44,717 → 46,246 (+3.4%); full source excluding AIR 52,384 → 53,993 (+3.1%). library/std.md is 10,961 tokens; AIR remains 175,736 bytes. Eleven generic safe functions reuse buffer/Option/exchange and existing ownership/borrow rules without semantic or verifier-state growth. Full ring invariants and accounting stay on demand; cumulative full-source growth is +58.9%, with the RFC's owner-review justification and no empirical MCC claim.
+2
View File
@@ -449,3 +449,5 @@ fn main(heap: cap<mem.alloc>) -> u64 effects [mem.alloc] {
`ref values = buffer.view(b);` / `mut values = buffer.view(b);` borrow only the prefix. A live child view/task loan blocks shape changes, even a no-op reserve. Read Copy elements; use value.swap to replace linear elements, consuming the returned old value. Full contracts: language/buffers.md.
Import `std.vec` for `Vec<T>` and new/len/capacity/reserve/push/pop/free/get/replace, each explicitly specialized `::<T>`. new/reserve require mem.alloc; push is bounded, get requires Copy, pop returns std.option.Option<T>. Failure variants retain ownership: full(item), out_of_bounds(item), not_empty(vector). Match move on linear results; import std.option to name its variants. Signatures: library/std.md. Inside a specialized generic body, `move name` also accepts complete Copy bindings and retains their availability; monomorphic Copy moves and moves of borrows still reject.
`std.deque` uses the same explicit allocation, returned-ownership and empty-only free contract, with push_front/push_back and pop_front/pop_back. Indices count from the front. Each capacity slot charges Option<T> (tag plus payload); reserve preserves order and needs old+new quota. It uses existing source primitives; signatures and representation invariants stay in library/std.md.
+1 -1
View File
@@ -8,7 +8,7 @@ The other files in `/docs` hold the full rules. Open one only when this page is
| Need | Read |
|---|---|
| built-in bytes/math/text/formatting, option/result and owning Vec, signatures and failure contracts | `/docs/library/std.md` |
| built-in bytes/math/text/formatting, option/result, owning Vec and Deque, signatures and failure contracts | `/docs/library/std.md` |
| initialized buffer storage, explicit growth/drain and child views | `/docs/language/buffers.md` |
| whole-value linear aggregates, unpack, exchange and allocation failure | `/docs/language/linear-aggregates.md` |
| generic declarations/applications, property constraints and specialization limits | `/docs/language/generics.md` |
+1 -1
View File
@@ -141,4 +141,4 @@ Lowering layers (P6A-3/4), each with accepted (golden AIR), rejected (`E7xxx`) a
| P6-9 | todo | Port reference programs and examples to `.aji` | P6-5 | `tests/programs/`, `examples/` | exit criterion passes |
| P6-10 | todo | Phase exit review | all | plan status | exit criterion passes |
The [standard-library track](standard-library.md) implements nine compiler-pinned modules and qualified standard enum names. STD-3/RFC 0021 completes P6-3 on the branch with explicit manifest source mapping, acyclic linking, direct qualified names, imported struct literals and task workers. Dependency fetching/resolution is separate package work; STD-4/RFC 0022 completes explicit generics and structural constraints on the branch. STD-5/RFC 0023 adds whole-value linear structs/enums/fixed arrays, complete unpack/match, explicit exchange and ownership-preserving allocation failure through all layers (spec 15 §16). STD-6a/b/RFC 0024 resolves Q-036 with initialized buffer<T> and safe std.vec, explicit growth, returned failure ownership and draining (spec 15 §17). Remaining collections are STD-6c. Existing `from`-returns remain unimplemented (Q-034). These increments do not complete Phase 6.
The [standard-library track](standard-library.md) implements ten compiler-pinned modules and qualified standard enum names. STD-3/RFC 0021 completes P6-3 on the branch with explicit manifest source mapping, acyclic linking, direct qualified names, imported struct literals and task workers. Dependency fetching/resolution is separate package work; STD-4/RFC 0022 completes explicit generics and structural constraints on the branch. STD-5/RFC 0023 adds whole-value linear structs/enums/fixed arrays, complete unpack/match, explicit exchange and ownership-preserving allocation failure through all layers (spec 15 §16). STD-6a/b/RFC 0024 resolves Q-036 with initialized buffer<T> and safe std.vec, explicit growth, returned failure ownership and draining (spec 15 §17). STD-6c/RFC 0025 adds safe owning Deque with existing source primitives. Remaining maps/sets/heaps are STD-6d. Existing `from`-returns remain unimplemented (Q-034). These increments do not complete Phase 6.
+8 -1
View File
@@ -56,7 +56,8 @@ SQL/database clients, Redis/Kafka, ORMs, application authentication, gRPC/protob
| STD-5 | done (branch implementation; RFC Proposed) | independent whole-value `linear_aggregates` RFC and vertical implementation phase | STD-3/4 for its source surface | spec → AIR → verifier → interpreter → source/lowering → Quick Reference → AIR/source tests; linear elements consumed on every path |
| STD-6a | done (branch implementation; RFC 0024 Proposed) | dynamic initialized buffer<T> storage/drain contract (Q-036) | STD-4/5 | vertical allocate/grow/push/pop/view/free; allocation failures preserve state, returned owners consumed; no hidden destruction |
| STD-6b | done (branch implementation; RFC 0024 Proposed) | safe std.vec for Copy/owners/files/channel endpoints | STD-6a | explicit reserve, bounded push, moving pop/replace, empty-only free; deterministic and failure/cleanup tests |
| STD-6c | todo | Deque, HashMap, HashSet, BinaryHeap | STD-6a/b | safe collection contracts, including HashMap<Key, Own<Value>>, recoverable failures and explicit draining |
| STD-6c | done (branch implementation; RFC 0025 Proposed) | safe std.deque for Copy/owners/files/endpoints | STD-6a/b | bounded ring, both ends, failure-preserving explicit growth, complete resource transfer and empty-only free |
| STD-6d | todo | HashMap, HashSet, BinaryHeap | STD-6a/b/c | safe collection contracts, including HashMap<Key, Own<Value>>, recoverable failures and explicit draining |
| STD-7 | todo | concrete I/O adapters, buffered I/O and lexical paths | STD-1b/2a/2b; STD-3 for public types | short reads, EOF, capacity and write failures covered; paths never grant filesystem authority |
| STD-8 | todo | filesystem gaps, args/env capability RFC, time/random distinctions and structured log | STD-3/7; vertical runtime feature where needed | CLI/storage milestone examples work in deterministic and hosted profiles; all authority is granted at entry |
| STD-9 | todo | independent integration application and API review | STD-6/7/8 | integration gate; public application is not private benchmark material |
@@ -123,3 +124,9 @@ The finite-layout E1003 check now traverses arrays, repairing a prior verifier g
RFC 0023 and spec 03 §25 implement whole-value linear structs/enums/fixed arrays vertically. Construction consumes nested owners; complete unpack, exhaustive match move, explicit exchange and own.pack failure preserve ownership on every normal path. Standard option/result accept owning payloads; observational classification helpers keep Copy constraints. Existing availability, alias/task-loan, Send/Share, budget and scheduler rules apply without per-field holes or hidden cleanup. No new diagnostic/effect/capability is introduced.
Source/AIR tests cover nested ownership, allocation success/failure, repeated exchange with a one-owner budget, enum replacement, borrowed fixed arrays, channels, tasks, mutexes, regions, atomics and rejected copies/leaks/aliases/recursive ownership. The interpreter preserves borrowed SSA identity across whole replacement and collection; individual own<array<T,N>> is distinguished from a repeated own_array allocation. RFC 0023 records final checks and documentation budgets. STD-6 starts with Q-036: dynamic storage, initialized length and explicit drain must be specified before growing resource collections. STD-5 does not complete Vec or Std 0.1.
## STD-6a/b/c verification
Initialized buffer<T> and safe Vec/Deque use existing ownership/borrow/task rules and deterministic allocation budgets. Deque is ordinary library source: Option<T> represents vacancy, both ends exchange complete elements, and explicit growth rotates a ring only after allocation succeeds. Nonempty free returns the queue, so no library action closes user resources. Slot charges include Option's enum tag. Ordinary visible representation fields have a documented invariant, with no unsafe bypass.
RFC 0024 records storage/Vec validation. RFC 0025 records the deque API/budget measurements and validation: independent Python deque traces, all small head/length combinations under growth, wrapped owners, files/senders/workers, failure/cleanup and borrow/constraint rejections. Maps/sets/heaps are STD-6d; this increment does not complete Std 0.1.
+21 -2
View File
@@ -1,8 +1,8 @@
# Standard library API
Normative contracts: spec 16. Import rules: spec 15 §13. These modules are bundled with the compiler, with no external source dependencies. Allocation authority is explicit for std.vec new/reserve.
Normative contracts: spec 16. Import rules: spec 15 §13. These modules are bundled with the compiler, with no external source dependencies. Allocation authority is explicit for std.vec/std.deque new/reserve.
Except std.vec new/reserve, functions below declare `effects []`, allocate no heap memory and retain no borrows. Pass arrays/slices using explicit `ref` or `mut`. Names are fully qualified; no alias or short-name import exists.
Except std.vec/std.deque new/reserve, functions below declare `effects []`, allocate no heap memory and retain no borrows. Pass arrays/slices using explicit `ref` or `mut`. Names are fully qualified; no alias or short-name import exists.
| Module | Function signature | Result/failure |
|---|---|---|
@@ -244,3 +244,22 @@ Import std.vec; every function supplies explicit `::<T>`. Vec<T> contains a buff
| replace<T> | value: mut<Vec<T>>, index: usize, item: T | ReplaceResult<T>: ok(old_value: T) / out_of_bounds(original_item: T) |
Growth has an old+new capacity allocation peak. Failure preserves capacity/length/elements; full push and out-of-bounds replacement return the exact input. Nonempty free returns the vector; pop/consume all elements before retrying. get returns none out of bounds, replace returns the old complete element on success. Generic moves compose Copy and linear types. Qualified variants require direct imports (including std.option for pop/get). [Executable owning vector](../../examples/std/vector.aji) returns 42 with heap=mem.alloc:256. Views and nested element borrows cannot escape or overlap shape changes. Normative contracts: spec 16 §2.10 and spec 03 §26.
## Owning deques
Import std.deque; every operation supplies `::<T>`. Deque<T> is always linear and has bounded ring capacity. Pop transfers complete values. No operation grows except explicit reserve. New/reserve declare mem.alloc and take explicit authority; all others declare effects [].
| Function | Parameters | Result |
|---|---|---|
| new<T> | capacity: usize, heap: cap<mem.alloc> | NewResult<T>: ok(Deque<T>) / err(alloc_error) |
| len<T> / capacity<T> | value: ref<Deque<T>> | usize |
| reserve<T> | value: mut<Deque<T>>, capacity: usize, heap: cap<mem.alloc> | ReserveResult: ok / err(alloc_error) |
| push_front<T> / push_back<T> | value: mut<Deque<T>>, item: T | PushResult<T>: ok / full(original_item: T) |
| pop_front<T> / pop_back<T> | value: mut<Deque<T>> | std.option.Option<T>: some(T) / none |
| free<T> | value: Deque<T> | FreeResult<T>: ok / not_empty(Deque<T>) |
| get<T: Copy> | value: ref<Deque<T>>, index: usize | std.option.Option<T>: some(T) / none |
| replace<T> | value: mut<Deque<T>>, index: usize, item: T | ReplaceResult<T>: ok(old_item: T) / out_of_bounds(original_item: T) |
Indices count from the front. Full pushes, out-of-bounds replaces and nonempty free preserve the queue and return ownership. Allocation failure also preserves physical slots/head/length. Successful growth preserves logical order, resets head and charges the old+new capacities at the peak; no shrink occurs. Every slot is an Option<T> (tag plus payload), including free slots: capacity 3 of own<u64> charges 27 bytes. Empty free explicitly drains internal none slots; it never destroys a user's T. Callers pop and consume resources before freeing; match move on linear result values and import std.option to name pop/get variants.
End operations and indexing use constant slot work; construction/growth/free use O(capacity) work. Interpreter representation costs remain those of buffer primitives. Deque<T> fields are ordinarily visible; direct representation writes/construction must preserve spec 16 §2.11's ring invariant. Library calls maintain it. [Executable owning deque](../../examples/std/deque.aji) returns 42 with heap=mem.alloc:1024. There is no iterator, returned borrow, trait hierarchy or implicit allocation/cleanup. Existing alias, task-loan and Copy/Send/Share checks apply.
+50
View File
@@ -0,0 +1,50 @@
# RFC 0025: Safe owning deque
Status: Proposed
Scope: STD-6c deque increment, ordinary safe library source
## Decision and invariant
Spec 16 §2.11 defines one deque API using the existing initialized buffer and Option<T>. A ring has capacity initialized option slots, a head and a logical length. Exactly the occupied ring range contains some; all other slots contain none. This represents vacancy with complete values, preserving whole-value ownership without holes or new primitives. Representation fields remain ordinarily visible; manual construction/mutation must preserve the documented invariant.
Eleven functions cover construction, metadata, explicit reserve, both ends, moving pop, empty-only free, Copy get and complete replace. Push never grows. Full push/out-of-bounds replace return the input; nonempty free returns the whole queue. Allocation failure preserves physical slots and metadata. Successful growth charges old+new capacity, fills new none slots, rotates old slots using complete exchanges and resets head without changing order. Index calculations avoid head+offset overflow. No destructor closes user resources.
## Verifier and runtime rules
Existing complete aggregate/enum moves and value.swap preserve exactly one owner per element. Borrow scopes, task loans, Send/Share and Copy constraints apply without special cases. The library never returns a borrow. Only new/reserve require explicit mem.alloc effect/capability; vacancy slots include the Option tag in their charge. The deterministic interpreter executes ordinary AIR with existing budgets/fuel; no opcode/runtime/feature or synchronization change is needed. Existing E7003/E2002/E3002/E2101/E4101/E7005 diagnostics cover bad moves, leaks, aliases, task loans and constraints. Valid calls are trap-free except execution limits; malformed manually modified representations have no weakened verifier or safety rules. Existing source/AIR/API semantics remain compatible.
## Examples and validation
The runnable deque example pushes a front/back owner, pops in FIFO order, explicitly consumes each owner and frees the empty queue. Rejected examples omit a move/cleanup, duplicate ownership, call Copy get with an owner or retain a borrow/task loan across mutation. Fixtures independently model ring order, wrapped growth, full/empty/zero capacity, repeated reuse, success/error budget release, files and channel endpoints. New/reserve charge Option<T> slots; tests must not assume Vec's T-only accounting. Ordinary unit/conformance, collection/schedule stress for deque cases, CLI canonical lowering/manifest/hosted checks and reference bundle checks accompany the implementation.
## Agent complexity impact
New language concepts, syntax, instructions, verifier state and diagnostics: none. Library concepts: two ends and the documented ring invariant. The API reuses Vec's returned-ownership naming, effects and explicit specialization; no overload/trait/reflection or implicit allocation/destruction is introduced. Existing primitives suffice. Full API/contracts live in the on-demand library page rather than another long Quick Reference tutorial. Measured Quick/Source/AIR bundle costs and final validation follow; no empirical MCC benefit is claimed. This increment completes STD-6c deque; maps/sets/heaps remain STD-6d and Std 0.1 is not complete.
The checked [owning example](../../examples/std/deque.aji) uses only safe ordinary source. This call rejects E7003 because a named owner must move:
```aji
fn bad(q: mut<std.deque.Deque<own<u64>>>, item: own<u64>) -> void effects [] {
let result = std.deque.push_back::<own<u64>>(q, item);
trap;
}
```
### Reference bundle measurement
Relative to STD-6a/b, with the repository's three tokenizers:
| Bundle | cl100k before → after | o200k before → after | Qwen2.5 before → after |
|---|---:|---:|---:|
| Quick Reference | 7,667 → 7,747 | 7,697 → 7,778 | 7,902 → 7,982 |
| Other source docs | 44,717 → 46,246 | 44,850 → 46,376 | 45,932 → 47,467 |
| Full source excluding AIR | 52,384 → 53,993 | 52,547 → 54,154 | 53,834 → 55,449 |
| AIR reference in source bundle | 45,520 → 45,520 | 45,667 → 45,667 | 46,981 → 46,981 |
The library page is 10,961 cl100k tokens; standalone AIR remains 175,736 bytes / 19 files / 50 sections. Full source growth is +3.1% relative to buffer/Vec, +58.9% since the 33,981-token pre-stdlib baseline. Quick Reference adds one short paragraph (+1.0%) rather than a new tutorial; the full ring invariant/API/accounting lives on demand. Cumulative growth and the existing front-door target overrun remain for owner review. This cost is justified by a resource-safe reusable ring using existing verifier-visible operations; documentation growth itself proves no compression benefit. No held-out corpus or task-specific semantic change was used.
### Checked implementation
Eleven generic functions and five result enums use only existing safe source/AIR. The interpreter/backend/verifier are unchanged; the compiler embeds one extra source module. Independent Python deque vectors exercise 128 operations over four seeds with every logical element checked; growth covers all 71 small capacity/head/length combinations including empty/full/wrapped queues. Owners, files, senders, shared workers, failure ownership, cross-authority refunds and tag-inclusive quota checks pass. Invalid caller metadata cannot make free normally discard a nested owner. Borrow/task/Copy/move/leak rejections have stable existing codes.
Validation passed full unit/conformance, focused per-instruction collection and 12-seed schedule stress (four quanta), canonical source/AIR and package/hosted CLI checks, source coverage, independent oracle checks, Zig formatting and reference bundle generation. Final counts are recorded in the commit. No native performance claim is made; construction/growth retains the interpreter's prefix-copy overhead.
+25 -2
View File
@@ -10,7 +10,7 @@ APIs SHOULD offer one canonical operation for a common need, small documentation
## 2. Bootstrap module registry
The built-in registry contains `std.bytes`, `std.encoding.base64`, `std.encoding.hex`, `std.fmt`, `std.math`, `std.option`, `std.result`, `std.utf8` and `std.vec`. They are implemented in safe `.aji`; their stable source paths are `std/bytes.aji`, `std/encoding/base64.aji`, `std/encoding/hex.aji`, `std/fmt.aji`, `std/math.aji`, `std/option.aji`, `std/result.aji`, `std/utf8.aji` and `std/vec.aji`, respectively. Spec 15 §13 defines imports; the reference API tables are in `reference/std.md`. All operations are deterministic in every profile and have no concurrency effects. Modules other than std.vec declare effects [] and allocate no heap memory. std.vec new/reserve declare mem.alloc and require explicit allocation authority (§2.10); its other functions allocate no heap. Ordinary interpreter fuel limits apply.
The built-in registry contains `std.bytes`, `std.encoding.base64`, `std.encoding.hex`, `std.fmt`, `std.math`, `std.option`, `std.result`, `std.utf8`, `std.vec` and `std.deque`. They are implemented in safe `.aji`; their stable source paths are `std/bytes.aji`, `std/encoding/base64.aji`, `std/encoding/hex.aji`, `std/fmt.aji`, `std/math.aji`, `std/option.aji`, `std/result.aji`, `std/utf8.aji`, `std/vec.aji` and `std/deque.aji`, respectively. Spec 15 §13 defines imports; the reference API tables are in `reference/std.md`. All operations are deterministic in every profile and have no concurrency effects. Modules other than std.vec/std.deque declare effects [] and allocate no heap memory. std.vec/std.deque new/reserve declare mem.alloc and require explicit allocation authority (§2.10–§2.11); their other functions allocate no heap. Ordinary interpreter fuel limits apply.
### 2.1 `std.math`
@@ -160,4 +160,27 @@ Public functions use explicit `::<T>` specialization: new<T>(capacity:usize,heap
These are safe `.aji` wrappers over spec 03 §26. new chooses exact initial capacity, reserve chooses a minimum capacity without shrinking, and push never grows implicitly. len/capacity observe initialized length/backing capacity. pop removes the last complete value, returning none for empty. A full push returns the original item. get copies an in-bounds Copy item or returns none. replace exchanges an in-bounds initialized element and returns the previous item; out_of_bounds returns the original supplied item and preserves the vector. free releases only an empty vector; otherwise it returns the same vector. Returned owning result specializations need exhaustive match move; Copy results use ordinary matching. Callers drain and explicitly consume resource payloads before freeing.
Capacity/allocation failure, alias/task exclusion, deterministic profiles and diagnostics are those of buffer primitives and ordinary enum/call rules. Valid complete values include owners/files/endpoints; no collection bypasses Send/Share or channel_transfer gates. Imports grant no authority. Deque/HashMap/HashSet/BinaryHeap, owning strings and general borrowed function returns remain separate increments of STD-6.
Capacity/allocation failure, alias/task exclusion, deterministic profiles and diagnostics are those of buffer primitives and ordinary enum/call rules. Valid complete values include owners/files/endpoints; no collection bypasses Send/Share or channel_transfer gates. Imports grant no authority. HashMap/HashSet/BinaryHeap, owning strings and general borrowed function returns remain separate increments of STD-6.
### 2.11 Explicit owning deques
The compiler-pinned registry MUST include safe `std.deque` (`std/deque.aji`). Its ordinary type is `Deque<T> { storage: buffer<std.option.Option<T>>, head: usize, length: usize }`, always linear. It exports `NewResult<T> { ok(Deque<T>), err(alloc_error) }`, `PushResult<T> { ok, full(T) }`, `ReserveResult { ok, err(alloc_error) }`, `FreeResult<T> { ok, not_empty(Deque<T>) }` and `ReplaceResult<T> { ok(T), out_of_bounds(T) }`.
For a valid deque of capacity C, the backing buffer MUST have C initialized Option<T> slots. For C=0, head=length=0; otherwise head<C and length≤C, with head=0 when empty. Logical element i (0≤i<length) occupies `(head+i) mod C`; precisely those slots contain some(T), every other slot contains none. Each linear element is owned exactly once. Algorithms MUST compute indices without intermediate usize overflow. Fields follow ordinary source visibility: callers constructing or modifying the representation MUST preserve this invariant. Library operations preserve it; ordinary traps/bounds/ownership checks still apply to invalid caller representations, with no unsafe exemption or promise to validate the entire invariant on every call.
Every function supplies explicit `::<T>` specialization:
| Function | Parameters | Result / contract |
|---|---|---|
| new<T> | capacity: usize, heap: cap<mem.alloc> | NewResult<T>; exact capacity, empty queue |
| len<T> / capacity<T> | value: ref<Deque<T>> | usize; logical length / capacity |
| reserve<T> | value: mut<Deque<T>>, capacity: usize, heap: cap<mem.alloc> | ReserveResult; no shrink; successful growth preserves logical order and sets head=0 |
| push_front<T> / push_back<T> | value: mut<Deque<T>>, item: T | PushResult<T>; insert at selected end, or full(original_item) with entire deque unchanged |
| pop_front<T> / pop_back<T> | value: mut<Deque<T>> | std.option.Option<T>; remove/move selected end, or none with empty deque unchanged |
| free<T> | value: Deque<T> | FreeResult<T>; empty frees all backing storage; nonempty returns same deque unchanged |
| get<T: Copy> | value: ref<Deque<T>>, index: usize | std.option.Option<T>; copy logical element, or none out of bounds |
| replace<T> | value: mut<Deque<T>>, index: usize, item: T | ReplaceResult<T>; return old logical element after complete exchange, or out_of_bounds(original_item) without mutation |
Only new/reserve declare effects [mem.alloc] and require cap<mem.alloc>. Each slot charges accounted_size(Option<T>) (the enum tag plus its largest payload), including free none slots. Growth uses buffer.reserve's old+new allocation peak; an allocation error MUST preserve head, length, capacity, every slot and ownership. After successful allocation the library initializes new slots to none and rotates the old ring using complete value.swap operations, with no second allocation. Requests≤C succeed without mutation. New/growth perform O(capacity) slot work; end operations, get/replace and metadata use constant slot work; freeing an empty deque drains its none slots in O(capacity). These are library slot-operation counts; the reference interpreter currently copies the initialized prefix in buffer.push, so construction/growth can have higher host cost. No native backend performance guarantee is added. Fuel exhaustion/traps are abnormal execution outcomes, outside returned-error preservation guarantees.
A full push and out-of-bounds replace return the exact original item. Callers MUST consume returned linear payloads. A nonempty free MUST NOT pop, close or destroy user elements; callers pop/consume all elements first. Empty free explicitly consumes only internal none slots before freeing its buffer. Ownership never escapes through a borrowed result. Valid calls add no program trap beyond the environment's execution limits. Existing linear availability, borrow/task-loan, bounds, generic Copy/Send/Share, effects and allocation rules verify the library as ordinary source; no new verifier state, AIR feature/opcode, runtime primitive, diagnostic, effect or authority is added. AIR format 0 and existing APIs retain meaning. Owners, files and channel endpoints follow the same rules as Vec; map/set/heap collections remain separate work.