Skip to main content

once_fn/
lib.rs

1//! Cache the result of a function so that its body runs only once.
2//!
3//! The [`once`] attribute caches the result of the annotated function: the
4//! first call runs the body, and every later call returns a clone of the cached
5//! result without running the body again. The arguments of later calls have no
6//! effect on the result.
7//!
8//! # Examples
9//!
10//! ```
11//! use once_fn::once;
12//!
13//! #[once]
14//! pub fn foo(b: bool) -> bool {
15//!     b
16//! }
17//!
18//! assert!(foo(true)); // runs the body and caches `true`
19//! assert!(foo(false)); // returns the cached `true`, body is not run again
20//! ```
21//!
22//! Reference returns are supported: the cache stores the pointee, and each call
23//! returns a reference to the cached value.
24//!
25//! ```
26//! use once_fn::once;
27//!
28//! #[once]
29//! pub fn foo2(b: &bool) -> &bool {
30//!     b
31//! }
32//!
33//! let b = true;
34//! assert_eq!(foo2(&b), &b);
35//! ```
36//!
37//! In impl blocks, apply [`once_impl`] to the block and [`once`] to the
38//! methods.
39//!
40//! ```
41//! use once_fn::{once, once_impl};
42//!
43//! struct Foo;
44//!
45//! #[once_impl]
46//! impl Foo {
47//!     #[once]
48//!     pub fn foo(b: bool) -> bool {
49//!         b
50//!     }
51//! }
52//!
53//! assert!(Foo::foo(true));
54//! assert!(Foo::foo(false)); // cached
55//! ```
56//!
57//! Methods inside `#[once_impl]` may return `Self`.
58//!
59//! ```
60//! use once_fn::{once, once_impl};
61//!
62//! #[derive(Clone, Debug, PartialEq, Eq)]
63//! struct Config {
64//!     value: u32,
65//! }
66//!
67//! #[once_impl]
68//! impl Config {
69//!     #[once]
70//!     fn first(x: u32) -> Self {
71//!         Config { value: x }
72//!     }
73//! }
74//!
75//! assert_eq!(Config::first(1), Config { value: 1 });
76//! assert_eq!(Config::first(2), Config { value: 1 }); // cached from the first call
77//! ```
78//!
79//! Returning [`std::sync::Arc`] is the pattern for large or non-[`Clone`]
80//! values: the cache stores the `Arc`, so every call only bumps the reference
81//! counter and the pointee type needs no `Clone`.
82//!
83//! ```
84//! use std::sync::Arc;
85//!
86//! use once_fn::once;
87//!
88//! struct Big([u8; 4096]); // does not implement Clone
89//!
90//! #[once]
91//! fn big() -> Arc<Big> {
92//!     Arc::new(Big([0; 4096]))
93//! }
94//!
95//! let a = big();
96//! let b = big();
97//! assert!(Arc::ptr_eq(&a, &b)); // both calls share one allocation
98//! assert_eq!(a.0.len(), 4096);
99//! ```
100//!
101//! `#[once(by_ref)]` is the alternative for non-[`Clone`] values: the body
102//! returns an owned value (as written), the cache stores it directly, and the
103//! generated function returns `&'static` references to it. This is the
104//! [`std::sync::LazyLock`] pattern without the static boilerplate; the
105//! trade-off is that callers cannot own the value.
106//!
107//! ```
108//! use once_fn::once;
109//!
110//! struct Huge([u8; 4096]); // does not implement Clone
111//!
112//! #[once(by_ref)]
113//! fn huge() -> Huge {
114//!     Huge([0; 4096])
115//! }
116//!
117//! let a: &'static Huge = huge();
118//! assert!(std::ptr::eq(a, huge())); // both calls borrow the same cached slot
119//! ```
120//!
121//! `#[once(resettable)]` switches to a resettable cache and generates a
122//! companion `<function>_reset` function with the same visibility: calling it
123//! drops the cached value, so the next call runs the body again.
124//!
125//! ```
126//! use std::sync::atomic::{AtomicUsize, Ordering};
127//!
128//! use once_fn::once;
129//!
130//! static RUNS: AtomicUsize = AtomicUsize::new(0);
131//!
132//! #[once(resettable)]
133//! fn stamped() -> usize {
134//!     RUNS.fetch_add(1, Ordering::SeqCst) + 1
135//! }
136//!
137//! assert_eq!(stamped(), 1);
138//! assert_eq!(stamped(), 1); // cached
139//! stamped_reset();
140//! assert_eq!(stamped(), 2); // runs again
141//! ```
142//!
143//! # Async
144//!
145//! `async fn` is supported: the body runs to completion once and the awaited
146//! result is cached; every later call returns a clone without re-running the
147//! body. If the first call is cancelled before the body finishes, or the body
148//! panics, the next call runs the body again.
149//!
150//! ```
151//! use once_fn::once;
152//!
153//! #[once]
154//! async fn answer() -> u32 {
155//!     tokio::task::yield_now().await;
156//!     42
157//! }
158//!
159//! #[tokio::main]
160//! async fn main() {
161//!     assert_eq!(answer().await, 42);
162//!     assert_eq!(answer().await, 42); // cached
163//! }
164//! ```
165//!
166//! The async cache is [`AsyncOnceCell`], a runtime-agnostic asynchronous once
167//! cell that can also be used directly.
168//!
169//! # Semantics
170//!
171//! - Only the first call runs the body; arguments of later calls are still evaluated at the call
172//!   site, but the body does not run, so they have no effect on the result.
173//! - A failing first attempt caches nothing: if the body panics, or an async initializer is
174//!   cancelled before it finishes, the next call runs the body again, so the body may run more than
175//!   once.
176//! - Concurrent first calls run the body exactly once: sync callers block inside `get_or_init`
177//!   until the value is available, while async callers park as futures and are woken when the value
178//!   is stored, without blocking any thread. The async initializer is polled inside the first
179//!   caller's task: nothing is spawned, and awaiting other once fns inside the body is fine, though
180//!   synchronous stretches of the body run on that task.
181//! - Every returned value is cached, failures included: after a first call returns `Err(..)`, every
182//!   later call returns the same `Err` again.
183//! - The cached value is never dropped and lives until process exit; the only exception is
184//!   `#[once(resettable)]`, whose `<function>_reset` drops it.
185//! - A once method's cache is one static per function, shared across all instances of the type.
186//!
187//! # Panics
188//!
189//! If a once function is called again while its body is running (directly or
190//! indirectly, on the same thread), the reentrant call panics with a clear
191//! message instead of deadlocking on the cache. An async once fn awaited again
192//! from inside its own initializing body panics the same way. Cross-thread
193//! reentrancy, where the initializing thread and the re-entering thread end up
194//! waiting on each other, is not detected and still deadlocks.
195//!
196//! # Limitations
197//!
198//! The cached value is returned by cloning, so the declared return type must
199//! implement [`Clone`]; for a reference return, the pointee must implement
200//! `Clone`. The exceptions are `#[once(by_ref)]` (no `Clone`, but the return
201//! type must be `'static`) and an [`std::sync::Arc`] return (cheap clones).
202//!
203//! The following forms are rejected at compile time:
204//!
205//! - generic functions and generic impls (lifetime-only generics are fine): the cache is one static
206//!   shared by all monomorphizations, so caching would silently mix instantiations; `impl Trait` in
207//!   argument or return position is rejected for the same reason.
208//! - `const fn`, `-> &mut T`, and unsized pointees (`-> &str`, `-> &[T]`, `-> &dyn Trait`).
209//! - `#[once(resettable)]` on an `async fn`, on a reference return type, or inside an
210//!   `#[once_impl]` block.
211//! - `#[once(by_ref)]` on a reference return type, on a non-`'static` return type, or together with
212//!   `resettable`.
213
214mod async_once_cell;
215
216#[doc(inline)]
217pub use async_once_cell::AsyncOnceCell;
218#[doc(inline)]
219pub use once_fn_macros::{once, once_impl};