#future #upper-bound #scope #hrtb #liftime

no-std scoped-futures

A utility crate for imposing upper bounds on Future lifetimes

4 releases

0.1.3 Jan 2, 2023
0.1.2 Nov 8, 2022
0.1.1 Nov 8, 2022
0.1.0 Nov 8, 2022

#118 in Asynchronous

Download history 15207/week @ 2023-12-12 13053/week @ 2023-12-19 6971/week @ 2023-12-26 15334/week @ 2024-01-02 16867/week @ 2024-01-09 18523/week @ 2024-01-16 18453/week @ 2024-01-23 17789/week @ 2024-01-30 17727/week @ 2024-02-06 17733/week @ 2024-02-13 20248/week @ 2024-02-20 20644/week @ 2024-02-27 22708/week @ 2024-03-05 20458/week @ 2024-03-12 21157/week @ 2024-03-19 19624/week @ 2024-03-26

87,569 downloads per month
Used in 30 crates (5 directly)

MIT/Apache

13KB
115 lines

scoped-futures

A utility crate for imposing upper bounds on Future lifetimes. This is especially useful for callbacks that use higher-ranked lifetimes in their return type, where it can prevent 'static bounds from being placed on a returned Future.

Example

use core::pin::Pin;
use scoped_futures::{ScopedBoxFuture, ScopedFutureExt};

pub struct Db {
    count: u8,
}

impl Db {
    async fn transaction<'a, F, T, E>(&mut self, callback: F) -> Result<T, E>
    where
        // ScopedBoxFuture imposes a lifetime bound on 'b which prevents the hrtb below needing
        // to be satisfied for all lifetimes (including 'static) and instead only lifetimes
        // which live at most as long as 'a
        F: for<'b /* where 'a: 'b */> FnOnce(&'b mut Self) -> ScopedBoxFuture<'a, 'b, Result<T, E>> + Send + 'a,
        T: 'a,
        E: 'a,
    {
        callback(self).await
    }
}`

pub async fn test_transaction<'a, 'b>(
    db: &mut Db,
    ok: &'a str,
    err: &'b str,
    is_ok: bool,
) -> Result<&'a str, &'b str> {
    // note the lack of `move` or any cloning in front of the closure
    db.transaction(|db| async move {
        db.count += 1;
        if is_ok {
            Ok(ok)
        } else {
            Err(err)
        }
    }.scope_boxed()).await?;

    // note that `async` can be used instead of `async move` since the callback param is unused
    db.transaction(|_| async {
        if is_ok {
            Ok(ok)
        } else {
            Err(err)
        }
    }.scope_boxed()).await
}

#[test]
fn test_transaction_works() {
    futures::executor::block_on(async {
        let mut db = Db { count: 0 };
        let ok = String::from("ok");
        let err = String::from("err");
        let result = test_transaction(&mut db, &ok, &err, true).await;
        assert_eq!(ok, result.unwrap());
        assert_eq!(1, db.count);
    })
}

Dependencies

~10KB