⏲ situwaition: a library for waiting

Hey ya'll, got a new library that's all about waiting for stuff, check it out:

https://crates.io/crates/situwaition

Here's the current version's tokio example (async-std is also supported):

use std::{
    result::Result,
    sync::{Arc, Mutex},
    time::Duration,
};

use situwaition::{runtime::tokio::wait_for, runtime::AsyncWaiter, AsyncSituwaition};
use thiserror::Error;

#[derive(Debug, Error)]
enum ExampleError {
    #[error("not done counting yet")]
    NotDoneCountingError,

    #[error("mutex encounted a poison error")]
    MutexPoisonError,
}

// This example uses wait_for to wait for a value that changes, completely synchronously.
//
// By default, wait_for checks every 250ms, and times out after 3 seconds.
// this means the code below should wait 750ms in total, and value should never be above 3.
#[tokio::main]
async fn main() -> Result<(), Box<dyn std::error::Error>> {
    let value = Arc::new(Mutex::new(0));
    let shared_value = value.clone();

    eprintln!("finished setup");
    let result = wait_for(|| async {
        // Get the current value from the mutex
        let mut current_value = shared_value
            .lock()
            .map_err(|_| ExampleError::MutexPoisonError)?;

        // Act on the current value
        eprintln!("acting on unlocked value... {current_value}");
        if *current_value >= 2 {
            Ok(42)
        } else {
            *current_value += 1;
            Err(ExampleError::NotDoneCountingError)
        }
    })
    .await?;

    assert!(matches!(result, 42));
    eprintln!("resulting value is: {}", result);

    // This async waiter always fails, so it will resolve to a failure in 500ms
    let _ = AsyncWaiter::with_timeout(
        || async { Err(ExampleError::NotDoneCountingError) as Result<(), ExampleError> },
        Duration::from_millis(500),
    )?
    .exec()
    .await;
    eprintln!("asynchronous always-failing result: {:?}", result);

    Ok(())
}

The example is a little contrived but I hope it illustrates how to use the library!

2 Likes

I gave a quick look at the documentation but I can't find situwaition::runtime::tokio::wait_for, there's no tokio module in runtime. I see there's a tokio feature, so I guess they are cfged out, but it makes for a bad experience on docs.rs. Have you considered using the doc_cfg feature to properly document them? See for example this stackoverflow answer

Hey thanks for the feedback -- those do require tokio (the default is sync-only) -- I'll add!

[EDIT] Done, and a new version v0.3.1 is released (some breaking changes and a doc bump!), docs.rs should be updated shortly

Love the name :+1:

1 Like

This topic was automatically closed 90 days after the last reply. We invite you to open a new topic if you have further questions or comments.