Skip to main content

asyncband/once/once_cell/
mod.rs

1// Licensed to the Apache Software Foundation (ASF) under one
2// or more contributor license agreements.  See the NOTICE file
3// distributed with this work for additional information
4// regarding copyright ownership.  The ASF licenses this file
5// to you under the Apache License, Version 2.0 (the
6// "License"); you may not use this file except in compliance
7// with the License.  You may obtain a copy of the License at
8//
9//   http://www.apache.org/licenses/LICENSE-2.0
10//
11// Unless required by applicable law or agreed to in writing,
12// software distributed under the License is distributed on an
13// "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
14// KIND, either express or implied.  See the License for the
15// specific language governing permissions and limitations
16// under the License.
17
18// Portions of this file originated from Tokio 1.47.0's OnceCell implementation.
19// Copyright (c) Tokio Contributors
20// The Tokio-derived portions remain licensed under the MIT License.
21// Asyncband substantially changed the synchronization model: initialization does not close the
22// semaphore, the cell can be emptied and initialized again, and value storage is delegated to a
23// reusable ValueCell shared with LazyCell.
24// Upstream source:
25// https://github.com/tokio-rs/tokio/blob/3911cb8523f190142f61c64b66881c07c0d3e7be/tokio/src/sync/once_cell.rs
26
27use std::convert::Infallible;
28use std::fmt;
29
30use crate::internal::value_cell::ValueCell;
31use crate::semaphore::Semaphore;
32use crate::semaphore::SemaphorePermit;
33
34/// A thread-safe cell that stores one value from an initializer supplied at access time.
35///
36/// Callers provide an initializer when accessing an empty cell. An initializer that returns an
37/// error, panics, or is cancelled leaves the cell empty so a later caller can retry. Use
38/// `LazyCell` instead when the cell should own a one-shot initializer and preserve its in-flight
39/// future across caller cancellation.
40///
41/// # Examples
42///
43/// ```
44/// # #[tokio::main]
45/// # async fn main() {
46/// use std::sync::Arc;
47///
48/// use asyncband::once::OnceCell;
49///
50/// static CELL: OnceCell<u8> = OnceCell::new();
51///
52/// let handle1 = tokio::spawn(async { CELL.get_or_init(move || async { 1 }).await });
53/// let handle2 = tokio::spawn(async { CELL.get_or_init(move || async { 2 }).await });
54/// let result1 = handle1.await.unwrap();
55/// let result2 = handle2.await.unwrap();
56/// assert_eq!(result1, result2);
57/// assert!(*result1 == 1 || *result1 == 2);
58/// # }
59/// ```
60pub struct OnceCell<T> {
61    value: ValueCell<T>,
62    // Each initializer takes two of three permits, so only one can run at a time. The spare
63    // permit lets an uncontended release avoid locking the semaphore's wait queue.
64    semaphore: Semaphore,
65}
66
67impl<T> Default for OnceCell<T> {
68    fn default() -> Self {
69        Self::new()
70    }
71}
72
73impl<T> OnceCell<T> {
74    /// Creates a new empty `OnceCell`.
75    pub const fn new() -> Self {
76        Self {
77            value: ValueCell::new(),
78            semaphore: Semaphore::new(3),
79        }
80    }
81
82    /// Creates a new `OnceCell` initialized with the provided value.
83    pub const fn from_value(value: T) -> Self {
84        Self {
85            value: ValueCell::from_value(value),
86            semaphore: Semaphore::new(3),
87        }
88    }
89
90    /// Returns whether the cell contains a value.
91    // `OnceMap` and `singleflight` inspect this state, while a standalone `OnceCell` build does
92    // not need the internal helper.
93    #[allow(dead_code)]
94    pub(crate) fn initialized(&self) -> bool {
95        self.value.is_initialized()
96    }
97
98    /// Returns whether the cell contains a value.
99    pub(crate) fn initialized_mut(&mut self) -> bool {
100        self.value.is_initialized_mut()
101    }
102
103    /// Returns the stored value.
104    ///
105    /// Returns `None` if the cell is uninitialized, or being initialized.
106    ///
107    /// This method never blocks.
108    pub fn get(&self) -> Option<&T> {
109        self.value.get()
110    }
111
112    /// Returns mutable access to the stored value.
113    ///
114    /// Returns `None` if the cell is uninitialized.
115    ///
116    /// This method never blocks. Since it borrows the `OnceCell` mutably, it is statically
117    /// guaranteed that no active borrows to the `OnceCell` exist, including from other threads.
118    pub fn get_mut(&mut self) -> Option<&mut T> {
119        self.value.get_mut()
120    }
121
122    /// Returns the value, initializing an empty cell with the provided asynchronous function.
123    ///
124    /// If some other task is currently working on initializing the `OnceCell`, this call will wait
125    /// for that other task to finish, then return the value that the other task produced.
126    ///
127    /// If the provided operation is cancelled, the initialization attempt is cancelled. If there
128    /// are other tasks waiting for the value to be initialized, one of them will start another
129    /// attempt at initializing the value.
130    ///
131    /// This will deadlock if `init` tries to initialize the cell recursively.
132    pub async fn get_or_init<F>(&self, init: F) -> &T
133    where
134        F: AsyncFnOnce() -> T,
135    {
136        match self
137            .get_or_try_init(async || Ok::<T, Infallible>(init().await))
138            .await
139        {
140            Ok(val) => val,
141        }
142    }
143
144    /// Returns the value, initializing an empty cell with the provided fallible asynchronous
145    /// function.
146    ///
147    /// If some other task is currently working on initializing the `OnceCell`, this call will wait
148    /// for that other task to finish, then return the value that the other task produced.
149    ///
150    /// If the provided operation returns an error, is cancelled or panics, the initialization
151    /// attempt is cancelled. If there are other tasks waiting for the value to be initialized
152    /// one of them will start another attempt at initializing the value.
153    ///
154    /// This will deadlock if `init` tries to initialize the cell recursively.
155    pub async fn get_or_try_init<E, F>(&self, init: F) -> Result<&T, E>
156    where
157        F: AsyncFnOnce() -> Result<T, E>,
158    {
159        if let Some(v) = self.get() {
160            return Ok(v);
161        }
162
163        let permit = self.semaphore.acquire(2).await;
164
165        if let Some(v) = self.get() {
166            // double-checked: another task initialized the value
167            // while we were waiting for the permit
168            return Ok(v);
169        }
170
171        let value = init().await?;
172        Ok(self.set_value(value, permit))
173    }
174
175    /// Returns mutable access to the value, initializing an empty cell asynchronously.
176    ///
177    /// This method never blocks other tasks because it takes `&mut self`, which guarantees
178    /// exclusive access to the `OnceCell` and thus no concurrent initialization can be in
179    /// progress.
180    ///
181    /// If the cell is already initialized, it returns a mutable reference to the existing value.
182    /// Otherwise, it runs `init`, stores the result, and returns a mutable reference to the newly
183    /// initialized value.
184    ///
185    /// # Examples
186    ///
187    /// ```
188    /// # #[tokio::main]
189    /// # async fn main() {
190    /// use asyncband::once::OnceCell;
191    ///
192    /// let mut cell: OnceCell<u32> = OnceCell::new();
193    /// let v = cell.get_mut_or_init(|| async { 41 }).await;
194    /// *v += 1;
195    /// assert_eq!(*cell.get().unwrap(), 42);
196    /// # }
197    /// ```
198    pub async fn get_mut_or_init<F>(&mut self, init: F) -> &mut T
199    where
200        F: AsyncFnOnce() -> T,
201    {
202        match self
203            .get_mut_or_try_init(async || Ok::<T, Infallible>(init().await))
204            .await
205        {
206            Ok(val) => val,
207        }
208    }
209
210    /// Returns mutable access to the value, initializing an empty cell with a fallible asynchronous
211    /// function.
212    ///
213    /// This method never blocks other tasks because it takes `&mut self`, which guarantees
214    /// exclusive access to the `OnceCell` and thus no concurrent initialization can be in
215    /// progress.
216    ///
217    /// If the cell is already initialized, it returns a mutable reference to the existing value.
218    /// Otherwise, it runs `init`. On success, it stores the result and returns a mutable
219    /// reference to the newly initialized value. On error, it returns the error and leaves the
220    /// cell uninitialized.
221    ///
222    /// # Examples
223    ///
224    /// ```
225    /// # #[tokio::main]
226    /// # async fn main() {
227    /// use asyncband::once::OnceCell;
228    ///
229    /// let mut cell: OnceCell<u32> = OnceCell::new();
230    /// assert!(
231    ///     cell.get_mut_or_try_init(|| async { Err(()) })
232    ///         .await
233    ///         .is_err()
234    /// );
235    /// let v = cell
236    ///     .get_mut_or_try_init(|| async { Ok::<_, ()>(10) })
237    ///     .await
238    ///     .unwrap();
239    /// *v += 5;
240    /// assert_eq!(*cell.get().unwrap(), 15);
241    /// # }
242    /// ```
243    pub async fn get_mut_or_try_init<E, F>(&mut self, init: F) -> Result<&mut T, E>
244    where
245        F: AsyncFnOnce() -> Result<T, E>,
246    {
247        // Workaround if let Some(v) = self.get_mut() { return Ok(v); }
248        // @see https://github.com/rust-lang/rust/issues/51545
249        if self.initialized_mut() {
250            return Ok(self
251                .value
252                .get_mut()
253                .expect("OnceCell initialized value missing"));
254        }
255
256        let value = init().await?;
257        Ok(self.set_value_mut(value))
258    }
259
260    /// Initializes the contents of the cell to `value` if the cell was uninitialized,
261    /// then returns a reference to it.
262    ///
263    /// May wait if another task is currently attempting to initialize the cell. The cell is
264    /// guaranteed to contain a value when `try_insert` returns, though not necessarily the
265    /// one provided.
266    ///
267    /// Returns `Ok(&value)` if the cell was uninitialized and `Err((&current_value, value))`
268    /// if it was already initialized.
269    ///
270    /// # Examples
271    ///
272    /// ```
273    /// use asyncband::once::OnceCell;
274    ///
275    /// static CELL: OnceCell<i32> = OnceCell::new();
276    ///
277    /// # #[tokio::main]
278    /// # async fn main() {
279    /// assert!(CELL.get().is_none());
280    ///
281    /// tokio::spawn(async {
282    ///     assert_eq!(CELL.try_insert(92).await, Ok(&92));
283    /// })
284    /// .await
285    /// .unwrap();
286    ///
287    /// assert_eq!(CELL.try_insert(62).await, Err((&92, 62)));
288    /// assert_eq!(CELL.get(), Some(&92));
289    /// # }
290    /// ```
291    pub async fn try_insert(&self, value: T) -> Result<&T, (&T, T)> {
292        let mut value = Some(value);
293        let res = self.get_or_init(async || value.take().unwrap()).await;
294        match value {
295            None => Ok(res),
296            Some(value) => Err((res, value)),
297        }
298    }
299
300    /// Initializes the contents of the cell to `value`.
301    ///
302    /// May wait if another task is currently attempting to initialize the cell. The cell is
303    /// guaranteed to contain a value when `set` returns, though not necessarily the one provided.
304    ///
305    /// Returns `Ok(())` if the cell was uninitialized and `Err(value)` if the cell was already
306    /// initialized.
307    ///
308    /// # Examples
309    ///
310    /// ```
311    /// use asyncband::once::OnceCell;
312    ///
313    /// static CELL: OnceCell<i32> = OnceCell::new();
314    ///
315    /// # #[tokio::main]
316    /// # async fn main() {
317    /// assert!(CELL.get().is_none());
318    ///
319    /// tokio::spawn(async {
320    ///     assert_eq!(CELL.set(92).await, Ok(()));
321    /// })
322    /// .await
323    /// .unwrap();
324    ///
325    /// assert_eq!(CELL.set(62).await, Err(62));
326    /// assert_eq!(CELL.get(), Some(&92));
327    /// # }
328    /// ```
329    pub async fn set(&self, value: T) -> Result<(), T> {
330        match self.try_insert(value).await {
331            Ok(_) => Ok(()),
332            Err((_, value)) => Err(value),
333        }
334    }
335
336    /// Consumes the `OnceCell`, returning the wrapped value. Returns `None` if the cell was
337    /// uninitialized.
338    ///
339    /// # Examples
340    ///
341    /// ```
342    /// use asyncband::once::OnceCell;
343    ///
344    /// # #[tokio::main]
345    /// # async fn main() {
346    /// let cell: OnceCell<String> = OnceCell::new();
347    /// assert_eq!(cell.into_inner(), None);
348    ///
349    /// let cell = OnceCell::new();
350    /// cell.set("hello".to_string()).await.unwrap();
351    /// assert_eq!(cell.into_inner(), Some("hello".to_string()));
352    /// # }
353    /// ```
354    pub fn into_inner(self) -> Option<T> {
355        self.value.into_inner()
356    }
357
358    /// Takes the value out of this `OnceCell`, moving it back to an uninitialized state.
359    ///
360    /// Has no effect and returns `None` if the `OnceCell` was uninitialized.
361    ///
362    /// Since this method borrows the `OnceCell` mutably, it is statically guaranteed that
363    /// no active borrows to the `OnceCell` exist, including from other threads.
364    ///
365    /// # Examples
366    ///
367    /// ```
368    /// use asyncband::once::OnceCell;
369    ///
370    /// # #[tokio::main]
371    /// # async fn main() {
372    /// let mut cell: OnceCell<String> = OnceCell::new();
373    /// assert_eq!(cell.take(), None);
374    ///
375    /// let mut cell = OnceCell::new();
376    /// cell.set("hello".to_string()).await.unwrap();
377    /// assert_eq!(cell.take(), Some("hello".to_string()));
378    /// assert_eq!(cell.get(), None);
379    /// # }
380    /// ```
381    pub fn take(&mut self) -> Option<T> {
382        self.value.take()
383    }
384
385    fn set_value(&self, value: T, _permit: SemaphorePermit<'_>) -> &T {
386        // SAFETY: Holding two of the three semaphore permits serializes initialization.
387        unsafe { self.value.set(value) }
388    }
389
390    fn set_value_mut(&mut self, value: T) -> &mut T {
391        self.value.set_mut(value)
392    }
393}
394
395impl<T: fmt::Debug> fmt::Debug for OnceCell<T> {
396    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
397        let mut d = f.debug_tuple("OnceCell");
398        match self.get() {
399            Some(v) => d.field(v),
400            None => d.field(&format_args!("<uninit>")),
401        };
402        d.finish()
403    }
404}
405
406impl<T: Clone> Clone for OnceCell<T> {
407    fn clone(&self) -> OnceCell<T> {
408        match self.get() {
409            Some(v) => OnceCell::from_value(v.clone()),
410            None => OnceCell::new(),
411        }
412    }
413}
414
415impl<T> From<T> for OnceCell<T> {
416    fn from(value: T) -> Self {
417        OnceCell::from_value(value)
418    }
419}
420
421impl<T: PartialEq> PartialEq for OnceCell<T> {
422    fn eq(&self, other: &Self) -> bool {
423        self.get() == other.get()
424    }
425}
426
427impl<T: Eq> Eq for OnceCell<T> {}