Merge feat/roadmap-p1-wave4a: P1 Algorithms, Unicode, and Async execution foundations

This commit is contained in:
faumaray committed 2026-11-24 03:53:02 +03:00
commit 2e5d1ef5e5
24 files changed
+5154 -10

No files matched your search

+29 -6
View File
@@ -1,8 +1,8 @@
# Workflow state # Workflow state
Updated: 2026-11-24. Updated: 2026-11-24.
Repository: VoidLibrary; active branch `feat/roadmap-p0-p1-foundations` (from `main` Repository: VoidLibrary; active branch `feat/roadmap-p1-wave4a` (from `main`
at `f1f9ba375b22abf1adcc7c550ec21ac20895c0a4`). at `5754a7f`, merged Waves 1–3 from `feat/roadmap-p0-p1-foundations`).
## Completed objective ## Completed objective
@@ -124,9 +124,32 @@ pushing to remote) while leaving local untracked files untouched.
`containers_lru_get_put` 20.59 ns, `binary_reader_u64_be` 1.31 ns, `containers_lru_get_put` 20.59 ns, `binary_reader_u64_be` 1.31 ns,
`data_json_parse_small_object` 325.73 ns, `data_json_serialize_small_object` 164.76 ns. `data_json_parse_small_object` 325.73 ns, `data_json_serialize_small_object` 164.76 ns.
## Verification already observed (Wave 4A — P1 Algorithms, Unicode, Async)
- Standalone `Algorithms;Testing` (`-Werror`, `/tmp/void-w4a-alg`, `bfd6246`): `Graph`
4/4 passed (64.2ms); `ctest` 2/2 passed (including `AlgorithmsOnly` installed consumer).
- Standalone `Unicode;Testing` (`-Werror`, `/tmp/void-w4a-unicode`, `4369fde`): `Utf`
4/4 passed (0.3ms); `ctest` 2/2 passed (including `UnicodeOnly` installed consumer).
- Standalone `Async;Testing` (`-Werror`, `/tmp/void-w4a-async`, `c75056f`):
`OperationScope*|Executor*|Coro*` 28/28 passed (4.1ms); `ctest` 2/2 passed.
- Debug TSan subset (`Async;Testing`, `/tmp/void-w4a-async-tsan`, `c75056f`):
`OperationScope*|Executor*|ThreadPool*` 20/20 passed (34.6ms), 0 TSan races.
- Full RelWithDebInfo + `-DVOID_WARNINGS_AS_ERRORS=ON` (`/tmp/void-w4a-full`, 31 modules,
`c75056f`): `VoidTests` 1,345 tests — 1,342 passed, 3 intentional skips
(`plugin_load_and_query_skipped`, `broken_feature`, `unquoted_skip`), 0 failed (3.75s);
`ctest` 2/2 passed (`VoidTests` 3.77s, `VoidInstalledComponentConsumers` 14.45s, total
18.21s).
- Full Debug ASan + UBSan + `-DVOID_WARNINGS_AS_ERRORS=ON` (`/tmp/void-w4a-asan`, 31 modules,
`c75056f`): `VoidTests` 1,345 tests — 1,342 passed, 3 skipped, 0 failed (11.00s), 0 leaks,
0 UB.
- `VoidFoundationBench` post-W4A (`rev=c75056fe0707`, `/tmp/void-w4a-full/post-w4a.json`):
`harness_empty_loop` 0.39 ns, `core_uuid_parse_hyphenated` 25.48 ns,
`core_uuid_to_string` 17.09 ns, `containers_spsc_ring_push_pop` 9.16 ns,
`containers_lru_get_put` 21.81 ns, `binary_reader_u64_be` 1.36 ns,
`data_json_parse_small_object` 319.83 ns, `data_json_serialize_small_object` 168.13 ns.
## Ownership and next step ## Ownership and next step
Waves 1–3 (`P0`, `P1 Gate 1`, and `P1 Text/Containers/Binary/Data`) are complete and Waves 1–4A (`P0`, `P1 Gate 1`, `P1 Text/Containers/Binary/Data`, and `P1 Algorithms/Unicode/Async`)
verified on `feat/roadmap-p0-p1-foundations` and ready to merge locally into `main`, are complete and verified on `feat/roadmap-p1-wave4a` and ready to merge locally into `main`,
before planning and executing Wave 4 (`Algorithms`, `Unicode`, `Async`, `IO`, `Runtime`, before planning and executing Wave 4B (`IO`, `Runtime`, `Testing` P1).
`Testing`).
+8
View File
@@ -43,6 +43,14 @@ These tasks author plans. Future feature task IDs inside those plans remain plan
| M-BINARY-02, M-BINARY-03 | `Budget.hpp`, `Writer.hpp`, `ByteBuffer.hpp`, upgraded `Reader.hpp`, expanded `Binary` consumer (`eacb8a4`) | [M-BINARY-02-03](tasks/M-BINARY-02-03.md) | VERIFIED | `Reader` 4/4, `Writer` 2/2, `ByteBuffer` 1/1 passed; `VoidInstalledComponentConsumers` (`Binary`, `RelocatedBinary`) passed | | M-BINARY-02, M-BINARY-03 | `Budget.hpp`, `Writer.hpp`, `ByteBuffer.hpp`, upgraded `Reader.hpp`, expanded `Binary` consumer (`eacb8a4`) | [M-BINARY-02-03](tasks/M-BINARY-02-03.md) | VERIFIED | `Reader` 4/4, `Writer` 2/2, `ByteBuffer` 1/1 passed; `VoidInstalledComponentConsumers` (`Binary`, `RelocatedBinary`) passed |
| M-DATA-02 | Exact `int64`/`uint64` JSON numbers, `number_as`, strict parser, exact `operator==`, `try_serialize`, SAX `on_int`/`on_uint`, exact reflection/config (`692f5ba`) | [M-DATA-02](tasks/M-DATA-02.md) | VERIFIED | `Json` 34/34, `Reflect` 14/14, `StrictJson` 3/3, `Update` 22/22, `Config` 12/12 passed in full RelWithDebInfo & ASan+UBSan | | M-DATA-02 | Exact `int64`/`uint64` JSON numbers, `number_as`, strict parser, exact `operator==`, `try_serialize`, SAX `on_int`/`on_uint`, exact reflection/config (`692f5ba`) | [M-DATA-02](tasks/M-DATA-02.md) | VERIFIED | `Json` 34/34, `Reflect` 14/14, `StrictJson` 3/3, `Update` 22/22, `Config` 12/12 passed in full RelWithDebInfo & ASan+UBSan |
## Wave 4A — P1 Algorithms, Unicode, Async (`feat/roadmap-p1-wave4a`)
| ID | Deliverable | Spec | State | Verification summary |
| --- | --- | --- | --- | --- |
| S-ALGORITHMS-02 | `src/Algorithms/module.cmake`, `Graph.hpp` (`WorkLimits`, `IndexedGraphView`, `HasVersionStamp`, `AdjacencyView`, iterative `bfs`/`dfs`/`shortest_path_unweighted`/`topological_order` + cycle witness), `AlgorithmsOnly` consumer (`bfd6246`) | [S-ALGORITHMS-02](tasks/S-ALGORITHMS-02.md) | VERIFIED | `Graph` 4/4 and `AlgorithmsOnly` passed in `Algorithms;Testing`, full RelWithDebInfo (1,342 ✔), & ASan+UBSan (0 leaks/UB) |
| S-UNICODE-01, S-UNICODE-02 | `src/Unicode/module.cmake`, `MANIFEST.md` (Unicode 17.0.0), `Utf.hpp` (`data_version`, `Scalar`, `UtfPolicy`, strict/one-unit-repair codecs, `_into` span transcoders, `Utf8StreamDecoder`/`Utf16StreamDecoder`), `UnicodeOnly` consumer (`4369fde`) | [S-UNICODE-01-02](tasks/S-UNICODE-01-02.md) | VERIFIED | `Utf` 4/4 and `UnicodeOnly` passed in `Unicode;Testing`, full RelWithDebInfo (1,342 ✔), & ASan+UBSan (0 leaks/UB) |
| M-ASYNC-02, M-ASYNC-03 | `src/Async/module.cmake` (`INTERNAL_DEPS Functional Time LogState`), `Detail/Types.hpp`, `Operation.hpp` (`ResumeTicket`, `OperationState`), upgraded `Executor.hpp` (`try_post`, `post_completion`, bounded `ManualExecutor`, clock/stop `schedule_on`), `TaskScope.hpp` (`TaskScope`, `JoinHandle`, `DetachedOwner`) (`c75056f`) | [M-ASYNC-02-03](tasks/M-ASYNC-02-03.md) | VERIFIED | `OperationScope*|Executor*|Coro*` 28/28, Debug TSan 20/20 (0 races), full RelWithDebInfo (1,342 ✔), & ASan+UBSan (0 leaks/UB) |
All workers share the checkout and have disjoint file ownership defined in their All workers share the checkout and have disjoint file ownership defined in their
persisted task specifications. Root owns all cross-cutting files and resolves contract persisted task specifications. Root owns all cross-cutting files and resolves contract
changes. No worker owns application code, build files, existing docs/short-url.md, or Git changes. No worker owns application code, build files, existing docs/short-url.md, or Git
+13
View File
@@ -188,3 +188,16 @@ Branch: `feat/roadmap-p0-p1-foundations`. Toolchain via `dev cpp-gcc`: GCC 16.2.
| Full Integrated ASan+UBSan (`692f5ba`) | `dev cpp-gcc -p libarchive -p openssl -p sqlite -p libsodium` Debug (`-DVOID_ENABLE_ASAN=ON -DVOID_ENABLE_UBSAN=ON -DVOID_WARNINGS_AS_ERRORS=ON`), `ASAN_OPTIONS=detect_leaks=1:halt_on_error=1 UBSAN_OPTIONS=print_stacktrace=1:halt_on_error=1 /tmp/void-w3-asan/tests/VoidTests` | 1,332 tests — 1,329 passed, 3 skipped, 0 failed (10.83s), 0 leaks, 0 UB | | Full Integrated ASan+UBSan (`692f5ba`) | `dev cpp-gcc -p libarchive -p openssl -p sqlite -p libsodium` Debug (`-DVOID_ENABLE_ASAN=ON -DVOID_ENABLE_UBSAN=ON -DVOID_WARNINGS_AS_ERRORS=ON`), `ASAN_OPTIONS=detect_leaks=1:halt_on_error=1 UBSAN_OPTIONS=print_stacktrace=1:halt_on_error=1 /tmp/void-w3-asan/tests/VoidTests` | 1,332 tests — 1,329 passed, 3 skipped, 0 failed (10.83s), 0 leaks, 0 UB |
| Wave 3 TSan Subset (`692f5ba`) | `dev cpp-gcc -c` Debug (`Containers;Async;Time;Testing`, `-DVOID_ENABLE_TSAN=ON -DVOID_WARNINGS_AS_ERRORS=ON`), `/tmp/void-w3-tsan/tests/VoidTests --filter "Ring*\|Pool*\|BufferPool*\|Clock*\|Stopwatch*"` | 67/67 passed (69.8ms), 0 TSan races (`ThreadPool` 7, `ThreadPoolBackpressure` 2, `BufferPoolTests` 8, `Pool` 13, `Ring` 15, `BlockPool` 2, `Clock` 6, `Stopwatch` 14) | | Wave 3 TSan Subset (`692f5ba`) | `dev cpp-gcc -c` Debug (`Containers;Async;Time;Testing`, `-DVOID_ENABLE_TSAN=ON -DVOID_WARNINGS_AS_ERRORS=ON`), `/tmp/void-w3-tsan/tests/VoidTests --filter "Ring*\|Pool*\|BufferPool*\|Clock*\|Stopwatch*"` | 67/67 passed (69.8ms), 0 TSan races (`ThreadPool` 7, `ThreadPoolBackpressure` 2, `BufferPoolTests` 8, `Pool` 13, `Ring` 15, `BlockPool` 2, `Clock` 6, `Stopwatch` 14) |
| Post-W3 Benchmark (`692f5ba`) | `/tmp/void-w3-full/benchmarks/VoidFoundationBench --json /tmp/void-w3-full/post-w3.json` (RelWithDebInfo, warmup=5, reps=20, ops=10000) | Medians: `harness_empty_loop` 0.39ns, `core_uuid_parse_hyphenated` 24.94ns, `core_uuid_to_string` 16.88ns, `core_hash_fnv1a64_256b` 181.90ns, `core_hash_murmur3_256b` 68.26ns, `functional_result_ok_chain` 1.13ns, `functional_error_with_context` 58.86ns, `math_checked_add_loop` 0.47ns, `containers_spsc_ring_push_pop` 8.85ns, `containers_lru_get_put` 20.59ns, `binary_reader_u64_be` 1.31ns, `data_json_parse_small_object` 325.73ns, `data_json_serialize_small_object` 164.76ns | | Post-W3 Benchmark (`692f5ba`) | `/tmp/void-w3-full/benchmarks/VoidFoundationBench --json /tmp/void-w3-full/post-w3.json` (RelWithDebInfo, warmup=5, reps=20, ops=10000) | Medians: `harness_empty_loop` 0.39ns, `core_uuid_parse_hyphenated` 24.94ns, `core_uuid_to_string` 16.88ns, `core_hash_fnv1a64_256b` 181.90ns, `core_hash_murmur3_256b` 68.26ns, `functional_result_ok_chain` 1.13ns, `functional_error_with_context` 58.86ns, `math_checked_add_loop` 0.47ns, `containers_spsc_ring_push_pop` 8.85ns, `containers_lru_get_put` 20.59ns, `binary_reader_u64_be` 1.31ns, `data_json_parse_small_object` 325.73ns, `data_json_serialize_small_object` 164.76ns |
## Wave 4A / P1 Algorithms, Unicode, Async Verification (2026-11-24)
Branch: `feat/roadmap-p1-wave4a` (branched from `main` at `5754a7f`). Toolchain via `dev cpp-gcc`: GCC 16.2.0, CMake 4.4.4, Ninja 1.13.2.
| Scope | Command & configuration | Observed outcome |
| --- | --- | --- |
| S-ALGORITHMS-02 (`bfd6246`) | `Algorithms;Testing` RelWithDebInfo `-DVOID_WARNINGS_AS_ERRORS=ON` `/tmp/void-w4a-alg` (`VoidTests --filter "Graph*"` & `ctest`) | `Graph` 4/4 passed (64.2ms); `ctest` 2/2 passed (`VoidTests` 0.17s, `VoidInstalledComponentConsumers` including `AlgorithmsOnly` 2.55s) |
| S-UNICODE-01..02 (`4369fde`) | `Unicode;Testing` RelWithDebInfo `-DVOID_WARNINGS_AS_ERRORS=ON` `/tmp/void-w4a-unicode` (`VoidTests --filter "Utf*"` & `ctest`) | `Utf` 4/4 passed (0.3ms); `ctest` 2/2 passed (`VoidTests` 0.11s, `VoidInstalledComponentConsumers` including `UnicodeOnly` 2.25s) |
| M-ASYNC-02..03 (`c75056f`) | `Async;Testing` RelWithDebInfo `-DVOID_WARNINGS_AS_ERRORS=ON` `/tmp/void-w4a-async` & Debug TSan `/tmp/void-w4a-async-tsan` | RelWithDebInfo `OperationScope*\|Executor*\|Coro*` 28/28 (4.1ms) & `ctest` 2/2 (2.74s); Debug TSan `OperationScope*\|Executor*\|ThreadPool*` 20/20 passed (34.6ms, 0 races) |
| Full Integrated RelWithDebInfo (`c75056f`) | `dev cpp-gcc -p libarchive -p openssl -p sqlite -p libsodium` full build (`-DVOID_WARNINGS_AS_ERRORS=ON -DVOID_ENABLE_BENCHMARKS=ON`), `/tmp/void-w4a-full/tests/VoidTests`, `ctest --test-dir /tmp/void-w4a-full --output-on-failure --timeout 180` | 31 active modules; `VoidTests`: 1,345 tests — 1,342 passed, 3 intentional skips (`plugin_load_and_query_skipped`, `broken_feature`, `unquoted_skip`), 0 failed (3.75s); `ctest`: 2/2 passed (`VoidTests` 3.77s + `VoidInstalledComponentConsumers` 14.45s, total 18.21s) |
| Full Integrated ASan+UBSan (`c75056f`) | `dev cpp-gcc -p libarchive -p openssl -p sqlite -p libsodium` Debug (`-DVOID_ENABLE_ASAN=ON -DVOID_ENABLE_UBSAN=ON -DVOID_WARNINGS_AS_ERRORS=ON`), `ASAN_OPTIONS=detect_leaks=1:halt_on_error=1 UBSAN_OPTIONS=print_stacktrace=1:halt_on_error=1 /tmp/void-w4a-asan/tests/VoidTests` | 1,345 tests — 1,342 passed, 3 skipped, 0 failed (11.00s), 0 leaks, 0 UB |
| Post-W4A Benchmark (`c75056f`) | `/tmp/void-w4a-full/benchmarks/VoidFoundationBench --json /tmp/void-w4a-full/post-w4a.json` (RelWithDebInfo, warmup=5, reps=20, ops=10000) | Medians: `harness_empty_loop` 0.39ns, `core_uuid_parse_hyphenated` 25.48ns, `core_uuid_to_string` 17.09ns, `core_hash_fnv1a64_256b` 185.25ns, `core_hash_murmur3_256b` 69.37ns, `functional_result_ok_chain` 1.15ns, `functional_error_with_context` 59.77ns, `math_checked_add_loop` 0.48ns, `containers_spsc_ring_push_pop` 9.16ns, `containers_lru_get_put` 21.81ns, `binary_reader_u64_be` 1.36ns, `data_json_parse_small_object` 319.83ns, `data_json_serialize_small_object` 168.13ns |
@@ -0,0 +1,38 @@
# Async OperationState, ResumeTicket, TaskScope, and Bounded Executor Lanes
Task ID: M-ASYNC-02, M-ASYNC-03
Phase: P1
Status: APPROVED
Contracts: C-01, C-04, C-06, C-07
## 1. Context and baseline
`src/Async/module.cmake` currently depends only on `LogState`, while `include/Void/Async/Executor.hpp` provides only void-returning `post()`, `ManualExecutor`, `schedule_on`, and fire-and-forget `spawn()`. Async lacks structured admission control, race-free backend completion vs cancellation settlement, completion-lane backpressure bypass, and structured `TaskScope` join/cancellation/exception ownership.
## 2. Deliverables
- Updated `src/Async/module.cmake` declaring `INTERNAL_DEPS Functional Time LogState`.
- New `include/Void/Async/Operation.hpp`: `OperationOptions`, `AdmissionError`, `AsyncErrorCode` (`kAsyncErrorDomain`), `make_async_error`, `DomainOutcomeKind`, `ResumeTicket`, and `OperationState` managing combined `std::stop_source`, atomic `backend_refs`, single-winner CAS terminal state, and post-backend-release continuation resumption outside locks.
- Upgraded `include/Void/Async/Executor.hpp`: keeps 1.x `post`/`ManualExecutor`/`schedule_on`/`spawn` working while adding `try_post`, `post_completion` (reserved completion lane), `is_executor_thread()`, bounded `ManualExecutor` queue capacity, and cancellable clock-aware `schedule_on(executor, options, clock)`.
- New `include/Void/Async/TaskScope.hpp`: `TaskScopeOptions`, `JoinHandle`, reserve-then-transfer `TaskScope::spawn` (preserving `Task<void>` on admission failure), `request_stop`, `co_await join()`, `join_blocking()` with `self_join` detection, `join_pumping`, and `DetachedOwner`.
- Tests in `tests/standalone/Async/OperationScope.cpp`.
## 3. Exact files and interfaces
- `src/Async/module.cmake`
- `include/Void/Async/Operation.hpp`
- `include/Void/Async/Executor.hpp`
- `include/Void/Async/TaskScope.hpp`
- `tests/standalone/Async/OperationScope.cpp`
## 4. Edge cases
- Failed `TaskScope::spawn` (full or stopped) does not consume or destroy caller's `Coro::Task<void>`.
- Concurrent backend commit vs `std::stop_token` firing resolves to exactly one terminal outcome, releases backend references before resuming continuation outside locks, and supports synchronous completion without double-resume.
- Reserved `post_completion` succeeds even when normal submission queue capacity is saturated.
- `join_blocking()` called from the associated executor thread detects `self_join` rather than deadlocking.
- Concurrent cancellation/completion/join stress passes cleanly under Debug TSan and ASan/UBSan.
## 5. Acceptance criteria
- `OperationScope*`, `Executor*`, `Coro*`, and `ThreadPool*` tests pass under RelWithDebInfo `-Werror`, ASan+UBSan, and Debug TSan (`-DVOID_ENABLE_TSAN=ON`).
## 6. Verification commands
```sh
dev cpp-gcc -c bash -lc 'cmake -S . -B /tmp/void-w4a-async -G Ninja -DVOID_ENABLED_MODULES="Async;Testing" -DVOID_WARNINGS_AS_ERRORS=ON && cmake --build /tmp/void-w4a-async && /tmp/void-w4a-async/tests/VoidTests --filter "OperationScope*|Executor*|Coro*" && ctest --test-dir /tmp/void-w4a-async --output-on-failure --timeout 60'
dev cpp-gcc -c bash -lc 'cmake -S . -B /tmp/void-w4a-async-tsan -G Ninja -DCMAKE_BUILD_TYPE=Debug -DVOID_ENABLED_MODULES="Async;Testing" -DVOID_ENABLE_TSAN=ON -DVOID_WARNINGS_AS_ERRORS=ON && cmake --build /tmp/void-w4a-async-tsan && /tmp/void-w4a-async-tsan/tests/VoidTests --filter "OperationScope*|Executor*|ThreadPool*"'
```
@@ -0,0 +1,38 @@
# Algorithms Indexed Graph Views, Work Budgets, and Iterative Traversals/Topology
Task ID: S-ALGORITHMS-02
Phase: P1
Status: APPROVED
Contracts: C-01, C-05, C-07
## 1. Context and baseline
VoidLibrary currently has no `Algorithms` module (`src/Algorithms/module.cmake`, `include/Void/Algorithms/`). Graph algorithms are needed as a standalone header-only module with strict dependency discipline (`INTERNAL_DEPS Core Math`), zero unbounded recursion, pre-checked scratch memory budgets, overflow-safe sizing via `Void::Numeric`, and safe cancellation / concurrent graph mutation detection.
## 2. Deliverables
- `src/Algorithms/module.cmake` declaring `INTERNAL_DEPS Core Math`.
- New `include/Void/Algorithms/Graph.hpp` defining `Void::Algorithms::{WorkLimits, AlgorithmError, Topology, TraversalResult, ShortestPathResult, IndexedGraphView, HasVersionStamp, AdjacencyView}` and iterative `bfs`, `dfs`, `shortest_path_unweighted`, and `topological_order`.
- Comprehensive unit and edge-case tests in `tests/standalone/Algorithms/Graph.cpp`.
- Package consumer `tests/package/AlgorithmsOnly/{CMakeLists.txt,main.cpp}` registered in `tests/package/InstalledComponents.cmake` (`Algorithms Math Core`).
## 3. Exact files and interfaces
- `src/Algorithms/module.cmake`
- `include/Void/Algorithms/Graph.hpp`
- `tests/standalone/Algorithms/Graph.cpp`
- `tests/package/AlgorithmsOnly/CMakeLists.txt`
- `tests/package/AlgorithmsOnly/main.cpp`
- `tests/package/InstalledComponents.cmake`
## 4. Edge cases
- Out-of-range source/target vertex IDs or `vertex_count()` exceeding `WorkLimits` rejected before scratch allocations.
- Overflowing edge/vertex scratch budget calculations rejected using `Void::Numeric::checked_mul`/`checked_add`.
- Out-of-range neighbor IDs in adjacency lists diagnosed cleanly without out-of-bounds vector access.
- Deep graphs (`> 100k` vertices / chains) execute strictly iteratively with no stack overflow.
- `topological_order` uses Kahn's algorithm and, on cycle detection, runs iterative 3-color DFS to extract a deterministic cycle witness `[u0, ..., uk, u0]`.
- Periodic `std::stop_token` and `HasVersionStamp::version()` checks abort mid-traversal with `cancelled` / `concurrent_modification`.
## 5. Acceptance criteria
- `Graph*` tests and `VoidInstalledComponentConsumers` (`AlgorithmsOnly`) pass under `-DVOID_WARNINGS_AS_ERRORS=ON` and ASan/UBSan.
## 6. Verification commands
```sh
dev cpp-gcc -c bash -lc 'cmake -S . -B /tmp/void-w4a-alg -G Ninja -DVOID_ENABLED_MODULES="Algorithms;Testing" -DVOID_WARNINGS_AS_ERRORS=ON && cmake --build /tmp/void-w4a-alg && /tmp/void-w4a-alg/tests/VoidTests --filter "Graph*" && ctest --test-dir /tmp/void-w4a-alg --output-on-failure --timeout 60'
```
@@ -0,0 +1,38 @@
# Unicode 17.0.0 Manifest and Strict/Repair/Streaming UTF Codecs
Task ID: S-UNICODE-01, S-UNICODE-02
Phase: P1
Status: APPROVED
Contracts: C-01, C-05, C-07
## 1. Context and baseline
VoidLibrary currently has no `Unicode` module (`src/Unicode/`). `Text` handles locale-free ASCII-only operations (`M-TEXT-02`), while UTF-8/UTF-16/UTF-32 validation, transcoding, one-unit repair, and streaming decoding must live in a dedicated `Unicode` module pinning Unicode `17.0.0` metadata and keeping `Text` independent of Unicode data.
## 2. Deliverables
- `src/Unicode/module.cmake` declaring `INTERNAL_DEPS Core Text`.
- `src/Unicode/MANIFEST.md` pinning Unicode `17.0.0`, official UCD source URL, and Unicode license notice.
- New `include/Void/Unicode/Utf.hpp` defining `Void::Unicode::{data_version, is_scalar_value, UtfPolicy, UtfErrorKind, UtfError, Scalar, UtfLimits, TranscodeCounts}`, strict & `replace_one_unit` validation/transcoding functions for UTF-8/UTF-16/UTF-32 (owning and into-`std::span`), and stateful `Utf8StreamDecoder` / `Utf16StreamDecoder`.
- Tests in `tests/standalone/Unicode/Utf.cpp`.
- Package consumer `tests/package/UnicodeOnly/{CMakeLists.txt,main.cpp}` registered in `tests/package/InstalledComponents.cmake` (`Unicode Text Core`).
## 3. Exact files and interfaces
- `src/Unicode/module.cmake`
- `src/Unicode/MANIFEST.md`
- `include/Void/Unicode/Utf.hpp`
- `tests/standalone/Unicode/Utf.cpp`
- `tests/package/UnicodeOnly/CMakeLists.txt`
- `tests/package/UnicodeOnly/main.cpp`
- `tests/package/InstalledComponents.cmake`
## 4. Edge cases
- Rejects overlong UTF-8 sequences, UTF-16 surrogates (`U+D800..U+DFFF`) in UTF-8/UTF-32, unpaired surrogates in UTF-16, code points `> U+10FFFF`, and truncated sequences under `UtfPolicy::reject`.
- One-unit repair (`replace_one_unit`) emits `U+FFFD` per ill-formed unit and advances cleanly by one code unit without skipping subsequent valid units; streaming chunk boundaries match one-shot behavior identically.
- Pre-reserve limit checks against `UtfLimits` reject oversized inputs/outputs before large allocations; periodic `std::stop_token` checks abort long transcodes cleanly.
- Streaming `Utf8StreamDecoder` / `Utf16StreamDecoder` split sequences across arbitrary 1-byte/1-unit boundaries and flush trailing incomplete sequences cleanly at EOF.
## 5. Acceptance criteria
- `Utf*` tests and `VoidInstalledComponentConsumers` (`UnicodeOnly`) pass under `-DVOID_WARNINGS_AS_ERRORS=ON` and ASan/UBSan.
## 6. Verification commands
```sh
dev cpp-gcc -c bash -lc 'cmake -S . -B /tmp/void-w4a-unicode -G Ninja -DVOID_ENABLED_MODULES="Unicode;Testing" -DVOID_WARNINGS_AS_ERRORS=ON && cmake --build /tmp/void-w4a-unicode && /tmp/void-w4a-unicode/tests/VoidTests --filter "Utf*" && ctest --test-dir /tmp/void-w4a-unicode --output-on-failure --timeout 60'
```
+786
View File
@@ -0,0 +1,786 @@
#pragma once
#include <Void/Math/Numeric.hpp>
#include <algorithm>
#include <concepts>
#include <cstddef>
#include <cstdint>
#include <expected>
#include <limits>
#include <ranges>
#include <span>
#include <stop_token>
#include <string>
#include <type_traits>
#include <utility>
#include <vector>
namespace Void::Algorithms
{
struct WorkLimits {
std::size_t max_vertices{1'000'000};
std::size_t max_steps{16'000'000};
std::size_t max_scratch_bytes{64ULL * 1024ULL * 1024ULL};
std::size_t cancel_check_interval{1024};
};
struct AlgorithmError {
enum class Code {
invalid_input,
invalid_vertex,
limit_exceeded,
overflow,
cancelled,
concurrent_modification,
cycle_detected
};
Code code{Code::invalid_input};
std::string message{};
std::vector<std::size_t> cycle{};
};
struct TraversalResult {
static constexpr std::size_t npos = std::numeric_limits<std::size_t>::max();
std::vector<std::size_t> order{};
std::vector<std::size_t> parent{};
std::vector<std::size_t> depth{};
};
struct ShortestPathResult {
static constexpr std::size_t npos = std::numeric_limits<std::size_t>::max();
bool found{false};
std::size_t distance{npos};
std::vector<std::size_t> path{};
};
struct Topology {
std::vector<std::size_t> order{};
std::vector<std::size_t> position{};
};
template <typename G>
concept IndexedGraphView = requires(const G& g, std::size_t u) {
{ g.vertex_count() } -> std::convertible_to<std::size_t>;
{ g.neighbors(u) } -> std::ranges::input_range;
requires std::convertible_to<std::ranges::range_value_t<decltype(g.neighbors(u))>,
std::size_t>;
};
template <typename G>
concept HasVersionStamp = requires(const G& g) {
{ g.version() };
{ g.version() == g.version() } -> std::convertible_to<bool>;
};
class AdjacencyView
{
public:
AdjacencyView() noexcept = default;
explicit AdjacencyView(std::span<const std::vector<std::size_t>> lists) noexcept
: lists_(lists)
{
}
explicit AdjacencyView(const std::vector<std::vector<std::size_t>>& lists) noexcept
: lists_(lists)
{
}
[[nodiscard]] static std::expected<AdjacencyView, AlgorithmError>
try_from_csr(std::span<const std::size_t> offsets,
std::span<const std::size_t> edges)
{
if (offsets.empty()) {
if (!edges.empty()) {
return std::unexpected{AlgorithmError{
AlgorithmError::Code::invalid_input,
"CSR edges present with empty offsets"}};
}
return AdjacencyView{};
}
if (offsets.front() != 0) {
return std::unexpected{AlgorithmError{
AlgorithmError::Code::invalid_input,
"CSR offsets must start at 0"}};
}
for (std::size_t i = 0; i + 1 < offsets.size(); ++i) {
if (offsets[i] > offsets[i + 1]) {
return std::unexpected{AlgorithmError{
AlgorithmError::Code::invalid_input,
"CSR offsets must be monotonically non-decreasing"}};
}
}
if (offsets.back() > edges.size()) {
return std::unexpected{AlgorithmError{
AlgorithmError::Code::invalid_input,
"CSR final offset exceeds edges span size"}};
}
return AdjacencyView{offsets, edges};
}
[[nodiscard]] std::size_t vertex_count() const noexcept
{
if (is_csr_) {
return csr_offsets_.empty() ? 0 : (csr_offsets_.size() - 1);
}
return lists_.size();
}
[[nodiscard]] std::span<const std::size_t> neighbors(std::size_t u) const noexcept
{
if (is_csr_) {
if (u + 1 >= csr_offsets_.size()) {
return {};
}
const std::size_t begin = csr_offsets_[u];
const std::size_t end = csr_offsets_[u + 1];
if (begin > end || end > csr_edges_.size()) {
return {};
}
return csr_edges_.subspan(begin, end - begin);
}
if (u >= lists_.size()) {
return {};
}
return lists_[u];
}
private:
AdjacencyView(std::span<const std::size_t> offsets,
std::span<const std::size_t> edges) noexcept
: csr_offsets_(offsets)
, csr_edges_(edges)
, is_csr_(true)
{
}
std::span<const std::vector<std::size_t>> lists_{};
std::span<const std::size_t> csr_offsets_{};
std::span<const std::size_t> csr_edges_{};
bool is_csr_{false};
};
namespace detail
{
template <typename T>
[[nodiscard]] inline bool valid_vertex_index(T raw, std::size_t vertex_count) noexcept
{
if constexpr (std::is_signed_v<T>) {
if (raw < 0) {
return false;
}
}
return std::cmp_less(raw, vertex_count);
}
[[nodiscard]] inline std::expected<std::size_t, AlgorithmError>
checked_scratch_bytes(std::size_t count,
std::size_t bytes_per_element,
const WorkLimits& limits)
{
const auto prod = Void::Numeric::checked_mul(count, bytes_per_element);
if (!prod.has_value()) {
return std::unexpected{AlgorithmError{
AlgorithmError::Code::overflow,
"Scratch byte budget multiplication overflowed"}};
}
if (*prod > limits.max_scratch_bytes) {
return std::unexpected{AlgorithmError{
AlgorithmError::Code::limit_exceeded,
"Estimated scratch memory exceeds WorkLimits::max_scratch_bytes"}};
}
return *prod;
}
template <typename G>
struct VersionSnapshot {
};
template <typename G>
requires HasVersionStamp<G>
struct VersionSnapshot<G> {
using type = std::remove_cvref_t<decltype(std::declval<const G&>().version())>;
type initial{};
};
template <IndexedGraphView G>
[[nodiscard]] inline VersionSnapshot<G> capture_version(const G& g)
{
if constexpr (HasVersionStamp<G>) {
return VersionSnapshot<G>{g.version()};
} else {
(void)g;
return VersionSnapshot<G>{};
}
}
template <IndexedGraphView G>
[[nodiscard]] inline std::expected<void, AlgorithmError>
check_state(const G& g,
const VersionSnapshot<G>& snap,
const std::stop_token& stop_token)
{
if (stop_token.stop_requested()) {
return std::unexpected{AlgorithmError{
AlgorithmError::Code::cancelled,
"Algorithm cancelled via stop_token"}};
}
if constexpr (HasVersionStamp<G>) {
if (!(g.version() == snap.initial)) {
return std::unexpected{AlgorithmError{
AlgorithmError::Code::concurrent_modification,
"Graph version changed during traversal"}};
}
} else {
(void)g;
(void)snap;
}
return {};
}
[[nodiscard]] inline std::expected<void, AlgorithmError>
advance_step(std::size_t& steps, const WorkLimits& limits)
{
if (steps >= limits.max_steps) {
return std::unexpected{AlgorithmError{
AlgorithmError::Code::limit_exceeded,
"Step count exceeded WorkLimits::max_steps"}};
}
const auto next = Void::Numeric::checked_add(steps, std::size_t{1});
if (!next.has_value()) {
return std::unexpected{AlgorithmError{
AlgorithmError::Code::overflow,
"Step counter overflowed"}};
}
steps = *next;
return {};
}
template <IndexedGraphView G>
[[nodiscard]] inline std::expected<void, AlgorithmError>
step_and_maybe_check(const G& g,
const VersionSnapshot<G>& snap,
const std::stop_token& stop_token,
std::size_t& steps,
const WorkLimits& limits)
{
if (auto s = advance_step(steps, limits); !s.has_value()) {
return std::unexpected{std::move(s.error())};
}
if (limits.cancel_check_interval > 0 &&
(steps % limits.cancel_check_interval) == 0) {
if (auto c = check_state(g, snap, stop_token); !c.has_value()) {
return std::unexpected{std::move(c.error())};
}
}
return {};
}
} // namespace detail
template <IndexedGraphView G>
[[nodiscard]] std::expected<TraversalResult, AlgorithmError>
bfs(const G& graph,
std::size_t start,
const WorkLimits& limits = {},
std::stop_token stop_token = {})
{
const auto version = detail::capture_version(graph);
if (auto c = detail::check_state(graph, version, stop_token); !c.has_value()) {
return std::unexpected{std::move(c.error())};
}
const std::size_t n = static_cast<std::size_t>(graph.vertex_count());
if (n > limits.max_vertices) {
return std::unexpected{AlgorithmError{
AlgorithmError::Code::limit_exceeded,
"Vertex count exceeds WorkLimits::max_vertices"}};
}
if (start >= n) {
return std::unexpected{AlgorithmError{
AlgorithmError::Code::invalid_vertex,
"Start vertex index is out of range"}};
}
constexpr std::size_t kPerVertexBytes =
4 * sizeof(std::size_t) + sizeof(std::uint8_t);
if (auto s = detail::checked_scratch_bytes(n, kPerVertexBytes, limits);
!s.has_value()) {
return std::unexpected{std::move(s.error())};
}
std::vector<std::uint8_t> visited(n, 0);
std::vector<std::size_t> queue;
queue.reserve(n);
TraversalResult result;
result.parent.assign(n, TraversalResult::npos);
result.depth.assign(n, TraversalResult::npos);
result.order.reserve(n);
visited[start] = 1;
result.depth[start] = 0;
queue.push_back(start);
std::size_t steps = 0;
std::size_t head = 0;
while (head < queue.size()) {
const std::size_t u = queue[head++];
if (auto s = detail::step_and_maybe_check(graph, version, stop_token, steps, limits);
!s.has_value()) {
return std::unexpected{std::move(s.error())};
}
result.order.push_back(u);
for (const auto raw_v : graph.neighbors(u)) {
if (auto s = detail::step_and_maybe_check(graph, version, stop_token, steps, limits);
!s.has_value()) {
return std::unexpected{std::move(s.error())};
}
if (!detail::valid_vertex_index(raw_v, n)) {
return std::unexpected{AlgorithmError{
AlgorithmError::Code::invalid_vertex,
"Neighbor vertex index out of range"}};
}
const std::size_t v = static_cast<std::size_t>(raw_v);
if (!visited[v]) {
visited[v] = 1;
result.parent[v] = u;
result.depth[v] = result.depth[u] + 1;
queue.push_back(v);
}
}
}
if (auto c = detail::check_state(graph, version, stop_token); !c.has_value()) {
return std::unexpected{std::move(c.error())};
}
return result;
}
template <IndexedGraphView G>
[[nodiscard]] std::expected<TraversalResult, AlgorithmError>
dfs(const G& graph,
std::size_t start,
const WorkLimits& limits = {},
std::stop_token stop_token = {})
{
const auto version = detail::capture_version(graph);
if (auto c = detail::check_state(graph, version, stop_token); !c.has_value()) {
return std::unexpected{std::move(c.error())};
}
const std::size_t n = static_cast<std::size_t>(graph.vertex_count());
if (n > limits.max_vertices) {
return std::unexpected{AlgorithmError{
AlgorithmError::Code::limit_exceeded,
"Vertex count exceeds WorkLimits::max_vertices"}};
}
if (start >= n) {
return std::unexpected{AlgorithmError{
AlgorithmError::Code::invalid_vertex,
"Start vertex index is out of range"}};
}
struct Frame {
std::size_t vertex;
std::size_t parent;
std::size_t depth;
};
constexpr std::size_t kBasePerVertexBytes =
3 * sizeof(std::size_t) + sizeof(std::uint8_t);
const auto base_scratch =
detail::checked_scratch_bytes(n, kBasePerVertexBytes, limits);
if (!base_scratch.has_value()) {
return std::unexpected{std::move(base_scratch.error())};
}
std::vector<std::uint8_t> visited(n, 0);
std::vector<Frame> stack;
std::vector<std::size_t> scratch_neighbors;
TraversalResult result;
result.parent.assign(n, TraversalResult::npos);
result.depth.assign(n, TraversalResult::npos);
result.order.reserve(n);
if (*base_scratch + sizeof(Frame) > limits.max_scratch_bytes) {
return std::unexpected{AlgorithmError{
AlgorithmError::Code::limit_exceeded,
"DFS stack scratch memory exceeds WorkLimits::max_scratch_bytes"}};
}
stack.push_back(Frame{start, TraversalResult::npos, 0});
std::size_t steps = 0;
while (!stack.empty()) {
const Frame cur = stack.back();
stack.pop_back();
if (auto s = detail::step_and_maybe_check(graph, version, stop_token, steps, limits);
!s.has_value()) {
return std::unexpected{std::move(s.error())};
}
if (visited[cur.vertex]) {
continue;
}
visited[cur.vertex] = 1;
result.parent[cur.vertex] = cur.parent;
result.depth[cur.vertex] = cur.depth;
result.order.push_back(cur.vertex);
scratch_neighbors.clear();
for (const auto raw_v : graph.neighbors(cur.vertex)) {
if (auto s = detail::step_and_maybe_check(graph, version, stop_token, steps, limits);
!s.has_value()) {
return std::unexpected{std::move(s.error())};
}
if (!detail::valid_vertex_index(raw_v, n)) {
return std::unexpected{AlgorithmError{
AlgorithmError::Code::invalid_vertex,
"Neighbor vertex index out of range"}};
}
const std::size_t v = static_cast<std::size_t>(raw_v);
if (!visited[v]) {
scratch_neighbors.push_back(v);
const auto dyn_bytes = Void::Numeric::checked_mul(
stack.size() + scratch_neighbors.size(), sizeof(Frame));
if (!dyn_bytes.has_value()) {
return std::unexpected{AlgorithmError{
AlgorithmError::Code::overflow,
"DFS stack byte calculation overflowed"}};
}
if (*base_scratch + *dyn_bytes > limits.max_scratch_bytes) {
return std::unexpected{AlgorithmError{
AlgorithmError::Code::limit_exceeded,
"DFS stack scratch memory exceeds WorkLimits::max_scratch_bytes"}};
}
}
}
for (auto it = scratch_neighbors.rbegin(); it != scratch_neighbors.rend(); ++it) {
stack.push_back(Frame{*it, cur.vertex, cur.depth + 1});
}
}
if (auto c = detail::check_state(graph, version, stop_token); !c.has_value()) {
return std::unexpected{std::move(c.error())};
}
return result;
}
template <IndexedGraphView G>
[[nodiscard]] std::expected<ShortestPathResult, AlgorithmError>
shortest_path_unweighted(const G& graph,
std::size_t start,
std::size_t target,
const WorkLimits& limits = {},
std::stop_token stop_token = {})
{
const auto version = detail::capture_version(graph);
if (auto c = detail::check_state(graph, version, stop_token); !c.has_value()) {
return std::unexpected{std::move(c.error())};
}
const std::size_t n = static_cast<std::size_t>(graph.vertex_count());
if (n > limits.max_vertices) {
return std::unexpected{AlgorithmError{
AlgorithmError::Code::limit_exceeded,
"Vertex count exceeds WorkLimits::max_vertices"}};
}
if (start >= n || target >= n) {
return std::unexpected{AlgorithmError{
AlgorithmError::Code::invalid_vertex,
"Start or target vertex index is out of range"}};
}
if (start == target) {
if (auto c = detail::check_state(graph, version, stop_token); !c.has_value()) {
return std::unexpected{std::move(c.error())};
}
return ShortestPathResult{
.found = true,
.distance = 0,
.path = {start},
};
}
constexpr std::size_t kPerVertexBytes =
2 * sizeof(std::size_t) + sizeof(std::uint8_t);
if (auto s = detail::checked_scratch_bytes(n, kPerVertexBytes, limits);
!s.has_value()) {
return std::unexpected{std::move(s.error())};
}
std::vector<std::uint8_t> visited(n, 0);
std::vector<std::size_t> parent(n, ShortestPathResult::npos);
std::vector<std::size_t> queue;
queue.reserve(n);
visited[start] = 1;
queue.push_back(start);
bool reached = false;
std::size_t steps = 0;
std::size_t head = 0;
while (head < queue.size() && !reached) {
const std::size_t u = queue[head++];
if (auto s = detail::step_and_maybe_check(graph, version, stop_token, steps, limits);
!s.has_value()) {
return std::unexpected{std::move(s.error())};
}
for (const auto raw_v : graph.neighbors(u)) {
if (auto s = detail::step_and_maybe_check(graph, version, stop_token, steps, limits);
!s.has_value()) {
return std::unexpected{std::move(s.error())};
}
if (!detail::valid_vertex_index(raw_v, n)) {
return std::unexpected{AlgorithmError{
AlgorithmError::Code::invalid_vertex,
"Neighbor vertex index out of range"}};
}
const std::size_t v = static_cast<std::size_t>(raw_v);
if (!visited[v]) {
visited[v] = 1;
parent[v] = u;
queue.push_back(v);
if (v == target) {
reached = true;
break;
}
}
}
}
if (auto c = detail::check_state(graph, version, stop_token); !c.has_value()) {
return std::unexpected{std::move(c.error())};
}
if (!reached) {
return ShortestPathResult{
.found = false,
.distance = ShortestPathResult::npos,
.path = {},
};
}
std::vector<std::size_t> path;
for (std::size_t cur = target; cur != ShortestPathResult::npos; cur = parent[cur]) {
path.push_back(cur);
}
std::reverse(path.begin(), path.end());
const std::size_t distance = path.empty() ? 0 : (path.size() - 1);
return ShortestPathResult{
.found = true,
.distance = distance,
.path = std::move(path),
};
}
template <IndexedGraphView G>
[[nodiscard]] std::expected<Topology, AlgorithmError>
topological_order(const G& graph,
const WorkLimits& limits = {},
std::stop_token stop_token = {})
{
const auto version = detail::capture_version(graph);
if (auto c = detail::check_state(graph, version, stop_token); !c.has_value()) {
return std::unexpected{std::move(c.error())};
}
const std::size_t n = static_cast<std::size_t>(graph.vertex_count());
if (n > limits.max_vertices) {
return std::unexpected{AlgorithmError{
AlgorithmError::Code::limit_exceeded,
"Vertex count exceeds WorkLimits::max_vertices"}};
}
if (n == 0) {
return Topology{};
}
constexpr std::size_t kPerVertexBytes = 4 * sizeof(std::size_t);
const auto base_scratch =
detail::checked_scratch_bytes(n, kPerVertexBytes, limits);
if (!base_scratch.has_value()) {
return std::unexpected{std::move(base_scratch.error())};
}
std::vector<std::size_t> in_degree(n, 0);
std::size_t steps = 0;
for (std::size_t u = 0; u < n; ++u) {
if (auto s = detail::step_and_maybe_check(graph, version, stop_token, steps, limits);
!s.has_value()) {
return std::unexpected{std::move(s.error())};
}
for (const auto raw_v : graph.neighbors(u)) {
if (auto s = detail::step_and_maybe_check(graph, version, stop_token, steps, limits);
!s.has_value()) {
return std::unexpected{std::move(s.error())};
}
if (!detail::valid_vertex_index(raw_v, n)) {
return std::unexpected{AlgorithmError{
AlgorithmError::Code::invalid_vertex,
"Neighbor vertex index out of range"}};
}
const std::size_t v = static_cast<std::size_t>(raw_v);
const auto inc = Void::Numeric::checked_add(in_degree[v], std::size_t{1});
if (!inc.has_value()) {
return std::unexpected{AlgorithmError{
AlgorithmError::Code::overflow,
"In-degree counter overflowed"}};
}
in_degree[v] = *inc;
}
}
std::vector<std::size_t> queue;
queue.reserve(n);
for (std::size_t u = 0; u < n; ++u) {
if (in_degree[u] == 0) {
queue.push_back(u);
}
}
Topology topo;
topo.order.reserve(n);
topo.position.assign(n, 0);
std::size_t head = 0;
while (head < queue.size()) {
const std::size_t u = queue[head++];
if (auto s = detail::step_and_maybe_check(graph, version, stop_token, steps, limits);
!s.has_value()) {
return std::unexpected{std::move(s.error())};
}
topo.position[u] = topo.order.size();
topo.order.push_back(u);
for (const auto raw_v : graph.neighbors(u)) {
if (auto s = detail::step_and_maybe_check(graph, version, stop_token, steps, limits);
!s.has_value()) {
return std::unexpected{std::move(s.error())};
}
if (!detail::valid_vertex_index(raw_v, n)) {
return std::unexpected{AlgorithmError{
AlgorithmError::Code::invalid_vertex,
"Neighbor vertex index out of range"}};
}
const std::size_t v = static_cast<std::size_t>(raw_v);
if (--in_degree[v] == 0) {
queue.push_back(v);
}
}
}
if (topo.order.size() == n) {
if (auto c = detail::check_state(graph, version, stop_token); !c.has_value()) {
return std::unexpected{std::move(c.error())};
}
return topo;
}
// Extract a deterministic cycle witness [u0, ..., uk, u0] via iterative 3-color DFS.
enum class Color : std::uint8_t { unvisited = 0, active = 1, done = 2 };
struct CycleFrame {
std::size_t vertex;
std::size_t edge_begin;
std::size_t edge_end;
std::size_t edge_cursor;
};
const auto extra_colors = detail::checked_scratch_bytes(n, sizeof(Color), limits);
if (!extra_colors.has_value() ||
*base_scratch + *extra_colors > limits.max_scratch_bytes) {
return std::unexpected{AlgorithmError{
AlgorithmError::Code::limit_exceeded,
"Cycle-witness scratch memory exceeds WorkLimits::max_scratch_bytes"}};
}
std::vector<Color> color(n, Color::unvisited);
std::vector<CycleFrame> stack;
std::vector<std::size_t> edge_pool;
auto push_frame = [&](std::size_t v) -> std::expected<void, AlgorithmError> {
color[v] = Color::active;
const std::size_t begin = edge_pool.size();
for (const auto raw_nxt : graph.neighbors(v)) {
if (!detail::valid_vertex_index(raw_nxt, n)) {
return std::unexpected{AlgorithmError{
AlgorithmError::Code::invalid_vertex,
"Neighbor vertex index out of range"}};
}
edge_pool.push_back(static_cast<std::size_t>(raw_nxt));
}
const std::size_t end = edge_pool.size();
const std::size_t dyn_bytes =
(stack.size() + 1) * sizeof(CycleFrame) + edge_pool.size() * sizeof(std::size_t);
if (*base_scratch + *extra_colors + dyn_bytes > limits.max_scratch_bytes) {
return std::unexpected{AlgorithmError{
AlgorithmError::Code::limit_exceeded,
"Cycle-witness scratch memory exceeds WorkLimits::max_scratch_bytes"}};
}
stack.push_back(CycleFrame{v, begin, end, begin});
return {};
};
for (std::size_t seed = 0; seed < n; ++seed) {
if (in_degree[seed] == 0 || color[seed] != Color::unvisited) {
continue;
}
if (auto p = push_frame(seed); !p.has_value()) {
return std::unexpected{std::move(p.error())};
}
while (!stack.empty()) {
if (auto s = detail::step_and_maybe_check(graph, version, stop_token, steps, limits);
!s.has_value()) {
return std::unexpected{std::move(s.error())};
}
auto& top = stack.back();
if (top.edge_cursor < top.edge_end) {
const std::size_t v = edge_pool[top.edge_cursor++];
if (color[v] == Color::active) {
std::vector<std::size_t> witness;
auto it = std::find_if(stack.begin(), stack.end(), [v](const CycleFrame& f) {
return f.vertex == v;
});
for (; it != stack.end(); ++it) {
witness.push_back(it->vertex);
}
witness.push_back(v);
if (auto c = detail::check_state(graph, version, stop_token); !c.has_value()) {
return std::unexpected{std::move(c.error())};
}
return std::unexpected{AlgorithmError{
AlgorithmError::Code::cycle_detected,
"Directed graph contains a cycle",
std::move(witness)}};
}
if (color[v] == Color::unvisited) {
if (auto p = push_frame(v); !p.has_value()) {
return std::unexpected{std::move(p.error())};
}
}
} else {
const std::size_t pop_begin = top.edge_begin;
color[top.vertex] = Color::done;
stack.pop_back();
edge_pool.resize(pop_begin);
}
}
}
return std::unexpected{AlgorithmError{
AlgorithmError::Code::cycle_detected,
"Directed graph contains a cycle"}};
}
} // namespace Void::Algorithms
+138
View File
@@ -0,0 +1,138 @@
#pragma once
#include <Void/Functional/Error.hpp>
#include <Void/Functional/Result.hpp>
#include <Void/Time/Clock.hpp>
#include <cstdint>
#include <optional>
#include <stop_token>
#include <string>
namespace Void::Async
{
enum class AdmissionError {
overloaded,
stopped,
deadline_expired,
invalid_argument,
self_join
};
enum class AsyncErrorCode : std::int32_t {
none = 0,
cancelled = 1,
timeout = 2,
overloaded = 3,
stopped = 4,
invalid_argument = 5,
self_join = 6,
backend_error = 7,
limit_exceeded = 8
};
enum class DomainOutcomeKind {
pending,
succeeded,
not_committed,
unknown,
failed,
cancelled
};
struct OperationOptions {
std::stop_token stop{};
std::optional<Void::Time::MonotonicClock::time_point> deadline{};
};
[[nodiscard]] inline bool is_deadline_expired(
const OperationOptions& options,
const Void::Time::MonotonicClock& clock =
Void::Time::SystemMonotonicClock::instance()) noexcept
{
return options.deadline.has_value() && clock.now() >= *options.deadline;
}
[[nodiscard]] inline Void::Result::Error
make_async_error(AsyncErrorCode code, std::string message = {})
{
using Void::Result::Error;
using Void::Result::ErrorCode;
using Void::Result::ErrorKind;
ErrorKind kind = ErrorKind::internal;
switch (code) {
case AsyncErrorCode::none:
kind = ErrorKind::internal;
break;
case AsyncErrorCode::cancelled:
case AsyncErrorCode::stopped:
kind = ErrorKind::cancelled;
break;
case AsyncErrorCode::timeout:
kind = ErrorKind::timeout;
break;
case AsyncErrorCode::overloaded:
kind = ErrorKind::overloaded;
break;
case AsyncErrorCode::invalid_argument:
kind = ErrorKind::invalid_argument;
break;
case AsyncErrorCode::self_join:
kind = ErrorKind::conflict;
break;
case AsyncErrorCode::backend_error:
kind = ErrorKind::internal;
break;
case AsyncErrorCode::limit_exceeded:
kind = ErrorKind::exhausted;
break;
}
const ErrorCode domain_code{
Void::Result::kAsyncErrorDomain,
static_cast<std::int32_t>(code)};
return Error{kind, std::move(message), domain_code};
}
[[nodiscard]] inline Void::Result::Error
make_async_error(AdmissionError adm, std::string message = {})
{
AsyncErrorCode code = AsyncErrorCode::invalid_argument;
switch (adm) {
case AdmissionError::overloaded:
code = AsyncErrorCode::overloaded;
if (message.empty()) {
message = "Async executor or scope capacity exceeded";
}
break;
case AdmissionError::stopped:
code = AsyncErrorCode::stopped;
if (message.empty()) {
message = "Async executor or scope is stopped";
}
break;
case AdmissionError::deadline_expired:
code = AsyncErrorCode::timeout;
if (message.empty()) {
message = "Async operation deadline expired";
}
break;
case AdmissionError::invalid_argument:
code = AsyncErrorCode::invalid_argument;
if (message.empty()) {
message = "Invalid async admission argument";
}
break;
case AdmissionError::self_join:
code = AsyncErrorCode::self_join;
if (message.empty()) {
message = "Cannot blocking-join from inside the active executor thread";
}
break;
}
return make_async_error(code, std::move(message));
}
} // namespace Void::Async
+248 -2
View File
@@ -1,15 +1,56 @@
#pragma once #pragma once
#include <Void/Async/Detail/Types.hpp>
#include <Void/Async/MpscQueue.hpp> #include <Void/Async/MpscQueue.hpp>
#include <Void/Async/Task.hpp> #include <Void/Async/Task.hpp>
#include <atomic>
#include <coroutine> #include <coroutine>
#include <cstddef> #include <cstddef>
#include <exception> #include <exception>
#include <expected>
#include <optional>
namespace Void::Async namespace Void::Async
{ {
class Executor;
namespace detail
{
struct ActiveExecutorFrame {
const Executor* exec{nullptr};
const ActiveExecutorFrame* prev{nullptr};
[[nodiscard]] static inline const ActiveExecutorFrame*& head() noexcept
{
thread_local const ActiveExecutorFrame* slot = nullptr;
return slot;
}
};
class ExecutorThreadGuard
{
public:
explicit ExecutorThreadGuard(const Executor* exec) noexcept
: frame_{exec, ActiveExecutorFrame::head()}
{
ActiveExecutorFrame::head() = &frame_;
}
~ExecutorThreadGuard()
{
ActiveExecutorFrame::head() = frame_.prev;
}
ExecutorThreadGuard(const ExecutorThreadGuard&) = delete;
ExecutorThreadGuard& operator=(const ExecutorThreadGuard&) = delete;
private:
ActiveExecutorFrame frame_;
};
} // namespace detail
// ── Executor ────────────────────────────────────────────────────────────────── // ── Executor ──────────────────────────────────────────────────────────────────
// Minimal scheduling interface bridging Coro::Task to a driving thread. // Minimal scheduling interface bridging Coro::Task to a driving thread.
// post() must be safe to call from any thread. // post() must be safe to call from any thread.
@@ -21,6 +62,54 @@ public:
// Schedule a coroutine for resumption on this executor. Thread-safe. // Schedule a coroutine for resumption on this executor. Thread-safe.
virtual void post(std::coroutine_handle<> handle) = 0; virtual void post(std::coroutine_handle<> handle) = 0;
// Bounded non-blocking admission. Subclasses may override with queue caps.
[[nodiscard]] virtual std::expected<void, AdmissionError>
try_post(std::coroutine_handle<> handle)
{
if (!handle) {
return std::unexpected{AdmissionError::invalid_argument};
}
post(handle);
return {};
}
// Reserved lane for resuming waiting/joining continuations without normal
// work-queue backpressure rejections.
virtual void post_completion(std::coroutine_handle<> handle)
{
if (handle) {
post(handle);
}
}
[[nodiscard]] virtual bool is_executor_thread() const noexcept
{
for (const auto* f = detail::ActiveExecutorFrame::head();
f != nullptr;
f = f->prev) {
if (f->exec == this) {
return true;
}
}
return false;
}
[[nodiscard]] virtual bool supports_reservation() const noexcept { return false; }
[[nodiscard]] virtual std::expected<void, AdmissionError> try_reserve_slot()
{
return {};
}
virtual void commit_reserved(std::coroutine_handle<> handle)
{
post_completion(handle);
}
virtual void release_reserved() noexcept {}
[[nodiscard]] virtual bool has_background_workers() const noexcept { return true; }
}; };
// ── ManualExecutor ──────────────────────────────────────────────────────────── // ── ManualExecutor ────────────────────────────────────────────────────────────
@@ -31,18 +120,111 @@ public:
class ManualExecutor final : public Executor class ManualExecutor final : public Executor
{ {
public: public:
explicit ManualExecutor(std::size_t max_queue = 0) noexcept
: max_queue_(max_queue)
{
}
void post(std::coroutine_handle<> handle) override void post(std::coroutine_handle<> handle) override
{ {
if (!handle) {
return;
}
pending_normal_.fetch_add(1, std::memory_order_acq_rel);
queue_.push(handle); queue_.push(handle);
} }
[[nodiscard]] std::expected<void, AdmissionError>
try_post(std::coroutine_handle<> handle) override
{
if (!handle) {
return std::unexpected{AdmissionError::invalid_argument};
}
auto reserved = try_reserve_slot();
if (!reserved.has_value()) {
return reserved;
}
queue_.push(handle);
return {};
}
void post_completion(std::coroutine_handle<> handle) override
{
if (!handle) {
return;
}
completion_queue_.push(handle);
}
[[nodiscard]] bool supports_reservation() const noexcept override { return true; }
[[nodiscard]] std::expected<void, AdmissionError> try_reserve_slot() override
{
std::size_t cur = pending_normal_.load(std::memory_order_acquire);
for (;;) {
if (!accepting_.load(std::memory_order_acquire)) {
return std::unexpected{AdmissionError::stopped};
}
if (max_queue_ != 0 && cur >= max_queue_) {
return std::unexpected{AdmissionError::overloaded};
}
if (pending_normal_.compare_exchange_weak(
cur,
cur + 1,
std::memory_order_acq_rel,
std::memory_order_acquire)) {
return {};
}
}
}
void commit_reserved(std::coroutine_handle<> handle) override
{
if (!handle) {
pending_normal_.fetch_sub(1, std::memory_order_acq_rel);
return;
}
queue_.push(handle);
}
void release_reserved() noexcept override
{
pending_normal_.fetch_sub(1, std::memory_order_acq_rel);
}
[[nodiscard]] bool has_background_workers() const noexcept override { return false; }
void shutdown() noexcept
{
accepting_.store(false, std::memory_order_release);
}
[[nodiscard]] bool is_accepting() const noexcept
{
return accepting_.load(std::memory_order_acquire);
}
[[nodiscard]] std::size_t pending_normal() const noexcept
{
return pending_normal_.load(std::memory_order_acquire);
}
[[nodiscard]] std::size_t max_queue() const noexcept { return max_queue_; }
// Resume one pending coroutine. Returns false if none was pending. // Resume one pending coroutine. Returns false if none was pending.
bool run_one() bool run_one()
{ {
if (auto c = completion_queue_.try_pop(); c.has_value()) {
detail::ExecutorThreadGuard guard{this};
c->resume();
return true;
}
auto h = queue_.try_pop(); auto h = queue_.try_pop();
if (!h) { if (!h) {
return false; return false;
} }
pending_normal_.fetch_sub(1, std::memory_order_acq_rel);
detail::ExecutorThreadGuard guard{this};
h->resume(); h->resume();
return true; return true;
} }
@@ -58,10 +240,17 @@ public:
return count; return count;
} }
[[nodiscard]] bool empty() const noexcept { return queue_.empty(); } [[nodiscard]] bool empty() const noexcept
{
return completion_queue_.empty() && queue_.empty();
}
private: private:
MpscQueue<std::coroutine_handle<>> queue_; std::size_t max_queue_{0};
std::atomic<std::size_t> pending_normal_{0};
std::atomic<bool> accepting_{true};
MpscQueue<std::coroutine_handle<>> queue_{};
MpscQueue<std::coroutine_handle<>> completion_queue_{};
}; };
// ── schedule_on ─────────────────────────────────────────────────────────────── // ── schedule_on ───────────────────────────────────────────────────────────────
@@ -112,4 +301,61 @@ inline void spawn(Executor& executor, Coro::Task<void> task)
Detail::spawn_impl(executor, std::move(task)); Detail::spawn_impl(executor, std::move(task));
} }
struct ScheduleStatusAwaiter {
Executor& executor;
OperationOptions options{};
const Void::Time::MonotonicClock* clock{&Void::Time::SystemMonotonicClock::instance()};
Void::Result::Result<void> pre_outcome{};
[[nodiscard]] bool await_ready() noexcept
{
if (options.stop.stop_requested()) {
pre_outcome = std::unexpected{make_async_error(
AsyncErrorCode::cancelled, "schedule_on cancelled before scheduling")};
return true;
}
if (is_deadline_expired(options, *clock)) {
pre_outcome = std::unexpected{make_async_error(
AsyncErrorCode::timeout, "schedule_on deadline expired before scheduling")};
return true;
}
return false;
}
[[nodiscard]] bool await_suspend(std::coroutine_handle<> handle)
{
const auto post_res = executor.try_post(handle);
if (!post_res.has_value()) {
pre_outcome = std::unexpected{make_async_error(
post_res.error(), "schedule_on rejected by executor")};
return false;
}
return true;
}
[[nodiscard]] Void::Result::Result<void> await_resume() noexcept
{
if (!pre_outcome.has_value()) {
return pre_outcome;
}
if (options.stop.stop_requested()) {
return std::unexpected{make_async_error(
AsyncErrorCode::cancelled, "schedule_on cancelled before execution")};
}
if (is_deadline_expired(options, *clock)) {
return std::unexpected{make_async_error(
AsyncErrorCode::timeout, "schedule_on deadline expired before execution")};
}
return {};
}
};
[[nodiscard]] inline ScheduleStatusAwaiter schedule_on(
Executor& executor,
OperationOptions options,
const Void::Time::MonotonicClock& clock = Void::Time::SystemMonotonicClock::instance()) noexcept
{
return ScheduleStatusAwaiter{executor, std::move(options), &clock};
}
} // namespace Void::Async } // namespace Void::Async
+410
View File
@@ -0,0 +1,410 @@
#pragma once
#include <Void/Async/Detail/Types.hpp>
#include <Void/Async/Executor.hpp>
#include <atomic>
#include <coroutine>
#include <cstdint>
#include <expected>
#include <memory>
#include <optional>
#include <stop_token>
#include <string>
#include <type_traits>
#include <utility>
namespace Void::Async
{
enum class StopBehavior {
notify_only,
settle_cancelled
};
// Move-only, single-delivery handle for resuming a suspended continuation on
// its bound completion lane (or inline when no executor was supplied).
class ResumeTicket
{
public:
ResumeTicket() noexcept = default;
explicit ResumeTicket(std::coroutine_handle<> handle,
Executor* executor = nullptr) noexcept
: handle_(handle)
, executor_(executor)
{
}
ResumeTicket(ResumeTicket&& other) noexcept
: handle_(std::exchange(other.handle_, {}))
, executor_(std::exchange(other.executor_, nullptr))
{
}
ResumeTicket& operator=(ResumeTicket&& other) noexcept
{
if (this != &other) {
handle_ = std::exchange(other.handle_, {});
executor_ = std::exchange(other.executor_, nullptr);
}
return *this;
}
ResumeTicket(const ResumeTicket&) = delete;
ResumeTicket& operator=(const ResumeTicket&) = delete;
[[nodiscard]] explicit operator bool() const noexcept
{
return static_cast<bool>(handle_);
}
[[nodiscard]] std::coroutine_handle<> handle() const noexcept { return handle_; }
[[nodiscard]] Executor* executor() const noexcept { return executor_; }
void dispatch()
{
auto h = std::exchange(handle_, {});
auto* ex = std::exchange(executor_, nullptr);
if (!h) {
return;
}
if (ex != nullptr) {
ex->post_completion(h);
} else {
h.resume();
}
}
void resume_inline()
{
auto h = std::exchange(handle_, {});
executor_ = nullptr;
if (h) {
h.resume();
}
}
[[nodiscard]] std::coroutine_handle<> release() noexcept
{
executor_ = nullptr;
return std::exchange(handle_, {});
}
private:
std::coroutine_handle<> handle_{};
Executor* executor_{nullptr};
};
// Thread-safe shared operation state arbitrating backend work refs, external
// stop intent, single-winner outcome selection, and post-backend-release
// continuation delivery.
template <typename T = void>
class OperationState : public std::enable_shared_from_this<OperationState<T>>
{
public:
using OutcomeType = std::expected<T, Void::Result::Error>;
struct Awaitable {
std::shared_ptr<OperationState<T>> state;
Executor* resume_executor{nullptr};
[[nodiscard]] bool await_ready() const noexcept { return false; }
[[nodiscard]] bool await_suspend(std::coroutine_handle<> handle) noexcept
{
return state->try_arm_suspend(handle, resume_executor);
}
[[nodiscard]] OutcomeType await_resume()
{
return state->take_result();
}
};
[[nodiscard]] static std::shared_ptr<OperationState<T>> create(
OperationOptions options = {},
Executor* resume_executor = nullptr,
StopBehavior stop_behavior = StopBehavior::notify_only)
{
auto ptr = std::shared_ptr<OperationState<T>>(
new OperationState<T>(resume_executor, stop_behavior, options.deadline));
if (options.stop.stop_possible()) {
ptr->stop_cb_.emplace(options.stop, StopForwarder{ptr.get()});
}
return ptr;
}
OperationState(const OperationState&) = delete;
OperationState& operator=(const OperationState&) = delete;
OperationState(OperationState&&) = delete;
OperationState& operator=(OperationState&&) = delete;
[[nodiscard]] std::stop_token stop_token() const noexcept
{
return stop_source_.get_token();
}
[[nodiscard]] bool stop_requested() const noexcept
{
return (sync_.load(std::memory_order_acquire) & kStopRequestedFlag) != 0 ||
stop_source_.stop_requested();
}
[[nodiscard]] const std::optional<Void::Time::MonotonicClock::time_point>&
deadline() const noexcept
{
return deadline_;
}
[[nodiscard]] bool is_deadline_expired(
const Void::Time::MonotonicClock& clock =
Void::Time::SystemMonotonicClock::instance()) const noexcept
{
return deadline_.has_value() && clock.now() >= *deadline_;
}
bool request_stop() noexcept
{
sync_.fetch_or(kStopRequestedFlag, std::memory_order_acq_rel);
const bool triggered = stop_source_.request_stop();
if (stop_behavior_ == StopBehavior::settle_cancelled) {
if (auto ticket = try_commit_cancelled("Operation cancelled");
ticket.has_value()) {
ticket->dispatch();
}
}
return triggered;
}
void acquire_backend_ref() noexcept
{
sync_.fetch_add(kRefStep, std::memory_order_acq_rel);
}
[[nodiscard]] std::optional<ResumeTicket> release_backend_ref() noexcept
{
const std::uint64_t prev = sync_.fetch_sub(kRefStep, std::memory_order_acq_rel);
const std::uint64_t cur = prev - kRefStep;
if ((cur >> kRefShift) != 0) {
return std::nullopt;
}
return maybe_claim_ticket();
}
void release_backend_ref_and_dispatch()
{
if (auto ticket = release_backend_ref(); ticket.has_value()) {
ticket->dispatch();
}
}
template <typename U = T>
requires (!std::is_void_v<U>)
[[nodiscard]] std::optional<ResumeTicket> try_commit_value(U value)
{
return settle_with(DomainOutcomeKind::succeeded,
[&](std::optional<OutcomeType>& slot) {
slot.emplace(std::in_place, std::move(value));
});
}
template <typename U = T>
requires (std::is_void_v<U>)
[[nodiscard]] std::optional<ResumeTicket> try_commit_value()
{
return settle_with(DomainOutcomeKind::succeeded,
[](std::optional<OutcomeType>& slot) {
slot.emplace();
});
}
[[nodiscard]] std::optional<ResumeTicket> try_commit_error(
Void::Result::Error err,
DomainOutcomeKind kind = DomainOutcomeKind::failed)
{
return settle_with(kind, [&](std::optional<OutcomeType>& slot) {
slot.emplace(std::unexpected{std::move(err)});
});
}
[[nodiscard]] std::optional<ResumeTicket> try_commit_not_committed(
std::string message = "Operation stopped before commit")
{
return try_commit_error(
make_async_error(AsyncErrorCode::cancelled, std::move(message)),
DomainOutcomeKind::not_committed);
}
[[nodiscard]] std::optional<ResumeTicket> try_commit_unknown(
std::string message = "Commit state unknown after backend failure")
{
return try_commit_error(
make_async_error(AsyncErrorCode::backend_error, std::move(message)),
DomainOutcomeKind::unknown);
}
[[nodiscard]] std::optional<ResumeTicket> try_commit_cancelled(
std::string message = "Operation cancelled")
{
return try_commit_error(
make_async_error(AsyncErrorCode::cancelled, std::move(message)),
DomainOutcomeKind::cancelled);
}
[[nodiscard]] std::optional<ResumeTicket> try_commit_timeout(
std::string message = "Operation deadline expired")
{
return try_commit_error(
make_async_error(AsyncErrorCode::timeout, std::move(message)),
DomainOutcomeKind::failed);
}
[[nodiscard]] bool try_arm_suspend(std::coroutine_handle<> continuation,
Executor* resume_exec = nullptr) noexcept
{
continuation_ = continuation;
if (resume_exec != nullptr) {
resume_executor_ = resume_exec;
}
std::uint64_t cur = sync_.load(std::memory_order_acquire);
for (;;) {
if ((cur & kSettledFlag) != 0 &&
(cur >> kRefShift) == 0 &&
(cur & kDispatchedFlag) == 0) {
if (sync_.compare_exchange_weak(
cur,
cur | kSuspendedFlag | kDispatchedFlag,
std::memory_order_acq_rel,
std::memory_order_acquire)) {
continuation_ = {};
resume_executor_ = nullptr;
return false;
}
} else {
if (sync_.compare_exchange_weak(
cur,
cur | kSuspendedFlag,
std::memory_order_acq_rel,
std::memory_order_acquire)) {
return true;
}
}
}
}
[[nodiscard]] bool is_settled() const noexcept
{
return (sync_.load(std::memory_order_acquire) & kSettledFlag) != 0;
}
[[nodiscard]] std::uint64_t backend_ref_count() const noexcept
{
return sync_.load(std::memory_order_acquire) >> kRefShift;
}
[[nodiscard]] DomainOutcomeKind outcome_kind() const noexcept
{
return domain_outcome_.load(std::memory_order_acquire);
}
[[nodiscard]] OutcomeType take_result()
{
// Acquire on sync_ ensures visibility of the winner's write to outcome_.
(void)sync_.load(std::memory_order_acquire);
if (!outcome_.has_value()) {
return std::unexpected{make_async_error(
AsyncErrorCode::backend_error,
"OperationState result accessed before settlement")};
}
return std::move(*outcome_);
}
[[nodiscard]] Awaitable awaitable(Executor* resume_exec = nullptr) noexcept
{
return Awaitable{this->shared_from_this(), resume_exec};
}
[[nodiscard]] Awaitable operator co_await() noexcept
{
return awaitable(nullptr);
}
private:
static constexpr std::uint64_t kSettledFlag = 1ULL << 0;
static constexpr std::uint64_t kSuspendedFlag = 1ULL << 1;
static constexpr std::uint64_t kDispatchedFlag = 1ULL << 2;
static constexpr std::uint64_t kStopRequestedFlag = 1ULL << 3;
static constexpr std::uint64_t kRefShift = 4;
static constexpr std::uint64_t kRefStep = 1ULL << kRefShift;
struct StopForwarder {
OperationState* self{nullptr};
void operator()() const noexcept
{
if (self != nullptr) {
self->request_stop();
}
}
};
OperationState(Executor* resume_executor,
StopBehavior stop_behavior,
std::optional<Void::Time::MonotonicClock::time_point> deadline) noexcept
: stop_behavior_(stop_behavior)
, deadline_(deadline)
, resume_executor_(resume_executor)
{
}
template <typename InitFn>
[[nodiscard]] std::optional<ResumeTicket> settle_with(
DomainOutcomeKind kind, InitFn&& init_fn)
{
if (outcome_claimed_.exchange(true, std::memory_order_acq_rel)) {
return std::nullopt;
}
init_fn(outcome_);
domain_outcome_.store(kind, std::memory_order_release);
sync_.fetch_or(kSettledFlag, std::memory_order_acq_rel);
return maybe_claim_ticket();
}
[[nodiscard]] std::optional<ResumeTicket> maybe_claim_ticket() noexcept
{
std::uint64_t cur = sync_.load(std::memory_order_acquire);
for (;;) {
if ((cur & kSettledFlag) == 0 ||
(cur & kSuspendedFlag) == 0 ||
(cur & kDispatchedFlag) != 0 ||
(cur >> kRefShift) != 0) {
return std::nullopt;
}
if (sync_.compare_exchange_weak(
cur,
cur | kDispatchedFlag,
std::memory_order_acq_rel,
std::memory_order_acquire)) {
return ResumeTicket{
std::exchange(continuation_, {}),
std::exchange(resume_executor_, nullptr)};
}
}
}
std::stop_source stop_source_{};
StopBehavior stop_behavior_{StopBehavior::notify_only};
std::optional<Void::Time::MonotonicClock::time_point> deadline_{};
std::atomic<std::uint64_t> sync_{0};
std::atomic<bool> outcome_claimed_{false};
std::atomic<DomainOutcomeKind> domain_outcome_{DomainOutcomeKind::pending};
std::optional<OutcomeType> outcome_{};
std::coroutine_handle<> continuation_{};
Executor* resume_executor_{nullptr};
// MUST stay LAST: destroyed first in ~OperationState() to synchronize any
// in-flight external stop callback before members above are torn down.
std::optional<std::stop_callback<StopForwarder>> stop_cb_{};
};
} // namespace Void::Async
+798
View File
@@ -0,0 +1,798 @@
#pragma once
#include <Void/Async/Detail/Types.hpp>
#include <Void/Async/Executor.hpp>
#include <Void/Async/Operation.hpp>
#include <Void/Async/Task.hpp>
#include <concepts>
#include <condition_variable>
#include <coroutine>
#include <cstddef>
#include <exception>
#include <expected>
#include <functional>
#include <limits>
#include <memory>
#include <mutex>
#include <optional>
#include <stop_token>
#include <string>
#include <string_view>
#include <thread>
#include <type_traits>
#include <utility>
namespace Void::Async
{
struct TaskScopeOptions {
std::size_t max_tasks{1024};
std::stop_token parent_stop{};
bool stop_on_first_error{true};
[[nodiscard]] static constexpr TaskScopeOptions unlimited(
std::stop_token parent_stop = {},
bool stop_on_first_error = true) noexcept
{
return TaskScopeOptions{
std::numeric_limits<std::size_t>::max(),
parent_stop,
stop_on_first_error};
}
};
namespace detail
{
class ScopeControl;
class ChildTaskControl : public std::enable_shared_from_this<ChildTaskControl>
{
public:
explicit ChildTaskControl(Executor& executor) noexcept
: executor_(executor)
{
}
ChildTaskControl(const ChildTaskControl&) = delete;
ChildTaskControl& operator=(const ChildTaskControl&) = delete;
[[nodiscard]] std::stop_token stop_token() const noexcept
{
return stop_source_.get_token();
}
bool request_stop() noexcept
{
return stop_source_.request_stop();
}
void attach_stops(std::stop_token scope_stop, std::stop_token option_stop)
{
if (scope_stop.stop_possible()) {
scope_stop_cb_.emplace(scope_stop, StopForwarder{this});
}
if (option_stop.stop_possible()) {
option_stop_cb_.emplace(option_stop, StopForwarder{this});
}
}
void set_error(Void::Result::Error err)
{
std::lock_guard lk{mu_};
error_ = std::move(err);
}
void mark_finished()
{
std::coroutine_handle<> waiter{};
{
std::lock_guard lk{mu_};
finished_ = true;
waiter = std::exchange(async_waiter_, {});
}
cv_.notify_all();
if (waiter) {
executor_.post_completion(waiter);
}
}
[[nodiscard]] bool done() const
{
std::lock_guard lk{mu_};
return finished_;
}
[[nodiscard]] bool try_register_waiter(std::coroutine_handle<> waiter)
{
std::lock_guard lk{mu_};
if (finished_) {
return false;
}
async_waiter_ = waiter;
return true;
}
[[nodiscard]] Void::Result::Result<void> take_outcome() const
{
std::lock_guard lk{mu_};
if (error_.has_value()) {
return std::unexpected{*error_};
}
return {};
}
[[nodiscard]] Void::Result::Result<void> join_blocking()
{
if (executor_.is_executor_thread()) {
return std::unexpected{make_async_error(
AdmissionError::self_join,
"JoinHandle::join_blocking called on active executor thread")};
}
std::unique_lock lk{mu_};
cv_.wait(lk, [this] { return finished_; });
if (error_.has_value()) {
return std::unexpected{*error_};
}
return {};
}
private:
struct StopForwarder {
ChildTaskControl* self{nullptr};
void operator()() const noexcept
{
if (self != nullptr) {
self->request_stop();
}
}
};
Executor& executor_;
std::stop_source stop_source_{};
mutable std::mutex mu_{};
std::condition_variable cv_{};
bool finished_{false};
std::optional<Void::Result::Error> error_{};
std::coroutine_handle<> async_waiter_{};
// MUST stay LAST so stop callbacks synchronize before members destruct.
std::optional<std::stop_callback<StopForwarder>> scope_stop_cb_{};
std::optional<std::stop_callback<StopForwarder>> option_stop_cb_{};
};
class ScopeControl : public std::enable_shared_from_this<ScopeControl>
{
public:
[[nodiscard]] static std::shared_ptr<ScopeControl> create(
Executor& executor, TaskScopeOptions options)
{
auto ptr = std::shared_ptr<ScopeControl>(
new ScopeControl(executor, options));
if (options.parent_stop.stop_possible()) {
ptr->parent_stop_cb_.emplace(options.parent_stop, StopForwarder{ptr.get()});
}
return ptr;
}
ScopeControl(const ScopeControl&) = delete;
ScopeControl& operator=(const ScopeControl&) = delete;
[[nodiscard]] Executor& executor() noexcept { return executor_; }
[[nodiscard]] std::stop_token stop_token() const noexcept
{
return stop_source_.get_token();
}
bool request_stop() noexcept
{
return stop_source_.request_stop();
}
void close() noexcept
{
std::lock_guard lk{mu_};
closed_ = true;
}
[[nodiscard]] std::expected<void, AdmissionError> try_reserve(
const OperationOptions& op,
const Void::Time::MonotonicClock& clock)
{
if (max_tasks_ == 0) {
return std::unexpected{AdmissionError::invalid_argument};
}
if (op.stop.stop_requested()) {
return std::unexpected{AdmissionError::stopped};
}
if (is_deadline_expired(op, clock)) {
return std::unexpected{AdmissionError::deadline_expired};
}
std::lock_guard lk{mu_};
if (closed_ || stop_source_.stop_requested()) {
return std::unexpected{AdmissionError::stopped};
}
if (active_tasks_ >= max_tasks_) {
return std::unexpected{AdmissionError::overloaded};
}
++active_tasks_;
return {};
}
void release_reservation()
{
on_task_finished();
}
void record_exception(std::exception_ptr ex, std::string_view what)
{
bool trigger_stop = false;
{
std::lock_guard lk{mu_};
++failure_count_;
if (!first_exception_) {
first_exception_ = ex;
first_error_ = make_async_error(
AsyncErrorCode::backend_error,
what.empty()
? std::string{"Unhandled exception in TaskScope task"}
: std::string{what});
trigger_stop = stop_on_first_error_;
}
}
if (trigger_stop) {
request_stop();
}
}
void on_task_finished()
{
std::coroutine_handle<> waiter{};
bool notify = false;
{
std::lock_guard lk{mu_};
--active_tasks_;
if (active_tasks_ == 0) {
notify = true;
waiter = std::exchange(async_join_waiter_, {});
}
}
if (notify) {
cv_.notify_all();
if (waiter) {
executor_.post_completion(waiter);
}
}
}
[[nodiscard]] bool try_begin_async_join(std::coroutine_handle<> waiter)
{
std::lock_guard lk{mu_};
closed_ = true;
if (active_tasks_ == 0) {
return false;
}
async_join_waiter_ = waiter;
return true;
}
[[nodiscard]] Void::Result::Result<void> finish_outcome() const
{
std::lock_guard lk{mu_};
if (first_error_.has_value()) {
return std::unexpected{*first_error_};
}
return {};
}
[[nodiscard]] Void::Result::Result<void> join_blocking()
{
if (executor_.is_executor_thread()) {
return std::unexpected{make_async_error(
AdmissionError::self_join,
"TaskScope::join_blocking called on active executor thread")};
}
std::unique_lock lk{mu_};
closed_ = true;
cv_.wait(lk, [this] { return active_tasks_ == 0; });
if (first_error_.has_value()) {
return std::unexpected{*first_error_};
}
return {};
}
[[nodiscard]] std::size_t active_count() const
{
std::lock_guard lk{mu_};
return active_tasks_;
}
[[nodiscard]] std::size_t failure_count() const
{
std::lock_guard lk{mu_};
return failure_count_;
}
[[nodiscard]] bool has_exception() const
{
std::lock_guard lk{mu_};
return static_cast<bool>(first_exception_);
}
[[nodiscard]] std::exception_ptr first_exception() const
{
std::lock_guard lk{mu_};
return first_exception_;
}
private:
struct StopForwarder {
ScopeControl* self{nullptr};
void operator()() const noexcept
{
if (self != nullptr) {
self->request_stop();
}
}
};
ScopeControl(Executor& executor, TaskScopeOptions options) noexcept
: executor_(executor)
, max_tasks_(options.max_tasks)
, stop_on_first_error_(options.stop_on_first_error)
{
}
Executor& executor_;
std::size_t max_tasks_{1024};
bool stop_on_first_error_{true};
std::stop_source stop_source_{};
mutable std::mutex mu_{};
std::condition_variable cv_{};
std::size_t active_tasks_{0};
std::size_t failure_count_{0};
bool closed_{false};
std::exception_ptr first_exception_{};
std::optional<Void::Result::Error> first_error_{};
std::coroutine_handle<> async_join_waiter_{};
// MUST stay LAST: waits for any active parent stop callback on destruction.
std::optional<std::stop_callback<StopForwarder>> parent_stop_cb_{};
};
struct TakePromiseTaskTag {};
struct GetScopePtrTag {};
struct GetChildPtrTag {};
struct ScopeRunner {
struct promise_type {
std::shared_ptr<ScopeControl> scope{};
std::shared_ptr<ChildTaskControl> child{};
std::optional<Coro::Task<void>> task{};
ScopeRunner get_return_object() noexcept
{
return ScopeRunner{
std::coroutine_handle<promise_type>::from_promise(*this)};
}
std::suspend_always initial_suspend() noexcept { return {}; }
struct FinalAwaiter {
bool await_ready() const noexcept { return false; }
void await_suspend(std::coroutine_handle<promise_type> h) noexcept
{
auto sc = std::move(h.promise().scope);
auto ch = std::move(h.promise().child);
h.promise().task.reset();
// Destroy the coroutine frame completely before decrementing active
// task counters or waking any join waiter.
h.destroy();
if (ch) {
ch->mark_finished();
}
if (sc) {
sc->on_task_finished();
}
}
void await_resume() const noexcept {}
};
FinalAwaiter final_suspend() noexcept { return {}; }
void return_void() noexcept {}
void unhandled_exception() noexcept {}
auto await_transform(TakePromiseTaskTag) noexcept
{
struct Awaiter {
promise_type* p;
bool await_ready() const noexcept { return true; }
void await_suspend(std::coroutine_handle<>) noexcept {}
Coro::Task<void> await_resume() noexcept
{
auto t = std::move(*p->task);
p->task.reset();
return t;
}
};
return Awaiter{this};
}
auto await_transform(GetScopePtrTag) noexcept
{
struct Awaiter {
promise_type* p;
bool await_ready() const noexcept { return true; }
void await_suspend(std::coroutine_handle<>) noexcept {}
std::shared_ptr<ScopeControl> await_resume() noexcept
{
return p->scope;
}
};
return Awaiter{this};
}
auto await_transform(GetChildPtrTag) noexcept
{
struct Awaiter {
promise_type* p;
bool await_ready() const noexcept { return true; }
void await_suspend(std::coroutine_handle<>) noexcept {}
std::shared_ptr<ChildTaskControl> await_resume() noexcept
{
return p->child;
}
};
return Awaiter{this};
}
template <typename A>
decltype(auto) await_transform(A&& awaitable) noexcept
{
return std::forward<A>(awaitable);
}
};
std::coroutine_handle<promise_type> handle{};
};
inline ScopeRunner make_scope_runner()
{
auto task = co_await TakePromiseTaskTag{};
auto scope = co_await GetScopePtrTag{};
auto child = co_await GetChildPtrTag{};
try {
co_await std::move(task);
} catch (const std::exception& ex) {
if (child) {
child->set_error(make_async_error(AsyncErrorCode::backend_error, ex.what()));
}
if (scope) {
scope->record_exception(std::current_exception(), ex.what());
}
} catch (...) {
constexpr std::string_view kUnknown =
"Unhandled non-std exception in TaskScope task";
if (child) {
child->set_error(
make_async_error(AsyncErrorCode::backend_error, std::string{kUnknown}));
}
if (scope) {
scope->record_exception(std::current_exception(), kUnknown);
}
}
}
} // namespace detail
class JoinHandle
{
public:
explicit JoinHandle(std::shared_ptr<detail::ChildTaskControl> control) noexcept
: control_(std::move(control))
{
}
[[nodiscard]] bool done() const
{
return !control_ || control_->done();
}
bool request_stop() noexcept
{
return control_ ? control_->request_stop() : false;
}
[[nodiscard]] std::stop_token stop_token() const noexcept
{
return control_ ? control_->stop_token() : std::stop_token{};
}
struct JoinAwaiter {
std::shared_ptr<detail::ChildTaskControl> control;
[[nodiscard]] bool await_ready() const noexcept
{
return !control || control->done();
}
[[nodiscard]] bool await_suspend(std::coroutine_handle<> waiter)
{
return control->try_register_waiter(waiter);
}
[[nodiscard]] Void::Result::Result<void> await_resume() const
{
return control ? control->take_outcome() : Void::Result::Result<void>{};
}
};
[[nodiscard]] JoinAwaiter join() const noexcept
{
return JoinAwaiter{control_};
}
[[nodiscard]] JoinAwaiter operator co_await() const noexcept
{
return join();
}
[[nodiscard]] Void::Result::Result<void> join_blocking() const
{
return control_ ? control_->join_blocking() : Void::Result::Result<void>{};
}
private:
std::shared_ptr<detail::ChildTaskControl> control_{};
};
class TaskScope
{
public:
explicit TaskScope(
Executor& executor,
TaskScopeOptions options = {},
const Void::Time::MonotonicClock& clock =
Void::Time::SystemMonotonicClock::instance())
: control_(detail::ScopeControl::create(executor, options))
, clock_(clock)
{
}
~TaskScope()
{
control_->request_stop();
control_->close();
if (control_->active_count() > 0) {
if (!control_->executor().has_background_workers()) {
if (auto* manual = dynamic_cast<ManualExecutor*>(&control_->executor())) {
(void)join_pumping(*manual);
}
} else if (!control_->executor().is_executor_thread()) {
(void)control_->join_blocking();
}
}
}
TaskScope(const TaskScope&) = delete;
TaskScope& operator=(const TaskScope&) = delete;
TaskScope(TaskScope&&) = delete;
TaskScope& operator=(TaskScope&&) = delete;
// Reserve-then-transfer spawn: failed admission preserves `task` intact in
// the caller without destroying or losing its coroutine frame.
[[nodiscard]] std::expected<JoinHandle, AdmissionError>
spawn(Coro::Task<void>&& task, OperationOptions options = {})
{
if (!task.handle() || task.done()) {
return std::unexpected{AdmissionError::invalid_argument};
}
return admit_and_launch(options, &task, nullptr);
}
template <typename F>
requires (!std::same_as<std::remove_cvref_t<F>, Coro::Task<void>>) &&
std::invocable<F, std::stop_token> &&
std::same_as<std::invoke_result_t<F, std::stop_token>, Coro::Task<void>>
[[nodiscard]] std::expected<JoinHandle, AdmissionError>
spawn(F&& factory, OperationOptions options = {})
{
return admit_and_launch(
options,
nullptr,
[&](std::stop_token st) -> Coro::Task<void> {
return std::invoke(std::forward<F>(factory), st);
});
}
bool request_stop() noexcept { return control_->request_stop(); }
void close() noexcept { control_->close(); }
[[nodiscard]] std::stop_token stop_token() const noexcept { return control_->stop_token(); }
[[nodiscard]] std::size_t active_count() const { return control_->active_count(); }
[[nodiscard]] std::size_t failure_count() const { return control_->failure_count(); }
[[nodiscard]] bool has_exception() const { return control_->has_exception(); }
[[nodiscard]] std::exception_ptr first_exception() const { return control_->first_exception(); }
struct ScopeJoinAwaiter {
std::shared_ptr<detail::ScopeControl> control;
[[nodiscard]] bool await_ready() const noexcept
{
return false;
}
[[nodiscard]] bool await_suspend(std::coroutine_handle<> waiter)
{
return control->try_begin_async_join(waiter);
}
[[nodiscard]] Void::Result::Result<void> await_resume() const
{
return control->finish_outcome();
}
};
[[nodiscard]] ScopeJoinAwaiter join() noexcept
{
return ScopeJoinAwaiter{control_};
}
[[nodiscard]] Void::Result::Result<void> join_blocking()
{
return control_->join_blocking();
}
[[nodiscard]] Void::Result::Result<void> join_pumping(ManualExecutor& manual)
{
control_->close();
while (control_->active_count() > 0) {
if (manual.drain() == 0 && control_->active_count() > 0) {
std::this_thread::yield();
}
}
return control_->finish_outcome();
}
[[nodiscard]] Void::Result::Result<void> join_pumping()
{
auto* manual = dynamic_cast<ManualExecutor*>(&control_->executor());
if (manual == nullptr) {
return std::unexpected{make_async_error(
AsyncErrorCode::invalid_argument,
"TaskScope::join_pumping requires ManualExecutor")};
}
return join_pumping(*manual);
}
private:
template <typename FactoryFn = std::nullptr_t>
[[nodiscard]] std::expected<JoinHandle, AdmissionError>
admit_and_launch(const OperationOptions& options,
Coro::Task<void>* existing_task,
FactoryFn&& factory)
{
if (auto sr = control_->try_reserve(options, clock_); !sr.has_value()) {
return std::unexpected{sr.error()};
}
Executor& exec = control_->executor();
const bool use_reserved = exec.supports_reservation();
if (use_reserved) {
if (auto er = exec.try_reserve_slot(); !er.has_value()) {
control_->release_reservation();
return std::unexpected{er.error()};
}
}
auto child = std::make_shared<detail::ChildTaskControl>(exec);
child->attach_stops(control_->stop_token(), options.stop);
detail::ScopeRunner runner{};
try {
runner = detail::make_scope_runner();
auto& prom = runner.handle.promise();
prom.scope = control_;
prom.child = child;
if (existing_task != nullptr) {
prom.task.emplace(std::move(*existing_task));
} else if constexpr (!std::is_null_pointer_v<std::decay_t<FactoryFn>>) {
prom.task.emplace(factory(child->stop_token()));
}
} catch (...) {
if (runner.handle) {
if (existing_task != nullptr && runner.handle.promise().task.has_value()) {
*existing_task = std::move(*runner.handle.promise().task);
}
runner.handle.promise().scope.reset();
runner.handle.promise().child.reset();
runner.handle.destroy();
}
if (use_reserved) {
exec.release_reserved();
}
control_->release_reservation();
throw;
}
auto rollback_unstarted = [&]() {
if (existing_task != nullptr && runner.handle.promise().task.has_value()) {
*existing_task = std::move(*runner.handle.promise().task);
}
runner.handle.promise().scope.reset();
runner.handle.promise().child.reset();
runner.handle.destroy();
if (use_reserved) {
exec.release_reserved();
}
control_->release_reservation();
};
if (use_reserved) {
try {
exec.commit_reserved(runner.handle);
} catch (...) {
rollback_unstarted();
return std::unexpected{AdmissionError::overloaded};
}
} else {
auto post_res = exec.try_post(runner.handle);
if (!post_res.has_value()) {
rollback_unstarted();
return std::unexpected{post_res.error()};
}
}
return JoinHandle{std::move(child)};
}
std::shared_ptr<detail::ScopeControl> control_;
const Void::Time::MonotonicClock& clock_;
};
// Explicit structured lifetime owner for detached/background fire-and-forget work.
class DetachedOwner
{
public:
explicit DetachedOwner(
Executor& executor,
TaskScopeOptions options = {},
const Void::Time::MonotonicClock& clock =
Void::Time::SystemMonotonicClock::instance())
: scope_(executor, options, clock)
{
}
[[nodiscard]] std::expected<JoinHandle, AdmissionError>
spawn(Coro::Task<void>&& task, OperationOptions options = {})
{
return scope_.spawn(std::move(task), std::move(options));
}
template <typename F>
requires (!std::same_as<std::remove_cvref_t<F>, Coro::Task<void>>) &&
std::invocable<F, std::stop_token> &&
std::same_as<std::invoke_result_t<F, std::stop_token>, Coro::Task<void>>
[[nodiscard]] std::expected<JoinHandle, AdmissionError>
spawn(F&& factory, OperationOptions options = {})
{
return scope_.spawn(std::forward<F>(factory), std::move(options));
}
bool request_stop() noexcept { return scope_.request_stop(); }
void close() noexcept { scope_.close(); }
[[nodiscard]] std::stop_token stop_token() const noexcept { return scope_.stop_token(); }
[[nodiscard]] std::size_t active_count() const { return scope_.active_count(); }
[[nodiscard]] std::size_t failure_count() const { return scope_.failure_count(); }
[[nodiscard]] Void::Result::Result<void> drain_blocking() { return scope_.join_blocking(); }
[[nodiscard]] Void::Result::Result<void> drain_pumping() { return scope_.join_pumping(); }
[[nodiscard]] Void::Result::Result<void> drain_pumping(ManualExecutor& manual)
{
return scope_.join_pumping(manual);
}
private:
TaskScope scope_;
};
} // namespace Void::Async
File diff suppressed because it is too large. Load diff
+3
View File
@@ -0,0 +1,3 @@
void_add_module(Algorithms
INTERNAL_DEPS Core Math
)
+2 -2
View File
@@ -1,3 +1,3 @@
void_add_module(Async void_add_module(Async
INTERNAL_DEPS LogState INTERNAL_DEPS Functional Time LogState
) )
+11
View File
@@ -0,0 +1,11 @@
# Void::Unicode Data & Specification Manifest
- **Unicode Standard Version**: `17.0.0`
- **Official UCD Base URL**: `https://www.unicode.org/Public/17.0.0/ucd/`
- **Encoding & Scalar Specification**: Unicode Standard Section 3.9 (Forms & UTF-8/UTF-16/UTF-32 definitions D89-D92)
- **License**: Unicode License V3 (`Unicode-3.0`, https://www.unicode.org/license.txt)
## Scope Notes
- `Void::Unicode` P1 implements Unicode `17.0.0` scalar value classification, UTF-8 / UTF-16 / UTF-32 strict validation, bounded transcoding (owning and non-allocating `std::span` destinations), one-unit repair (`U+FFFD`), and incremental streaming decoders.
- `Void::Text` remains intentionally Unicode-free (ASCII-only helpers in `M-TEXT-02`).
- Generated UCD character property tables (normalization, grapheme cluster segmentation, casefolding) belong to subsequent phases and will append table hashes here when introduced.
+3
View File
@@ -0,0 +1,3 @@
void_add_module(Unicode
INTERNAL_DEPS Core Text
)
@@ -0,0 +1,10 @@
cmake_minimum_required(VERSION 4.0)
project(VoidAlgorithmsOnlyConsumer LANGUAGES CXX)
find_package(Void CONFIG REQUIRED COMPONENTS Algorithms)
add_executable(void_algorithms_only_consumer main.cpp)
target_link_libraries(void_algorithms_only_consumer PRIVATE Void::Algorithms)
enable_testing()
add_test(NAME VoidAlgorithmsOnlyConsumer COMMAND void_algorithms_only_consumer)
+20
View File
@@ -0,0 +1,20 @@
#include <Void/Algorithms/Graph.hpp>
#include <vector>
int main()
{
const std::vector<std::vector<std::size_t>> dag{
{1, 2},
{3},
{3},
{},
};
const Void::Algorithms::AdjacencyView view{dag};
const auto sp = Void::Algorithms::shortest_path_unweighted(view, 0, 3);
const auto topo = Void::Algorithms::topological_order(view);
if (!sp || !sp->found || sp->distance != 2 || !topo || topo->order.size() != 4) {
return 1;
}
return 0;
}
+10
View File
@@ -96,6 +96,16 @@ if(_has_binary)
run_consumer(Binary "${install_prefix}" "Binary" ${_no_external_deps}) run_consumer(Binary "${install_prefix}" "Binary" ${_no_external_deps})
endif() endif()
has_modules(_has_algorithms Algorithms Math Core)
if(_has_algorithms)
run_consumer(AlgorithmsOnly "${install_prefix}" "AlgorithmsOnly" ${_no_external_deps})
endif()
has_modules(_has_unicode Unicode Text Core)
if(_has_unicode)
run_consumer(UnicodeOnly "${install_prefix}" "UnicodeOnly" ${_no_external_deps})
endif()
# Foundation consumer with Core-formatting bridge and zero external packages. # Foundation consumer with Core-formatting bridge and zero external packages.
has_modules(_has_foundation Math Text Time Functional Binary FunctionalCoreFormatting Memory Core) has_modules(_has_foundation Math Text Time Functional Binary FunctionalCoreFormatting Memory Core)
if(_has_foundation) if(_has_foundation)
+10
View File
@@ -0,0 +1,10 @@
cmake_minimum_required(VERSION 4.0)
project(VoidUnicodeOnlyConsumer LANGUAGES CXX)
find_package(Void CONFIG REQUIRED COMPONENTS Unicode)
add_executable(void_unicode_only_consumer main.cpp)
target_link_libraries(void_unicode_only_consumer PRIVATE Void::Unicode)
enable_testing()
add_test(NAME VoidUnicodeOnlyConsumer COMMAND void_unicode_only_consumer)
+16
View File
@@ -0,0 +1,16 @@
#include <Void/Unicode/Utf.hpp>
#include <string_view>
int main()
{
if (Void::Unicode::data_version() != std::string_view{"17.0.0"}) {
return 1;
}
const auto u16 = Void::Unicode::utf8_to_utf16("hi \xF0\x9F\x9A\x80");
if (!u16.has_value()) {
return 1;
}
const auto u8 = Void::Unicode::utf16_to_utf8(*u16);
return (u8 && *u8 == "hi \xF0\x9F\x9A\x80") ? 0 : 1;
}
+304
View File
@@ -0,0 +1,304 @@
#include <Void/Algorithms/Graph.hpp>
#include <Void/Testing/Assert.hpp>
#include <Void/Testing/Test.hpp>
#include <atomic>
#include <cstddef>
#include <cstdint>
#include <limits>
#include <span>
#include <stop_token>
#include <vector>
namespace
{
struct HugeMockGraph {
std::size_t count{0};
[[nodiscard]] std::size_t vertex_count() const noexcept { return count; }
[[nodiscard]] std::span<const std::size_t> neighbors(std::size_t) const noexcept { return {}; }
};
struct VersionedChainGraph {
std::vector<std::vector<std::size_t>> adj;
mutable std::atomic<std::uint64_t> ver{1};
std::size_t mutate_after_reads{std::numeric_limits<std::size_t>::max()};
mutable std::size_t reads{0};
[[nodiscard]] std::size_t vertex_count() const noexcept { return adj.size(); }
[[nodiscard]] std::uint64_t version() const noexcept
{
return ver.load(std::memory_order_acquire);
}
[[nodiscard]] std::span<const std::size_t> neighbors(std::size_t u) const noexcept
{
const std::size_t r = ++reads;
if (r >= mutate_after_reads) {
ver.fetch_add(1, std::memory_order_release);
}
return adj[u];
}
};
struct CancellingGraph {
std::vector<std::vector<std::size_t>> adj;
std::stop_source* stop_src{nullptr};
std::size_t cancel_after_reads{std::numeric_limits<std::size_t>::max()};
mutable std::size_t reads{0};
[[nodiscard]] std::size_t vertex_count() const noexcept { return adj.size(); }
[[nodiscard]] std::span<const std::size_t> neighbors(std::size_t u) const noexcept
{
const std::size_t r = ++reads;
if (stop_src != nullptr && r >= cancel_after_reads) {
stop_src->request_stop();
}
return adj[u];
}
};
} // namespace
Void::Testing::Test graph_bfs_dfs_shortest_path_and_csr_views()
{
using Void::Algorithms::AdjacencyView;
using Void::Algorithms::AlgorithmError;
using Void::Algorithms::bfs;
using Void::Algorithms::dfs;
using Void::Algorithms::shortest_path_unweighted;
// 0 -> {1, 2}, 1 -> {3, 4}, 2 -> {4}, 3 -> {5}, 4 -> {}, 5 -> {}, 6 (isolated)
const std::vector<std::vector<std::size_t>> adj{
{1, 2},
{3, 4},
{4},
{5},
{},
{},
{},
};
const AdjacencyView list_view{adj};
const auto bfs_res = bfs(list_view, 0);
Void::Testing::require(bfs_res.has_value());
Void::Testing::expect_eq(bfs_res->order.size(), std::size_t{6});
Void::Testing::expect_eq(bfs_res->order[0], std::size_t{0});
Void::Testing::expect_eq(bfs_res->depth[5], std::size_t{3});
Void::Testing::expect_eq(bfs_res->depth[6], Void::Algorithms::TraversalResult::npos);
Void::Testing::expect_eq(bfs_res->parent[4], std::size_t{1});
const auto dfs_res = dfs(list_view, 0);
Void::Testing::require(dfs_res.has_value());
Void::Testing::expect_eq(dfs_res->order.size(), std::size_t{6});
Void::Testing::expect_eq(dfs_res->order[0], std::size_t{0});
Void::Testing::expect_eq(dfs_res->order[1], std::size_t{1});
Void::Testing::expect_eq(dfs_res->order[2], std::size_t{3});
Void::Testing::expect_eq(dfs_res->order[3], std::size_t{5});
Void::Testing::expect_eq(dfs_res->order[4], std::size_t{4});
Void::Testing::expect_eq(dfs_res->order[5], std::size_t{2});
const auto sp_found = shortest_path_unweighted(list_view, 0, 5);
Void::Testing::require(sp_found.has_value());
Void::Testing::expect(sp_found->found);
Void::Testing::expect_eq(sp_found->distance, std::size_t{3});
Void::Testing::expect_eq(sp_found->path.size(), std::size_t{4});
Void::Testing::expect_eq(sp_found->path[0], std::size_t{0});
Void::Testing::expect_eq(sp_found->path[1], std::size_t{1});
Void::Testing::expect_eq(sp_found->path[2], std::size_t{3});
Void::Testing::expect_eq(sp_found->path[3], std::size_t{5});
const auto sp_self = shortest_path_unweighted(list_view, 2, 2);
Void::Testing::require(sp_self.has_value());
Void::Testing::expect(sp_self->found);
Void::Testing::expect_eq(sp_self->distance, std::size_t{0});
Void::Testing::expect_eq(sp_self->path.size(), std::size_t{1});
const auto sp_missing = shortest_path_unweighted(list_view, 0, 6);
Void::Testing::require(sp_missing.has_value());
Void::Testing::expect(!sp_missing->found);
Void::Testing::expect(sp_missing->path.empty());
// Equivalent CSR view validation
const std::vector<std::size_t> offsets{0, 2, 4, 5, 6, 6, 6, 6};
const std::vector<std::size_t> edges{1, 2, 3, 4, 4, 5};
const auto csr_res = AdjacencyView::try_from_csr(offsets, edges);
Void::Testing::require(csr_res.has_value());
const auto csr_sp = shortest_path_unweighted(*csr_res, 0, 4);
Void::Testing::require(csr_sp.has_value());
Void::Testing::expect_eq(csr_sp->distance, std::size_t{2});
// Malformed CSR rejected
const std::vector<std::size_t> bad_offsets{0, 3, 2};
Void::Testing::expect(
AdjacencyView::try_from_csr(bad_offsets, edges).error().code ==
AlgorithmError::Code::invalid_input);
}
Void::Testing::Test graph_topological_order_and_cycle_witness()
{
using Void::Algorithms::AdjacencyView;
using Void::Algorithms::AlgorithmError;
using Void::Algorithms::topological_order;
// Empty graph is a valid DAG
const std::vector<std::vector<std::size_t>> empty_adj{};
const auto empty_topo = topological_order(AdjacencyView{empty_adj});
Void::Testing::require(empty_topo.has_value());
Void::Testing::expect(empty_topo->order.empty());
// DAG: 0 -> {1, 2}, 1 -> {3}, 2 -> {3}, 3 -> {4}
const std::vector<std::vector<std::size_t>> dag{
{1, 2},
{3},
{3},
{4},
{},
};
const auto topo = topological_order(AdjacencyView{dag});
Void::Testing::require(topo.has_value());
Void::Testing::expect_eq(topo->order.size(), std::size_t{5});
for (std::size_t u = 0; u < dag.size(); ++u) {
for (const std::size_t v : dag[u]) {
Void::Testing::expect(topo->position[u] < topo->position[v]);
}
}
// Cyclic graph: 0 -> 1 -> 2 -> 3 -> 1 plus tail 4
const std::vector<std::vector<std::size_t>> cyclic{
{1},
{2},
{3},
{1, 4},
{},
};
const AdjacencyView cyclic_view{cyclic};
const auto cyc_res = topological_order(cyclic_view);
Void::Testing::expect(!cyc_res.has_value());
Void::Testing::expect(cyc_res.error().code == AlgorithmError::Code::cycle_detected);
const auto& witness = cyc_res.error().cycle;
Void::Testing::require(witness.size() >= 2);
Void::Testing::expect_eq(witness.front(), witness.back());
// Every consecutive pair in witness must be a real edge in the graph
for (std::size_t i = 0; i + 1 < witness.size(); ++i) {
const auto nbrs = cyclic_view.neighbors(witness[i]);
bool found_edge = false;
for (const std::size_t x : nbrs) {
if (x == witness[i + 1]) {
found_edge = true;
break;
}
}
Void::Testing::expect(found_edge);
}
// Self-loop cycle witness [u, u]
const std::vector<std::vector<std::size_t>> self_loop{{0}};
const auto self_res = topological_order(AdjacencyView{self_loop});
Void::Testing::expect(!self_res.has_value());
Void::Testing::expect(self_res.error().code == AlgorithmError::Code::cycle_detected);
Void::Testing::expect_eq(self_res.error().cycle.size(), std::size_t{2});
Void::Testing::expect_eq(self_res.error().cycle[0], std::size_t{0});
Void::Testing::expect_eq(self_res.error().cycle[1], std::size_t{0});
}
Void::Testing::Test graph_bounds_limits_overflow_and_deep_chain()
{
using Void::Algorithms::AdjacencyView;
using Void::Algorithms::AlgorithmError;
using Void::Algorithms::WorkLimits;
using Void::Algorithms::bfs;
using Void::Algorithms::dfs;
using Void::Algorithms::shortest_path_unweighted;
using Void::Algorithms::topological_order;
// Overflow before scratch allocation on absurd vertex_count()
const HugeMockGraph huge{std::numeric_limits<std::size_t>::max()};
const WorkLimits huge_v_limits{
.max_vertices = std::numeric_limits<std::size_t>::max(),
.max_scratch_bytes = std::numeric_limits<std::size_t>::max(),
};
const auto ovf = bfs(huge, 0, huge_v_limits);
Void::Testing::expect(!ovf.has_value());
Void::Testing::expect(ovf.error().code == AlgorithmError::Code::overflow);
// Scratch memory limit exceeded cleanly
const std::vector<std::vector<std::size_t>> small{{1}, {}};
const auto small_scratch = bfs(
AdjacencyView{small},
0,
WorkLimits{.max_scratch_bytes = 8});
Void::Testing::expect(!small_scratch.has_value());
Void::Testing::expect(small_scratch.error().code == AlgorithmError::Code::limit_exceeded);
// Out-of-range neighbor index rejected safely without UB
const std::vector<std::vector<std::size_t>> bad_edge{{99}, {}};
const auto bad_nbr = bfs(AdjacencyView{bad_edge}, 0);
Void::Testing::expect(!bad_nbr.has_value());
Void::Testing::expect(bad_nbr.error().code == AlgorithmError::Code::invalid_vertex);
// Step budget limit exceeded cleanly
const std::vector<std::vector<std::size_t>> path4{{1}, {2}, {3}, {}};
const auto step_limited = bfs(
AdjacencyView{path4},
0,
WorkLimits{.max_steps = 2});
Void::Testing::expect(!step_limited.has_value());
Void::Testing::expect(step_limited.error().code == AlgorithmError::Code::limit_exceeded);
// Deep chain (> 100,000 vertices) runs iteratively with no stack overflow
constexpr std::size_t kDeepCount = 110'000;
std::vector<std::vector<std::size_t>> deep(kDeepCount);
for (std::size_t i = 0; i + 1 < kDeepCount; ++i) {
deep[i].push_back(i + 1);
}
const AdjacencyView deep_view{deep};
const auto deep_dfs = dfs(deep_view, 0);
Void::Testing::require(deep_dfs.has_value());
Void::Testing::expect_eq(deep_dfs->order.size(), kDeepCount);
Void::Testing::expect_eq(deep_dfs->depth[kDeepCount - 1], kDeepCount - 1);
const auto deep_topo = topological_order(deep_view);
Void::Testing::require(deep_topo.has_value());
Void::Testing::expect_eq(deep_topo->order.size(), kDeepCount);
Void::Testing::expect_eq(deep_topo->order.back(), kDeepCount - 1);
const auto deep_sp = shortest_path_unweighted(deep_view, 0, kDeepCount - 1);
Void::Testing::require(deep_sp.has_value());
Void::Testing::expect_eq(deep_sp->distance, kDeepCount - 1);
}
Void::Testing::Test graph_cancellation_and_version_mutation_checks()
{
using Void::Algorithms::AlgorithmError;
using Void::Algorithms::WorkLimits;
using Void::Algorithms::bfs;
using Void::Algorithms::topological_order;
// Concurrent version mutation detected mid-traversal
VersionedChainGraph mutated{
.adj = {{1}, {2}, {3}, {4}, {5}, {}},
.mutate_after_reads = 2,
};
const auto mod_res = bfs(
mutated,
0,
WorkLimits{.cancel_check_interval = 1});
Void::Testing::expect(!mod_res.has_value());
Void::Testing::expect(mod_res.error().code == AlgorithmError::Code::concurrent_modification);
// Cooperative cancellation via std::stop_token
std::stop_source src;
CancellingGraph cg{
.adj = {{1}, {2}, {3}, {4}, {}},
.stop_src = &src,
.cancel_after_reads = 2,
};
const auto cancel_res = topological_order(
cg,
WorkLimits{.cancel_check_interval = 1},
src.get_token());
Void::Testing::expect(!cancel_res.has_value());
Void::Testing::expect(cancel_res.error().code == AlgorithmError::Code::cancelled);
}
+633
View File
@@ -0,0 +1,633 @@
#include <Void/Async/Executor.hpp>
#include <Void/Async/Operation.hpp>
#include <Void/Async/TaskScope.hpp>
#include <Void/Testing/Assert.hpp>
#include <Void/Testing/Test.hpp>
#include <Void/Time/Clock.hpp>
#include <atomic>
#include <chrono>
#include <condition_variable>
#include <coroutine>
#include <cstddef>
#include <cstdint>
#include <mutex>
#include <queue>
#include <stdexcept>
#include <stop_token>
#include <thread>
namespace
{
using namespace Void::Async;
class ThreadedWorkerExecutor final : public Executor
{
public:
ThreadedWorkerExecutor()
{
worker_ = std::thread([this] { run_loop(); });
}
~ThreadedWorkerExecutor() override
{
shutdown();
if (worker_.joinable()) {
worker_.join();
}
}
void post(std::coroutine_handle<> handle) override
{
if (!handle) {
return;
}
{
std::lock_guard lk{mu_};
if (stop_) {
return;
}
normal_.push(handle);
}
cv_.notify_one();
}
[[nodiscard]] std::expected<void, AdmissionError>
try_post(std::coroutine_handle<> handle) override
{
if (!handle) {
return std::unexpected{AdmissionError::invalid_argument};
}
{
std::lock_guard lk{mu_};
if (stop_) {
return std::unexpected{AdmissionError::stopped};
}
normal_.push(handle);
}
cv_.notify_one();
return {};
}
void post_completion(std::coroutine_handle<> handle) override
{
if (!handle) {
return;
}
{
std::lock_guard lk{mu_};
completions_.push(handle);
}
cv_.notify_one();
}
[[nodiscard]] bool is_executor_thread() const noexcept override
{
return std::this_thread::get_id() == worker_id_.load(std::memory_order_acquire);
}
void shutdown()
{
{
std::lock_guard lk{mu_};
stop_ = true;
}
cv_.notify_all();
}
private:
void run_loop()
{
worker_id_.store(std::this_thread::get_id(), std::memory_order_release);
for (;;) {
std::coroutine_handle<> next{};
{
std::unique_lock lk{mu_};
cv_.wait(lk, [this] {
return !completions_.empty() || !normal_.empty() || stop_;
});
if (!completions_.empty()) {
next = completions_.front();
completions_.pop();
} else if (!normal_.empty()) {
next = normal_.front();
normal_.pop();
} else if (stop_) {
return;
}
}
if (next) {
next.resume();
}
}
}
std::atomic<std::thread::id> worker_id_{};
std::mutex mu_{};
std::condition_variable cv_{};
std::queue<std::coroutine_handle<>> completions_{};
std::queue<std::coroutine_handle<>> normal_{};
bool stop_{false};
std::thread worker_;
};
class NonReservingBoundedExecutor final : public Executor
{
public:
explicit NonReservingBoundedExecutor(std::size_t cap) : cap_(cap) {}
void post(std::coroutine_handle<> h) override { inner_.post(h); }
[[nodiscard]] std::expected<void, AdmissionError>
try_post(std::coroutine_handle<> h) override
{
if (inner_.pending_normal() >= cap_) {
return std::unexpected{AdmissionError::overloaded};
}
return inner_.try_post(h);
}
void post_completion(std::coroutine_handle<> h) override { inner_.post_completion(h); }
[[nodiscard]] bool is_executor_thread() const noexcept override { return inner_.is_executor_thread(); }
[[nodiscard]] bool has_background_workers() const noexcept override { return false; }
std::size_t drain() { return inner_.drain(); }
private:
std::size_t cap_;
ManualExecutor inner_;
};
Void::Coro::Task<void> increment_task(int* counter)
{
++(*counter);
co_return;
}
Void::Coro::Task<void> await_op_u64_task(
std::shared_ptr<OperationState<std::uint64_t>> op,
int* resumes,
DomainOutcomeKind* observed_kind,
std::optional<AsyncErrorCode>* err_code,
std::uint64_t* receipt)
{
const auto res = co_await *op;
++(*resumes);
*observed_kind = op->outcome_kind();
if (res.has_value()) {
if (receipt != nullptr) {
*receipt = *res;
}
} else if (err_code != nullptr) {
*err_code = static_cast<AsyncErrorCode>(res.error().code().value);
}
}
Void::Coro::Task<void> await_op_void_task(
std::shared_ptr<OperationState<void>> op,
int* resumes,
DomainOutcomeKind* observed_kind,
bool* has_val)
{
const auto res = co_await *op;
++(*resumes);
*observed_kind = op->outcome_kind();
if (has_val != nullptr) {
*has_val = res.has_value();
}
}
Void::Coro::Task<void> await_op_int_task(
std::shared_ptr<OperationState<int>> op,
int expected,
int* waiter_resumed)
{
const auto res = co_await *op;
Void::Testing::require(res.has_value());
Void::Testing::expect_eq(*res, expected);
++(*waiter_resumed);
}
Void::Coro::Task<void> schedule_with_options_task(
Executor* exec,
OperationOptions opts,
const Void::Time::MonotonicClock* clock,
Void::Result::Result<void>* out)
{
*out = co_await schedule_on(*exec, std::move(opts), *clock);
}
} // namespace
Void::Testing::Test operation_scope_failed_spawn_preserves_task_ownership()
{
ManualExecutor bounded_exec{1};
TaskScope scope{bounded_exec, TaskScopeOptions{.max_tasks = 1}};
int ran_first = 0;
const auto h1 = scope.spawn(increment_task(&ran_first));
Void::Testing::require(h1.has_value());
// 1. Scope capacity exhausted -> task preserved intact!
int ran_preserved = 0;
auto preserved = increment_task(&ran_preserved);
const auto full_scope = scope.spawn(std::move(preserved));
Void::Testing::expect(!full_scope.has_value());
Void::Testing::expect(full_scope.error() == AdmissionError::overloaded);
Void::Testing::expect(static_cast<bool>(preserved.handle()));
Void::Testing::expect(!preserved.done());
// 2. Bounded executor queue full (reserve-then-transfer rollback)
TaskScope roomier_scope{bounded_exec, TaskScopeOptions{.max_tasks = 4}};
const auto full_exec = roomier_scope.spawn(std::move(preserved));
Void::Testing::expect(!full_exec.has_value());
Void::Testing::expect(full_exec.error() == AdmissionError::overloaded);
Void::Testing::expect(static_cast<bool>(preserved.handle()));
Void::Testing::expect(!preserved.done());
// 3. Non-reserving executor try_post failure also restores task via rollback
NonReservingBoundedExecutor non_res_exec{0};
TaskScope non_res_scope{non_res_exec};
const auto non_res_reject = non_res_scope.spawn(std::move(preserved));
Void::Testing::expect(!non_res_reject.has_value());
Void::Testing::expect(non_res_reject.error() == AdmissionError::overloaded);
Void::Testing::expect(static_cast<bool>(preserved.handle()));
Void::Testing::expect(!preserved.done());
// 4. Stopped options and expired clock deadline reject without consuming task
std::stop_source ssrc;
ssrc.request_stop();
const auto stopped_res = roomier_scope.spawn(
std::move(preserved), OperationOptions{.stop = ssrc.get_token()});
Void::Testing::expect(!stopped_res.has_value());
Void::Testing::expect(stopped_res.error() == AdmissionError::stopped);
Void::Testing::expect(static_cast<bool>(preserved.handle()));
Void::Time::ManualClock clock{Void::Time::MonotonicClock::time_point{std::chrono::seconds{50}}};
TaskScope clocked_scope{bounded_exec, TaskScopeOptions{.max_tasks = 4}, clock};
const auto expired_res = clocked_scope.spawn(
std::move(preserved),
OperationOptions{.deadline = Void::Time::MonotonicClock::time_point{std::chrono::seconds{50}}});
Void::Testing::expect(!expired_res.has_value());
Void::Testing::expect(expired_res.error() == AdmissionError::deadline_expired);
Void::Testing::expect(static_cast<bool>(preserved.handle()));
// 5. Invalid max_tasks == 0
TaskScope zero_scope{bounded_exec, TaskScopeOptions{.max_tasks = 0}};
const auto zero_res = zero_scope.spawn(std::move(preserved));
Void::Testing::expect(!zero_res.has_value());
Void::Testing::expect(zero_res.error() == AdmissionError::invalid_argument);
Void::Testing::expect(static_cast<bool>(preserved.handle()));
// Drain `scope` (closes `scope`), then prove caller still owns `preserved` via `roomier_scope`!
Void::Testing::require(scope.join_pumping().has_value());
Void::Testing::expect_eq(ran_first, 1);
// Closed `scope` rejects spawn cleanly while still preserving `preserved`
const auto closed_res = scope.spawn(std::move(preserved));
Void::Testing::expect(!closed_res.has_value());
Void::Testing::expect(closed_res.error() == AdmissionError::stopped);
Void::Testing::expect(static_cast<bool>(preserved.handle()));
const auto ok_after = roomier_scope.spawn(std::move(preserved));
Void::Testing::require(ok_after.has_value());
Void::Testing::require(roomier_scope.join_pumping().has_value());
Void::Testing::expect_eq(ran_preserved, 1);
}
Void::Testing::Test operation_scope_committing_adapter_races_and_backend_refs()
{
ManualExecutor exec;
TaskScope scope{exec};
// Scenario A: stop-before-append -> NotCommitted after backend ref releases
{
std::stop_source stop_src;
auto op = OperationState<std::uint64_t>::create(
OperationOptions{.stop = stop_src.get_token()},
&exec,
StopBehavior::notify_only);
op->acquire_backend_ref();
int resumes = 0;
DomainOutcomeKind observed_kind = DomainOutcomeKind::pending;
std::optional<AsyncErrorCode> err_code{};
Void::Testing::require(
scope.spawn(await_op_u64_task(op, &resumes, &observed_kind, &err_code, nullptr))
.has_value());
exec.drain();
Void::Testing::expect_eq(resumes, 0);
stop_src.request_stop();
Void::Testing::expect(op->stop_requested());
Void::Testing::expect(op->stop_token().stop_requested());
exec.drain();
Void::Testing::expect_eq(resumes, 0);
if (op->stop_token().stop_requested()) {
if (auto t = op->try_commit_not_committed(); t.has_value()) {
t->dispatch();
}
}
exec.drain();
Void::Testing::expect_eq(resumes, 0);
op->release_backend_ref_and_dispatch();
exec.drain();
Void::Testing::expect_eq(resumes, 1);
Void::Testing::expect(observed_kind == DomainOutcomeKind::not_committed);
Void::Testing::expect(err_code == AsyncErrorCode::cancelled);
}
// Scenario B: stop-during-sync + sync succeeds -> receipt preserved, never cancelled
{
std::stop_source stop_src;
auto op = OperationState<std::uint64_t>::create(
OperationOptions{.stop = stop_src.get_token()},
&exec,
StopBehavior::notify_only);
op->acquire_backend_ref();
int resumes = 0;
std::uint64_t receipt = 0;
DomainOutcomeKind observed_kind = DomainOutcomeKind::pending;
Void::Testing::require(
scope.spawn(await_op_u64_task(op, &resumes, &observed_kind, nullptr, &receipt))
.has_value());
exec.drain();
Void::Testing::expect_eq(resumes, 0);
stop_src.request_stop();
Void::Testing::expect(op->stop_requested());
auto t1 = op->try_commit_value(std::uint64_t{9001});
Void::Testing::expect(!t1.has_value());
auto t_dup = op->try_commit_cancelled("late cancel");
Void::Testing::expect(!t_dup.has_value());
op->release_backend_ref_and_dispatch();
exec.drain();
Void::Testing::expect_eq(resumes, 1);
Void::Testing::expect(observed_kind == DomainOutcomeKind::succeeded);
Void::Testing::expect_eq(receipt, std::uint64_t{9001});
}
// Scenario C: stop-during-sync + sync failure -> Unknown outcome after release
{
std::stop_source stop_src;
auto op = OperationState<std::uint64_t>::create(
OperationOptions{.stop = stop_src.get_token()},
&exec,
StopBehavior::notify_only);
op->acquire_backend_ref();
int resumes = 0;
DomainOutcomeKind observed_kind = DomainOutcomeKind::pending;
std::optional<AsyncErrorCode> err_code{};
Void::Testing::require(
scope.spawn(await_op_u64_task(op, &resumes, &observed_kind, &err_code, nullptr))
.has_value());
exec.drain();
stop_src.request_stop();
if (auto t = op->try_commit_unknown("fsync EIO"); t.has_value()) {
t->dispatch();
}
Void::Testing::expect_eq(resumes, 0);
op->release_backend_ref_and_dispatch();
exec.drain();
Void::Testing::expect_eq(resumes, 1);
Void::Testing::expect(err_code == AsyncErrorCode::backend_error);
Void::Testing::expect(observed_kind == DomainOutcomeKind::unknown);
}
// Scenario D: Side-effect-free StopBehavior::settle_cancelled waits for backend_ref == 0
{
std::stop_source stop_src;
auto op = OperationState<void>::create(
OperationOptions{.stop = stop_src.get_token()},
&exec,
StopBehavior::settle_cancelled);
op->acquire_backend_ref();
int resumes = 0;
DomainOutcomeKind observed_kind = DomainOutcomeKind::pending;
bool has_val = true;
Void::Testing::require(
scope.spawn(await_op_void_task(op, &resumes, &observed_kind, &has_val))
.has_value());
exec.drain();
stop_src.request_stop();
exec.drain();
Void::Testing::expect_eq(resumes, 0);
op->release_backend_ref_and_dispatch();
exec.drain();
Void::Testing::expect_eq(resumes, 1);
Void::Testing::expect(!has_val);
Void::Testing::expect(observed_kind == DomainOutcomeKind::cancelled);
}
Void::Testing::require(scope.join_pumping().has_value());
}
Void::Testing::Test operation_scope_reserved_completion_lane_and_schedule_on_clock()
{
ManualExecutor exec{1};
TaskScope scope{exec};
auto op = OperationState<int>::create({}, &exec);
int waiter_resumed = 0;
Void::Testing::require(
scope.spawn(await_op_int_task(op, 77, &waiter_resumed)).has_value());
// Advance waiter until it suspends on `op`.
Void::Testing::expect(exec.run_one());
Void::Testing::expect_eq(waiter_resumed, 0);
// Fill the normal queue capacity (max_queue = 1) completely!
std::coroutine_handle<> dummy_h = std::noop_coroutine();
Void::Testing::require(exec.try_post(dummy_h).has_value());
Void::Testing::expect(exec.try_post(dummy_h).error() == AdmissionError::overloaded);
// Even with normal queue 100% saturated, reserved completion lane wakes `op`!
if (auto ticket = op->try_commit_value(77); ticket.has_value()) {
ticket->dispatch();
}
Void::Testing::require(scope.join_pumping().has_value());
Void::Testing::expect_eq(waiter_resumed, 1);
// Cancellable clock-aware schedule_on tests
Void::Time::ManualClock clock{Void::Time::MonotonicClock::time_point{std::chrono::seconds{10}}};
const auto t_dl = clock.now() + std::chrono::seconds{5};
Void::Result::Result<void> sched_timeout_res{};
Void::Result::Result<void> sched_cancel_res{};
std::stop_source cancel_src;
TaskScope sched_scope{exec, TaskScopeOptions{.max_tasks = 4}, clock};
Void::Testing::require(
sched_scope.spawn(
schedule_with_options_task(
&exec, OperationOptions{.deadline = t_dl}, &clock, &sched_timeout_res))
.has_value());
// First run enters coroutine body and suspends inside schedule_on(exec, opts, clock)
Void::Testing::expect(exec.run_one());
// Advance clock past deadline WHILE queued!
Void::Testing::require(clock.advance(std::chrono::seconds{5}).has_value());
Void::Testing::require(sched_scope.join_pumping().has_value());
Void::Testing::expect(!sched_timeout_res.has_value());
Void::Testing::expect(
sched_timeout_res.error().code().value ==
static_cast<std::int32_t>(AsyncErrorCode::timeout));
// Pre-cancelled schedule_on in fresh scope
cancel_src.request_stop();
TaskScope cancel_scope{exec, TaskScopeOptions{.max_tasks = 4}, clock};
Void::Testing::require(
cancel_scope.spawn(
schedule_with_options_task(
&exec, OperationOptions{.stop = cancel_src.get_token()}, &clock, &sched_cancel_res))
.has_value());
Void::Testing::require(cancel_scope.join_pumping().has_value());
Void::Testing::expect(!sched_cancel_res.has_value());
Void::Testing::expect(
sched_cancel_res.error().code().value ==
static_cast<std::int32_t>(AsyncErrorCode::cancelled));
}
Void::Testing::Test operation_scope_join_exceptions_self_join_and_detached_owner()
{
// 1. Nested co_await scope.join(), exception sink + stop_on_first_error
{
ManualExecutor exec;
TaskScope parent{exec};
bool child1_saw_stop = false;
Void::Result::Result<void> nested_join_status{};
auto parent_task = [](Executor* ex,
bool* saw_stop_out,
Void::Result::Result<void>* join_status_out) -> Void::Coro::Task<void> {
TaskScope inner{*ex};
auto op = OperationState<void>::create(
OperationOptions{.stop = inner.stop_token()},
ex,
StopBehavior::settle_cancelled);
auto wait_stop = [](std::shared_ptr<OperationState<void>> s, bool* out) -> Void::Coro::Task<void> {
const auto res = co_await *s;
*out = !res.has_value();
};
auto throw_child = []() -> Void::Coro::Task<void> {
throw std::runtime_error{"boom inside inner"};
co_return;
};
Void::Testing::require(inner.spawn(wait_stop(op, saw_stop_out)).has_value());
Void::Testing::require(inner.spawn(throw_child()).has_value());
*join_status_out = co_await inner.join();
Void::Testing::expect(inner.has_exception());
Void::Testing::expect_eq(inner.failure_count(), std::size_t{1});
};
Void::Testing::require(
parent.spawn(parent_task(&exec, &child1_saw_stop, &nested_join_status)).has_value());
Void::Testing::require(parent.join_pumping().has_value());
Void::Testing::expect(child1_saw_stop);
Void::Testing::expect(!nested_join_status.has_value());
}
// 2. self_join detection when join_blocking() called inside active executor thread
{
ManualExecutor exec;
TaskScope scope{exec};
Void::Result::Result<void> self_res{};
auto self_joiner = [](Executor* ex, Void::Result::Result<void>* out) -> Void::Coro::Task<void> {
TaskScope dummy{*ex};
*out = dummy.join_blocking();
co_return;
};
Void::Testing::require(scope.spawn(self_joiner(&exec, &self_res)).has_value());
Void::Testing::require(scope.join_pumping().has_value());
Void::Testing::expect(!self_res.has_value());
Void::Testing::expect(
self_res.error().code().value ==
static_cast<std::int32_t>(AsyncErrorCode::self_join));
}
// 3. Individual JoinHandle co_await + DetachedOwner bounded drain
{
ManualExecutor exec;
DetachedOwner owner{exec, TaskScopeOptions{.max_tasks = 8}};
int completed = 0;
auto h = owner.spawn(increment_task(&completed));
Void::Testing::require(h.has_value());
bool awaited_ok = false;
auto await_child = [](JoinHandle handle, bool* ok_out) -> Void::Coro::Task<void> {
const auto res = co_await handle;
*ok_out = res.has_value();
};
Void::Testing::require(owner.spawn(await_child(*h, &awaited_ok)).has_value());
Void::Testing::require(owner.drain_pumping().has_value());
Void::Testing::expect_eq(completed, 1);
Void::Testing::expect(h->done());
Void::Testing::expect(awaited_ok);
}
}
Void::Testing::Test operation_scope_concurrent_stress_tsan()
{
ThreadedWorkerExecutor exec;
constexpr int kRounds = 64;
for (int i = 0; i < kRounds; ++i) {
std::stop_source stop_src;
auto op = OperationState<int>::create(
OperationOptions{.stop = stop_src.get_token()},
&exec,
(i % 2 == 0) ? StopBehavior::notify_only : StopBehavior::settle_cancelled);
op->acquire_backend_ref();
std::atomic<int> resumes{0};
TaskScope scope{exec};
auto awaiter = [](std::shared_ptr<OperationState<int>> state,
std::atomic<int>* count) -> Void::Coro::Task<void> {
const auto r = co_await *state;
(void)r;
count->fetch_add(1, std::memory_order_acq_rel);
};
auto jh = scope.spawn(awaiter(op, &resumes));
Void::Testing::require(jh.has_value());
std::thread cancel_thr([&] {
if (i % 3 != 0) {
stop_src.request_stop();
}
});
std::thread backend_thr([&] {
if (auto t = op->try_commit_value(i); t.has_value()) {
t->dispatch();
}
op->release_backend_ref_and_dispatch();
});
cancel_thr.join();
backend_thr.join();
Void::Testing::require(scope.join_blocking().has_value());
Void::Testing::expect_eq(resumes.load(std::memory_order_acquire), 1);
}
}
+269
View File
@@ -0,0 +1,269 @@
#include <Void/Unicode/Utf.hpp>
#include <Void/Testing/Assert.hpp>
#include <Void/Testing/Test.hpp>
#include <array>
#include <cstddef>
#include <stop_token>
#include <string>
#include <string_view>
Void::Testing::Test utf_manifest_scalars_and_roundtrips()
{
using Void::Unicode::Scalar;
using Void::Unicode::data_version;
using Void::Unicode::encode_utf16;
using Void::Unicode::encode_utf8;
using Void::Unicode::is_scalar_value;
using Void::Unicode::utf16_to_utf32;
using Void::Unicode::utf16_to_utf8;
using Void::Unicode::utf32_to_utf16;
using Void::Unicode::utf32_to_utf8;
using Void::Unicode::utf8_to_utf16;
using Void::Unicode::utf8_to_utf32;
using Void::Unicode::validate_utf16;
using Void::Unicode::validate_utf32;
using Void::Unicode::validate_utf8;
Void::Testing::expect_eq(data_version(), std::string_view{"17.0.0"});
Void::Testing::expect(is_scalar_value(U'\0'));
Void::Testing::expect(is_scalar_value(U'A'));
Void::Testing::expect(is_scalar_value(U'\u00DF'));
Void::Testing::expect(is_scalar_value(U'\u20AC'));
Void::Testing::expect(is_scalar_value(U'\U0001F680'));
Void::Testing::expect(is_scalar_value(0x10FFFFu));
Void::Testing::expect(!is_scalar_value(0xD800u));
Void::Testing::expect(!is_scalar_value(0xDFFFu));
Void::Testing::expect(!is_scalar_value(0x110000u));
Void::Testing::expect(Scalar::from_code_point(U'A').has_value());
Void::Testing::expect(!Scalar::from_code_point(0xD800u).has_value());
// Roundtrip across 1-, 2-, 3-, and 4-byte scalars plus embedded NUL.
const std::string utf8_src{"A\0\xC3\x9F\xE2\x82\xAC\xF0\x9F\x9A\x80", 11};
const auto v8 = validate_utf8(utf8_src);
Void::Testing::require(v8.has_value());
Void::Testing::expect_eq(v8->scalars_decoded, std::size_t{5});
Void::Testing::expect_eq(v8->replacements, std::size_t{0});
const auto u16 = utf8_to_utf16(utf8_src);
Void::Testing::require(u16.has_value());
Void::Testing::expect_eq(u16->size(), std::size_t{6}); // 4 BMP + 2 surrogate pair
Void::Testing::expect(validate_utf16(*u16).has_value());
const auto u32 = utf16_to_utf32(*u16);
Void::Testing::require(u32.has_value());
Void::Testing::expect_eq(u32->size(), std::size_t{5});
Void::Testing::expect((*u32)[4] == 0x1F680u);
Void::Testing::expect(validate_utf32(*u32).has_value());
const auto back_u8_from_32 = utf32_to_utf8(*u32);
Void::Testing::require(back_u8_from_32.has_value());
Void::Testing::expect(*back_u8_from_32 == utf8_src);
const auto back_u8_from_16 = utf16_to_utf8(*u16);
Void::Testing::require(back_u8_from_16.has_value());
Void::Testing::expect(*back_u8_from_16 == utf8_src);
const auto back_u16_from_32 = utf32_to_utf16(*u32);
Void::Testing::require(back_u16_from_32.has_value());
Void::Testing::expect(*back_u16_from_32 == *u16);
const auto direct_u32 = utf8_to_utf32(utf8_src);
Void::Testing::require(direct_u32.has_value());
Void::Testing::expect(*direct_u32 == *u32);
// Encode single scalar into small buffer checks
const auto rocket = *Scalar::from_code_point(0x1F680u);
std::array<char, 3> too_small_8{};
Void::Testing::expect(!encode_utf8(rocket, too_small_8).has_value());
std::array<char, 4> exact_8{};
const auto enc8 = encode_utf8(rocket, exact_8);
Void::Testing::require(enc8.has_value());
Void::Testing::expect_eq(*enc8, std::size_t{4});
std::array<char16_t, 1> too_small_16{};
Void::Testing::expect(!encode_utf16(rocket, too_small_16).has_value());
std::array<char16_t, 2> exact_16{};
const auto enc16 = encode_utf16(rocket, exact_16);
Void::Testing::require(enc16.has_value());
Void::Testing::expect_eq(*enc16, std::size_t{2});
}
Void::Testing::Test utf_strict_rejects_all_malformed_classes()
{
using Void::Unicode::UtfErrorKind;
using Void::Unicode::utf16_to_utf8;
using Void::Unicode::utf32_to_utf8;
using Void::Unicode::utf8_to_utf32;
using Void::Unicode::validate_utf16;
using Void::Unicode::validate_utf32;
using Void::Unicode::validate_utf8;
// Overlong 2-, 3-, and 4-byte UTF-8 encodings
Void::Testing::expect(validate_utf8("\xC0\xAF").error().kind == UtfErrorKind::invalid_utf8);
Void::Testing::expect(validate_utf8("\xC1\xBF").error().kind == UtfErrorKind::invalid_utf8);
Void::Testing::expect(validate_utf8("\xE0\x80\xAF").error().kind == UtfErrorKind::invalid_utf8);
Void::Testing::expect(validate_utf8("\xF0\x80\x80\xAF").error().kind == UtfErrorKind::invalid_utf8);
// UTF-8 encoded surrogates (U+D800, U+DFFF)
Void::Testing::expect(validate_utf8("\xED\xA0\x80").error().kind == UtfErrorKind::invalid_utf8);
Void::Testing::expect(validate_utf8("\xED\xBF\xBF").error().kind == UtfErrorKind::invalid_utf8);
// Out-of-range UTF-8 (> U+10FFFF)
Void::Testing::expect(validate_utf8("\xF4\x90\x80\x80").error().kind == UtfErrorKind::invalid_utf8);
Void::Testing::expect(validate_utf8("\xF5\x80\x80\x80").error().kind == UtfErrorKind::invalid_utf8);
// Unexpected continuation byte and truncated tail
Void::Testing::expect(validate_utf8("ab\x80").error().unit_offset == std::size_t{2});
const auto trunc8 = utf8_to_utf32("ok\xE2\x82");
Void::Testing::expect(!trunc8.has_value());
Void::Testing::expect(trunc8.error().kind == UtfErrorKind::truncated);
Void::Testing::expect_eq(trunc8.error().unit_offset, std::size_t{2});
// UTF-16 unpaired high/low surrogates and truncation
const std::u16string unpaired_high{u'a', char16_t{0xD800}, u'b'};
const auto err16_hi = utf16_to_utf8(unpaired_high);
Void::Testing::expect(!err16_hi.has_value());
Void::Testing::expect(err16_hi.error().kind == UtfErrorKind::invalid_utf16);
Void::Testing::expect_eq(err16_hi.error().unit_offset, std::size_t{1});
const std::u16string unpaired_low{char16_t{0xDC00}, u'z'};
Void::Testing::expect(validate_utf16(unpaired_low).error().kind == UtfErrorKind::invalid_utf16);
const std::u16string trunc16{u'a', char16_t{0xD83D}};
Void::Testing::expect(validate_utf16(trunc16).error().kind == UtfErrorKind::truncated);
// UTF-32 surrogates and > 0x10FFFF
const std::u32string sur32{U'a', char32_t{0xD800}};
Void::Testing::expect(validate_utf32(sur32).error().kind == UtfErrorKind::invalid_scalar);
const std::u32string big32{char32_t{0x110000}};
Void::Testing::expect(utf32_to_utf8(big32).error().kind == UtfErrorKind::invalid_scalar);
}
Void::Testing::Test utf_one_unit_repair_and_into_span_limits()
{
using Void::Unicode::UtfErrorKind;
using Void::Unicode::UtfLimits;
using Void::Unicode::UtfPolicy;
using Void::Unicode::utf16_to_utf32;
using Void::Unicode::utf32_to_utf8;
using Void::Unicode::utf8_repair;
using Void::Unicode::utf8_to_utf16_into;
using Void::Unicode::utf8_to_utf32;
// Invalid lead byte followed by valid ASCII preserves ASCII cleanly.
const auto rep_ascii = utf8_to_utf32("a\xFF" "b\xE2\x82" "c", UtfPolicy::replace_one_unit);
Void::Testing::require(rep_ascii.has_value());
const std::u32string expected_rep{U'a', U'\uFFFD', U'b', U'\uFFFD', U'\uFFFD', U'c'};
Void::Testing::expect(*rep_ascii == expected_rep);
const auto repaired_u8 = utf8_repair("ok\x80!");
Void::Testing::require(repaired_u8.has_value());
Void::Testing::expect(*repaired_u8 == std::string{"ok\xEF\xBF\xBD!"});
// UTF-16 repair: lone low, lone high, valid surrogate pair
const std::u16string bad16{
char16_t{0xDC00},
char16_t{0xD800},
u'Z',
char16_t{0xD83D},
char16_t{0xDE80},
};
const auto rep16 = utf16_to_utf32(bad16, UtfPolicy::replace_one_unit);
Void::Testing::require(rep16.has_value());
const std::u32string exp16{U'\uFFFD', U'\uFFFD', U'Z', U'\U0001F680'};
Void::Testing::expect(*rep16 == exp16);
// UTF-32 repair
const auto rep32 = utf32_to_utf8(
std::u32string_view{U"X"} , UtfPolicy::replace_one_unit);
Void::Testing::require(rep32.has_value());
const std::u32string invalid32{U'X', char32_t{0xD801}, char32_t{0x200000}, U'Y'};
const auto rep32_bad = utf32_to_utf8(invalid32, UtfPolicy::replace_one_unit);
Void::Testing::require(rep32_bad.has_value());
Void::Testing::expect(*rep32_bad == std::string{"X\xEF\xBF\xBD\xEF\xBF\xBDY"});
// Non-allocating _into transcoding + output_too_small + input/output limits + cancellation
std::array<char16_t, 4> buf16{};
const auto fit = utf8_to_utf16_into("A\xF0\x9F\x9A\x80", std::span{buf16});
Void::Testing::require(fit.has_value());
Void::Testing::expect_eq(fit->units_written, std::size_t{3});
Void::Testing::expect_eq(fit->scalars_decoded, std::size_t{2});
std::array<char16_t, 2> small16{};
const auto too_small = utf8_to_utf16_into("A\xF0\x9F\x9A\x80", std::span{small16});
Void::Testing::expect(!too_small.has_value());
Void::Testing::expect(too_small.error().kind == UtfErrorKind::output_too_small);
const auto lim_in = utf8_to_utf32("abcdef", UtfPolicy::reject, UtfLimits{.max_input_units = 4});
Void::Testing::expect(lim_in.error().kind == UtfErrorKind::limit_exceeded);
const auto lim_out = utf8_to_utf32("abcdef", UtfPolicy::reject, UtfLimits{.max_output_units = 3});
Void::Testing::expect(lim_out.error().kind == UtfErrorKind::limit_exceeded);
std::stop_source ssrc;
ssrc.request_stop();
const auto cancelled = utf8_to_utf32("abc", UtfPolicy::reject, UtfLimits{}, ssrc.get_token());
Void::Testing::expect(cancelled.error().kind == UtfErrorKind::cancelled);
}
Void::Testing::Test utf_streaming_decoders_arbitrary_splits()
{
using Void::Unicode::Scalar;
using Void::Unicode::Utf16StreamDecoder;
using Void::Unicode::Utf8StreamDecoder;
using Void::Unicode::UtfErrorKind;
using Void::Unicode::UtfPolicy;
using Void::Unicode::utf8_to_utf32;
// 1-byte chunks across 1-, 2-, 3-, 4-byte UTF-8 and invalid bytes under repair
const std::string sample{"H\xC3\xA9\xE2\x82\xAC\xF0\x9F\x9A\x80!\xE2\x82" "X\xED\xA0\x80", 17};
const auto expected_oneshot = utf8_to_utf32(sample, UtfPolicy::replace_one_unit);
Void::Testing::require(expected_oneshot.has_value());
Utf8StreamDecoder dec{UtfPolicy::replace_one_unit};
std::u32string streamed;
for (std::size_t i = 0; i < sample.size(); ++i) {
const auto res = dec.push(
std::string_view{sample.data() + i, 1},
[&](Scalar s) { streamed.push_back(s.code_point()); });
Void::Testing::require(res.has_value());
}
const auto fin = dec.finish([&](Scalar s) { streamed.push_back(s.code_point()); });
Void::Testing::require(fin.has_value());
Void::Testing::expect(!dec.has_pending());
Void::Testing::expect(streamed == *expected_oneshot);
// Strict UTF-8 streaming rejects truncated sequence at finish()
Utf8StreamDecoder strict_dec{UtfPolicy::reject};
std::u32string tmp;
Void::Testing::require(strict_dec.push("\xE2\x82", [&](Scalar s) { tmp.push_back(s.code_point()); }).has_value());
Void::Testing::expect(strict_dec.has_pending());
const auto trunc_fin = strict_dec.finish([&](Scalar s) { tmp.push_back(s.code_point()); });
Void::Testing::expect(!trunc_fin.has_value());
Void::Testing::expect(trunc_fin.error().kind == UtfErrorKind::truncated);
// UTF-16 split surrogate pair across chunk boundary
Utf16StreamDecoder u16_dec{UtfPolicy::reject};
std::u32string out16;
Void::Testing::require(
u16_dec.push(std::u16string_view{u"A\xD83D", 2}, [&](Scalar s) { out16.push_back(s.code_point()); }).has_value());
Void::Testing::expect(u16_dec.has_pending());
Void::Testing::require(
u16_dec.push(std::u16string_view{u"\xDE80Z", 2}, [&](Scalar s) { out16.push_back(s.code_point()); }).has_value());
Void::Testing::expect(!u16_dec.has_pending());
Void::Testing::require(u16_dec.finish([&](Scalar s) { out16.push_back(s.code_point()); }).has_value());
Void::Testing::expect(out16 == std::u32string{U'A', U'\U0001F680', U'Z'});
// UTF-16 repair with trailing high surrogate at EOF
Utf16StreamDecoder u16_rep{UtfPolicy::replace_one_unit};
std::u32string out16_rep;
const std::u16string part1{char16_t{0xD800}};
const std::u16string part2{u'B', char16_t{0xD83D}};
Void::Testing::require(u16_rep.push(part1, [&](Scalar s) { out16_rep.push_back(s.code_point()); }).has_value());
Void::Testing::require(u16_rep.push(part2, [&](Scalar s) { out16_rep.push_back(s.code_point()); }).has_value());
Void::Testing::require(u16_rep.finish([&](Scalar s) { out16_rep.push_back(s.code_point()); }).has_value());
Void::Testing::expect(out16_rep == std::u32string{U'\uFFFD', U'B', U'\uFFFD'});
}