Crate switch_resume

source ·
Expand description

switch-resume

This crates provides functionality for running switchable tasks (futures).

Switching is a control flow mechanism that pauses normal execution of current task, captures current continuation and passes it as an argument to the provided async fn. The task then proceeds by evaluating that fn, instead of resuming normally.

In order to resume normal execution, the passed resumption object can be called explicitly.

This is an implementation of delimited continuations in Rust using async that works on stable.

Examples

fn main() {
    futures::executor::block_on(async {
        switch_resume::run(|task| async move {
            println!("begin");
            task.switch(|resume| async move {
                println!("before");
                resume(()).await;
                println!("after");
            })
            .await;
            println!("end");
        })
        .await;
    });
    // begin
    // before
    // end
    // after
}
fn main() {
    futures::executor::block_on(async {
        async fn bar(resume: switch_resume::Resume<'_, i32, i32>) -> i32 {
            println!("foo has been paused, started bar");
            let resume_result = resume(69).await;
            assert_eq!(resume_result, -1); // This is the result of foo
            420 // This is the final result of task
        }
        async fn foo(task: switch_resume::Task<'_, i32>) -> i32 {
            println!("foo started");
            let value = task.switch(bar).await;
            println!("foo was resumed with {value}. Nice!");
            -1 // This is not the final task result since we switched to bar
        }
        let task_result = switch_resume::run(foo).await;
        assert_eq!(task_result, 420);
    });
}

Structs

  • Handle to the running task.

Functions

  • Run a task with switch capability.

Type Aliases