Expand description

A collection of lazy initialized values that are created by Futures.

OnceCell’s API should be familiar to anyone who has used the once_cell crate or the proposed std::lazy module. It provides an async version of a cell that can only be initialized once, permitting tasks to wait on the initialization if it is already running instead of racing multiple initialization tasks.

Unlike threads, tasks can be cancelled at any point where they block. OnceCell deals with this by allowing another initializer to run if the task currently initializing the cell is dropped. This also allows for fallible initialization using OnceCell::get_or_try_init, and for the initializing Future to contain borrows or use references to thread-local data.

OnceFuture and its wrappers Lazy and ConstLazy take the opposite approach: they wrap a single Future which is cooperatively run to completion by any polling task. This requires that the initialization function be independent of the calling context, but will never restart an initializing function just because the surrounding task was cancelled.

Overhead

Both cells use two usizes to store state and do not retain any allocations after initialization is complete. OnceCell only allocates if there is contention, whereas OnceFuture always allocates because it must have a pinned address for running the future.

Structs

A value which is initialized on the first access.

A value which is initialized on the first access.

A cell which can be written to only once.

A Future which is executed exactly once, producing an output accessible without locking.