#lazy-evaluation #once #static #lazy

async-oncecell

Asynchronous versions of OnceCell and Lazy

2 unstable releases

0.2.0 Apr 16, 2021
0.1.0 Apr 8, 2021

#710 in Asynchronous

Download history 47/week @ 2023-11-24 28/week @ 2023-12-01 97/week @ 2023-12-08 116/week @ 2023-12-15 42/week @ 2023-12-22 55/week @ 2023-12-29 86/week @ 2024-01-05 122/week @ 2024-01-12 81/week @ 2024-01-19 86/week @ 2024-01-26 56/week @ 2024-02-02 132/week @ 2024-02-09 136/week @ 2024-02-16 144/week @ 2024-02-23 122/week @ 2024-03-01 63/week @ 2024-03-08

482 downloads per month
Used in jcargo

MIT/Apache

13KB
164 lines

async-oncecell

Crates.io MIT or Apache 2.0 licensed Continuous integration

This crate offers an asynchronous version of Rust's OnceCell and Lazy structs, which allows its users to use async/await inside of the OnceCell and Lazy constructors.

The crate should work with any stable asynchronous runtime like tokio and async-std and only depends on the futures crate for an async aware Mutex.

Usage

The OnceCell can be used the similarly to the other popular OnceCell crates, and the implementation in the standard library with the exception that a Future is given instead of a closjure and that some functions return a Future.

Example

use async_oncecell::OnceCell;

#[tokio::main]
async fn main() {
    let cell = OnceCell::new();
    let v = cell.get_or_init(async { 
        // Expensive operation
     }).await;
    assert_eq!(cell.get(), Some(v));
}

The same holds for Lazy, however since the get() method needs to be awaited, no automatic dereferencing is implemented.

Example

use async_oncecell::Lazy;

#[tokio::main]
async fn main() {
    let lazy_value = Lazy::new(async {
        // Expensive operation
    });
    assert_eq!(lazy_value.get().await, /* result of expensive operation */);
}

Stability

This crate is extremely new and has therefore not extensively been tested. Next to that, the author is also inexperienced in working with unsafe Rust. While care has been taken in making this crate safe, it is not recommended for production use. As mentioned in the Contributing section: feedback and pull requests are very much appreciated, even more so if you see any problems with the soundness of the crate.

Contributing

Contributions are always welcome! Please create an issue or pull request if you have any insight which might help to improve this crate. This is my first real Rust crate, so I'm eager to learn from the community.

Wishlist

In the future I hope to add asynchronous transform structs as well to be able to transform data lazily.

Dependencies

~1MB
~16K SLoC