Files
Library/include/Void/Async/Generator.hpp
T
faumarayandClaude Fable 5 28b94883fd Restructure into umbrella modules (~55 -> 16 targets)
Headers move, CMake targets merge, C++ namespaces stay unchanged:
- Core: Scope, Lazy, Counted, Flags, Hash, Bits, Uuid, TypeList, TypeMap, Variant
- Functional: Pipeline, Either, Result, Retry
- Containers: Ring, Pool, PriorityQueue, LRU, Trie, Graph, DisjointSet, Bitset, Interval
- Math: +Matrix, Numeric, Random, Histogram
- Text: Str, Format, Tokenizer, Diff, Encoding, Semver
- Data: Json, Csv, Ini
- Async: Coro, Concurrency, EventBus, Observable
- Time: +Bench
- Log: Log facade + Logging framework (facade now header-only, breaking
  the Stacktrace<->Log link cycle the merge would have created)
- System: FileSystem + Process
- Configuration: +Argparse
- Unchanged: Stacktrace, Plugin, StateMachine, Testing, TestingMock, Detail

Module system fixes:
- OPTIONAL_DEPS resolution deferred to void_finalize_modules() so it no
  longer depends on the alphabetical discovery order of src/ subdirs
  (Testing -> Text would have been silently dropped).
- Every header-only module now has a tracked module.cmake; previously the
  empty src/<Name> marker dirs were untracked, so a fresh clone would have
  silently skipped those modules.
- VOID_HAS_LOGGING/CONCURRENCY/STR consumers renamed to LOG/ASYNC/TEXT.

Tests move to tests/standalone/<Umbrella>/<Feature>.cpp (Result suite files
prefixed: ResultBasic etc.). Test count verified identical (831) before and
after. README/CLAUDE.md module tables updated.

Co-Authored-By: Claude Fable 5 <noreply@anthropic.com>
2026-06-12 18:50:02 +03:00

177 lines
5.5 KiB
C++

#pragma once
#include <coroutine>
#include <exception>
#include <iterator>
#include <optional>
#include <type_traits>
#include <utility>
namespace Void::Coro
{
// ── Generator<T> ──────────────────────────────────────────────────────────────
// Lazy pull-based sequence driven by co_yield. Supports range-for.
// The coroutine body is NOT resumed until the first iterator increment.
//
// Generator<int> iota(int start) {
// while (true) co_yield start++;
// }
// for (int v : iota(0) | take(5)) { ... }
template <typename T>
class Generator
{
public:
struct promise_type
{
T* current{nullptr};
std::exception_ptr exception;
Generator get_return_object()
{
return Generator{std::coroutine_handle<promise_type>::from_promise(*this)};
}
std::suspend_always initial_suspend() noexcept { return {}; }
std::suspend_always final_suspend() noexcept { return {}; }
template <std::convertible_to<T> U>
std::suspend_always yield_value(U&& v) noexcept(std::is_nothrow_constructible_v<T, U>)
{
current = std::addressof(value_);
value_ = std::forward<U>(v);
return {};
}
void return_void() noexcept {}
void unhandled_exception() { exception = std::current_exception(); }
private:
T value_{};
};
using handle_type = std::coroutine_handle<promise_type>;
// ── construction ──────────────────────────────────────────────────────────
explicit Generator(handle_type h) noexcept : handle_{h} {}
Generator(const Generator&) = delete;
Generator& operator=(const Generator&) = delete;
Generator(Generator&& o) noexcept : handle_{std::exchange(o.handle_, {})} {}
Generator& operator=(Generator&& o) noexcept
{
if (this != &o) {
if (handle_) handle_.destroy();
handle_ = std::exchange(o.handle_, {});
}
return *this;
}
~Generator() { if (handle_) handle_.destroy(); }
// ── range interface ───────────────────────────────────────────────────────
struct sentinel {};
struct iterator
{
using iterator_category = std::input_iterator_tag;
using value_type = T;
using difference_type = std::ptrdiff_t;
handle_type handle;
[[nodiscard]] bool operator==(sentinel) const noexcept { return handle.done(); }
iterator& operator++()
{
handle.resume();
if (handle.done() && handle.promise().exception)
std::rethrow_exception(handle.promise().exception);
return *this;
}
void operator++(int) { ++(*this); }
[[nodiscard]] T& operator*() const noexcept { return *handle.promise().current; }
[[nodiscard]] T* operator->() const noexcept { return handle.promise().current; }
};
[[nodiscard]] iterator begin()
{
handle_.resume(); // advance to the first yield
if (handle_.done() && handle_.promise().exception)
std::rethrow_exception(handle_.promise().exception);
return iterator{handle_};
}
[[nodiscard]] sentinel end() noexcept { return {}; }
// ── explicit pull interface ───────────────────────────────────────────────
[[nodiscard]] bool done() const noexcept { return handle_.done(); }
[[nodiscard]] bool valid() const noexcept { return handle_ && !handle_.done(); }
// Resume and return the next value, or nullopt when exhausted.
[[nodiscard]] std::optional<T> next()
{
if (!handle_ || handle_.done()) return std::nullopt;
handle_.resume();
if (handle_.done()) {
if (handle_.promise().exception)
std::rethrow_exception(handle_.promise().exception);
return std::nullopt;
}
return *handle_.promise().current;
}
private:
handle_type handle_;
};
// ── generator combinators ─────────────────────────────────────────────────────
// take(n) — yield at most n elements from g.
template <typename T>
Generator<T> take(Generator<T> g, std::size_t n)
{
std::size_t i = 0;
for (T& v : g) {
if (i++ >= n) break;
co_yield v;
}
}
// filter(g, pred) — yield only elements satisfying pred.
template <typename T, typename Pred>
requires std::predicate<Pred, const T&>
Generator<T> filter(Generator<T> g, Pred pred)
{
for (T& v : g)
if (pred(v)) co_yield v;
}
// map(g, fn) — transform each element.
template <typename T, typename F>
requires std::invocable<F, T&>
Generator<std::invoke_result_t<F, T&>> map(Generator<T> g, F fn)
{
for (T& v : g)
co_yield fn(v);
}
// from_range(begin, end) — wrap an existing iterator range as a generator.
template <typename Iter, typename Sentinel>
Generator<typename std::iterator_traits<Iter>::value_type>
from_range(Iter first, Sentinel last)
{
for (; first != last; ++first)
co_yield *first;
}
} // namespace Void::Coro