Struct genawaiter::stack::Gen
source · pub struct Gen<'s, Y, R, F: Future> { /* private fields */ }
Expand description
This is a generator which can be stack-allocated.
Implementations§
source§impl<'s, Y, R, F: Future> Gen<'s, Y, R, F>
impl<'s, Y, R, F: Future> Gen<'s, Y, R, F>
sourcepub unsafe fn new(
shelf: &'s mut Shelf<Y, R, F>,
producer: impl FnOnce(Co<'s, Y, R>) -> F,
) -> Self
pub unsafe fn new( shelf: &'s mut Shelf<Y, R, F>, producer: impl FnOnce(Co<'s, Y, R>) -> F, ) -> Self
Creates a new generator from a function.
The state of the generator is stored in shelf
, which will be pinned in
place while this generator exists. The generator itself is movable,
since it just holds a reference to the pinned state.
The function accepts a Co
object, and returns a future. Every time
the generator is resumed, the future is polled. Each time the future is
polled, it should do one of two things:
- Call
co.yield_()
, and then returnPoll::Pending
. - Drop the
Co
, and then returnPoll::Ready
.
Typically this exchange will happen in the context of an async fn
.
§Safety
The Co
object must not outlive the returned Gen
. By time the
generator completes (i.e., by time the producer’s Future returns
Poll::Ready
), the Co
object should already have been dropped. If
this invariant is not upheld, memory unsafety can result.
Afaik, the Rust compiler is not flexible enough to let you express this invariant in the type system, but I would love to be proven wrong!
§Examples
let mut shelf = Shelf::new();
let gen = unsafe { Gen::new(&mut shelf, producer) };
sourcepub fn resume_with(&mut self, arg: R) -> GeneratorState<Y, F::Output>
pub fn resume_with(&mut self, arg: R) -> GeneratorState<Y, F::Output>
Resumes execution of the generator.
arg
is the resume argument. If the generator was previously paused by
awaiting a future returned from co.yield()
, that future will complete,
and return arg
.
If the generator yields a value, Yielded
is returned. Otherwise,
Completed
is returned.
source§impl<'s, Y, F: Future> Gen<'s, Y, (), F>
impl<'s, Y, F: Future> Gen<'s, Y, (), F>
sourcepub fn resume(&mut self) -> GeneratorState<Y, F::Output>
pub fn resume(&mut self) -> GeneratorState<Y, F::Output>
Resumes execution of the generator.
If the generator yields a value, Yielded
is returned. Otherwise,
Completed
is returned.
sourcepub fn async_resume(
&mut self,
) -> impl Future<Output = GeneratorState<Y, F::Output>> + '_
pub fn async_resume( &mut self, ) -> impl Future<Output = GeneratorState<Y, F::Output>> + '_
Resumes execution of the generator.
If the generator pauses without yielding, Poll::Pending
is returned.
If the generator yields a value, Poll::Ready(Yielded)
is returned.
Otherwise, Poll::Ready(Completed)
is returned.