Crate pasts

source ·
Expand description

Minimal and simpler alternative to the futures crate.

Optional Features

Only the std feature is enabled by default

  • Disable std to use pasts without the standard library.
  • Enable web to use pasts within the javascript DOM.

Getting Started

Add the following to your ./Cargo.toml:

[dependencies]
pasts = "0.13"

## This example uses async_main for convenience, but it is *not* required to
## use pasts.
async_main = { version = "0.2", features = ["pasts"] }

## This example uses async-std for a sleep future, but async-std is *not*
## required to use pasts.
async-std = "1.12"

## Also not required for pasts, but allows for portability with WebAssembly
## in the browser.
[features]
web = ["async_main/web", "pasts/web"]

Multi-Tasking On Multiple Iterators of Futures

This example runs two timers in parallel using the async-std crate counting from 0 to 6. The “one” task will always be run for count 6 and stop the program, although which task will run for count 5 may be either “one” or “two” because they trigger at the same time.

use core::time::Duration;

use async_main::{async_main, LocalSpawner};
use async_std::task::sleep;
use pasts::{prelude::*, Join, Loop};

// Exit type for App.
struct Exit;

// Shared state between tasks on the thread.
struct App<'a> {
    counter: usize,
    one: &'a mut (dyn Notifier<Event = ()> + Unpin),
    two: &'a mut (dyn Notifier<Event = ()> + Unpin),
}

impl App<'_> {
    fn one(&mut self, (): ()) -> Poll<Exit> {
        println!("One {}", self.counter);
        self.counter += 1;

        if self.counter > 6 {
            Ready(Exit)
        } else {
            Pending
        }
    }

    fn two(&mut self, (): ()) -> Poll<Exit> {
        println!("Two {}", self.counter);
        self.counter += 1;

        Pending
    }
}

#[async_main]
async fn main(_spawner: LocalSpawner) {
    let sleep = |seconds| sleep(Duration::from_secs_f64(seconds));
    let mut app = App {
        counter: 0,
        one: &mut Loop::pin(|| sleep(1.0)),
        two: &mut Loop::pin(|| sleep(2.0)),
    };

    Join::new(&mut app)
        .on(|s| s.one, App::one)
        .on(|s| s.two, App::two)
        .await;
}

Modules

Items that are almost always needed.

Structs

Pasts’ executor.
Composable asynchronous event loop.
A Notifier created from a function returning Futures.
A Notifier created from a function returning Poll.

Traits

Trait for “fusing” a Future (conversion to a Notifier).
Trait for asynchronous event notification.
Trait for implementing the parking / unparking threads.
Storage for a task pool.
Implementation for spawning tasks on an executor.

Type Definitions

An owned dynamically typed Notifier for use in cases where you can’t statically type your result or need to add some indirection.
BoxNotifier without the Send requirement.