Comments (3)
A rough sketch. Without any integration into the Iterator concept and IteratorImpl class. But I think this can subclass from IteratorImpl and it Just Works(tm). Then any function can return an IterGenerator<T>
and yield T
s and it's a sus::Iterator
.
Some questions:
- We could add an additional method to make it an
AsyncIterator
or something, which isbool is_done()
or something. This would allow the iterator to report separately that it's done iterating vs it returned a None. Sync iterators can't have this distinction. But is this useful? - More likely what we want instead is the ability for the iterator to
co_await
and return control up. How does that fit into this model and make it customizable?
https://godbolt.org/z/Ejhq7s8nx
#include <cassert>
#include <concepts>
#include <coroutine>
#include <cstdlib>
#include <iostream>
#include <utility>
namespace sus {
void check(bool v) { assert(v); }
[[noreturn]] void unreachable() { abort(); }
} // namespace sus
template <class T>
struct Option {
constexpr ~Option() noexcept {
if (has) t_.~T();
}
union {
T t_;
};
bool has = false;
constexpr Option() = default;
constexpr Option(T r) : t_(std::move(r)), has(true) {}
Option(Option&& o) : has(std::exchange(o.has, false)) {
if (has) {
if constexpr (std::is_trivially_default_constructible_v<T>)
t_ = o.t_;
else
new (&t_) T(std::move(o.t_));
o.t_.~T();
}
}
Option& operator=(Option&& o) {
if (has) {
t_.~T();
}
has = std::exchange(o.has, false);
if (has) {
if constexpr (std::is_trivially_default_constructible_v<T>)
t_ = o.t_;
else
new (&t_) T(std::move(o.t_));
o.t_.~T();
}
return *this;
}
constexpr void insert(T r) {
if (!has) {
has = true;
new (&t_) T(std::move(r));
} else {
t_ = std::move(r);
}
}
constexpr T unwrap_unchecked() && noexcept {
has = false;
T r = std::move(t_);
t_.~T();
return r;
}
constexpr Option take() & noexcept {
if (has) {
auto o = Option(std::move(t_));
t_.~T();
has = false;
return o;
} else {
return Option();
}
}
};
template <class IG, class T>
struct IterPromise {
IG get_return_object() { return IG(*this); }
constexpr auto yield_value(Option<T> y) noexcept {
yielded_ = std::move(y);
return std::suspend_always();
}
constexpr auto initial_suspend() noexcept { return std::suspend_always(); }
constexpr auto final_suspend() noexcept { return std::suspend_always(); }
void unhandled_exception() noexcept { ::sus::unreachable(); }
Option<T> yielded_;
};
struct IteratorEnd {};
template <class T>
struct IterGenerator {
// Coroutine implementation.
using promise_type = IterPromise<IterGenerator<T>, T>;
using CoHandle = std::coroutine_handle<promise_type>;
constexpr IterGenerator(promise_type& p) noexcept
: co_handle_(CoHandle::from_promise(p)) {}
constexpr ~IterGenerator() noexcept {
if (co_handle_ != nullptr) co_handle_.destroy();
}
constexpr IterGenerator(IterGenerator&& o) noexcept
: co_handle_(std::exchange(o.co_handle_, nullptr)) {
::sus::check(co_handle_ != nullptr);
}
constexpr IterGenerator& operator=(IterGenerator&& o) noexcept {
co_handle_ = std::exchange(o.co_handle_, nullptr);
::sus::check(co_handle_ != nullptr);
}
constexpr Option<T> next() noexcept {
if (!co_handle_.done()) co_handle_.resume();
return co_handle_.promise().yielded_.take();
}
constexpr auto begin() & noexcept {
// Ensure the first item is yielded and ready to be returned from the
// iterator's operator*().
if (!co_handle_.done()) co_handle_.resume();
return IterGeneratorLoop(*this);
}
constexpr auto end() & noexcept { return IteratorEnd(); }
struct IterGeneratorLoop {
IterGeneratorLoop(IterGenerator& ig [[clang::lifetimebound]])
: ig_(ig) {}
constexpr bool operator==(const IteratorEnd&) noexcept {
return ig_.co_handle_.done();
}
constexpr IterGeneratorLoop& operator++() & noexcept {
ig_.co_handle_.resume();
return *this;
}
constexpr T operator*() & noexcept {
return ig_.co_handle_.promise().yielded_.take().unwrap_unchecked();
}
IterGenerator& ig_;
};
CoHandle co_handle_;
};
int main() {
auto x = []() -> IterGenerator<int> {
co_yield 1;
co_yield 2;
co_yield 4;
co_yield 9;
};
auto it = x();
std::cout << it.next().unwrap_unchecked() << "\n";
for (int i : it) {
std::cout << i << " ";
}
}
from subspace.
await in an iterator does not seem particularly useful. it would need to yield and then have the caller give it data that it can await for...?
Iterators can yield other iterators with for loops:
int main() {
auto y = []() -> IterGenerator<int> {
co_yield 10;
co_yield 9;
co_yield 8;
};
auto x = [](IterGenerator<int> o) -> IterGenerator<int> {
co_yield 1;
co_yield 2;
co_yield 4;
co_yield 7;
for (auto&& x : o) co_yield x;
};
auto it = x(y());
print(it.next().unwrap_unchecked());
for (int i : it) {
print(i);
}
}
Prints: 1 2 4 7 10 9 8
https://godbolt.org/z/1Eo1863rz
from subspace.
Delete await_transform()
in the promise_type
to avoid co_await in the IteratorGenerator since it's a sync iterator and next() needs to return the next value. Returning early won't work, the caller expects a value there, there's no poll API.
void await_transform() = delete;
from subspace.
Related Issues (20)
- Cow type (Clone-on-write)
- Use seto to look for overflow
- Optimize storage for Result with NeverValueField HOT 1
- Compile-time option for overflow checks
- Add `c_int` and `c_uint` portability helper type
- TryFrom<ToType, FromType> should be satisfied for all From<ToType, FromType>
- Rewrite Tuple's impl to not be recursive HOT 1
- Provide Tuple::as_ref and as_mut
- DynIterator type erasure
- Think about Vec construction from variadics
- Iterator::collect should ideally support conversions HOT 1
- Nested classes missing in Subdoc
- Generate nested classes/enums. Where to display them?
- Friend decls are showing up in the overload set
- Subdoc fails with missing modmap files HOT 8
- Implement Error for string/string_view HOT 1
- compat_ headers are an ODR nightmare HOT 1
- Option::as_slice and as_mut_slice HOT 2
- Mark Slice and SliceMut as O(1) to construct via std::ranges::enable_view
- Add clang 19 bots and fix clang 18 bots HOT 1
Recommend Projects
-
React
A declarative, efficient, and flexible JavaScript library for building user interfaces.
-
Vue.js
🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.
-
Typescript
TypeScript is a superset of JavaScript that compiles to clean JavaScript output.
-
TensorFlow
An Open Source Machine Learning Framework for Everyone
-
Django
The Web framework for perfectionists with deadlines.
-
Laravel
A PHP framework for web artisans
-
D3
Bring data to life with SVG, Canvas and HTML. 📊📈🎉
-
Recommend Topics
-
javascript
JavaScript (JS) is a lightweight interpreted programming language with first-class functions.
-
web
Some thing interesting about web. New door for the world.
-
server
A server is a program made to process requests and deliver data to clients.
-
Machine learning
Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.
-
Visualization
Some thing interesting about visualization, use data art
-
Game
Some thing interesting about game, make everyone happy.
Recommend Org
-
Facebook
We are working to build community through open source technology. NB: members must have two-factor auth.
-
Microsoft
Open source projects and samples from Microsoft.
-
Google
Google ❤️ Open Source for everyone.
-
Alibaba
Alibaba Open Source for everyone
-
D3
Data-Driven Documents codes.
-
Tencent
China tencent open source team.
from subspace.