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