An asynchronous coroutine which implements the C++20 coroutine API.
Coroutines allow a series of asynchronous operations to be written as straight line code. Rather than manually writing a state machine, users can co_await any Pigweed asynchronous value (types with a Poll<T> Pend(Context&) method).
Pigweed's Coro<T> API supports checked, fallible, heap-free allocation. The first argument to any coroutine function must be a CoroContext (or a reference to one). This allows the coroutine to allocate space for asynchronously-held stack variables using the allocator member of the CoroContext.
Failure to allocate coroutine "stack" space will result in the Coro<T> returning Status::Invalid().
To create a coroutine, a function must:
Coro<T> where T is some type constructible from pw::Status, such as pw::Status or pw::Result<U>.co_return <value> rather than return <value> for any return statements. This also requires the use of PW_CO_TRY and PW_CO_TRY_ASSIGN rather than PW_TRY and PW_TRY_ASSIGN.pw::allocator::Allocator& as its first argument. This allocator will be used to allocate storage for coroutine stack variables held across a co_await point.Inside a coroutine function, co_await <expr> can be used on any type with a Poll<T> Pend(Context&) method. The result will be a value of type T.
embed:rst:leading-asterisk * .. literalinclude:: examples/basic.cc * :language: cpp * :linenos: * :start-after: [pw_async2-examples-basic-coro] * :end-before: [pw_async2-examples-basic-coro] *
Public Types | |
| using | promise_type = ::pw::async2::internal::CoroPromiseType< T > |
Public Member Functions | |
| bool | IsValid () const |
| Poll< T > | Pend (Context &cx) |
Static Public Member Functions | |
| static Coro | Empty () |
| Creates an empty, invalid coroutine object. | |
| using pw::async2::Coro< T >::promise_type = ::pw::async2::internal::CoroPromiseType<T> |
Used by the compiler in order to create a Coro<T> from a coroutine function.
|
inline |
|
inline |
Attempt to complete this coroutine, returning the result if complete.
Returns Status::Internal() if !IsValid(), which may occur if coroutine state allocation fails.