traffic-light-macros 0.1.1

Macros for another single-threaded blocking asynchronous executor in rust.
Documentation
  • Coverage
  • 66.67%
    2 out of 3 items documented2 out of 3 items with examples
  • Size
  • Source code size: 9.73 kB This is the summed size of all the files inside the crates.io package for this release.
  • Documentation size: 280.26 kB This is the summed size of all files generated by rustdoc for all configured targets
  • Ø build duration
  • this release: 19s Average build duration of successful builds.
  • all releases: 24s Average build duration of successful builds in releases after 2024-10-23.
  • Links
  • red-taxicab/traffic-light-rs
    0 0 0
  • crates.io
  • Dependencies
  • Versions
  • Owners
  • red-taxicab

traffic-light-macros

Macros for another single-threaded blocking asynchronous executor in Rust.

Examples

Cargo.toml

[dependencies]
traffic-light = { version = "*", features = ["macros"] }

src/main.rs

use std::{
    error,
    pin::Pin,
    result,
    task::{Context, Poll},
    thread::{self, JoinHandle},
    time::{Duration, Instant},
};

enum State {
    Idle,
    Spawned(JoinHandle<()>),
    Completed,
}

pub struct Timer {
    state: State,
    deadline: Instant,
}

impl Timer {
    pub fn new(duration: Duration) -> Self {
        Self {
            state: State::Idle,
            deadline: (Instant::now() + duration),
        }
    }
}

impl Future for Timer {
    type Output = ();

    fn poll(mut self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll<Self::Output> {
        match &self.state {
            State::Idle => {
                let deadline = self.deadline;

                let waker = cx.waker().clone();

                let join_handle = thread::spawn(move || {
                    thread::sleep(deadline.saturating_duration_since(Instant::now()));

                    waker.wake();
                });

                self.state = State::Spawned(join_handle);

                Poll::Pending
            },
            State::Spawned(join_handle) => {
                if join_handle.is_finished() {
                    self.state = State::Completed;

                    Poll::Ready(())
                } else {
                    Poll::Pending
                }
            },
            State::Completed => Poll::Ready(()),
        }
    }
}

#[traffic_light::main]
async fn main() -> result::Result<(), Box<dyn error::Error>> {
    Timer::new(Duration::from_secs(5)).await;

    println!("Hello, world!");

    Ok(())
}

License

Licensed under either of MIT or Apache 2.0 at your option.