Skip to main content

core/cell/
once.rs

1use crate::cell::UnsafeCell;
2use crate::{fmt, mem};
3
4/// A cell which can nominally be written to only once.
5///
6/// This allows obtaining a shared `&T` reference to its inner value without copying or replacing
7/// it (unlike [`Cell`]), and without runtime borrow checks (unlike [`RefCell`]). However,
8/// only immutable references can be obtained unless one has a mutable reference to the cell
9/// itself. In the same vein, the cell can only be re-initialized with such a mutable reference.
10///
11/// A `OnceCell` can be thought of as a safe abstraction over uninitialized data that becomes
12/// initialized once written.
13///
14/// For a thread-safe version of this struct, see [`std::sync::OnceLock`].
15///
16/// [`RefCell`]: crate::cell::RefCell
17/// [`Cell`]: crate::cell::Cell
18/// [`std::sync::OnceLock`]: ../../std/sync/struct.OnceLock.html
19///
20/// # Examples
21///
22/// ```
23/// use std::cell::OnceCell;
24///
25/// let cell = OnceCell::new();
26/// assert!(cell.get().is_none());
27///
28/// let value: &String = cell.get_or_init(|| {
29///     "Hello, World!".to_string()
30/// });
31/// assert_eq!(value, "Hello, World!");
32/// assert!(cell.get().is_some());
33/// ```
34#[stable(feature = "once_cell", since = "1.70.0")]
35pub struct OnceCell<T> {
36    // Invariant: written to at most once.
37    inner: UnsafeCell<Option<T>>,
38}
39
40impl<T> OnceCell<T> {
41    /// Creates a new uninitialized cell.
42    #[inline]
43    #[must_use]
44    #[stable(feature = "once_cell", since = "1.70.0")]
45    #[rustc_const_stable(feature = "once_cell", since = "1.70.0")]
46    pub const fn new() -> OnceCell<T> {
47        OnceCell { inner: UnsafeCell::new(None) }
48    }
49
50    /// Creates a new initialized cell.
51    ///
52    /// This is equivalent to `OnceCell::from(value)`, but can be used in
53    /// const contexts, unlike the `From` implementation.
54    ///
55    /// # Examples
56    ///
57    /// ```
58    /// #![feature(once_cell_new_init)]
59    /// use std::cell::OnceCell;
60    ///
61    /// const CELL: OnceCell<i32> = OnceCell::new_init(1);
62    /// assert_eq!(CELL.get(), Some(&1));
63    ///
64    /// let cell = OnceCell::new_init(String::from("kitty"));
65    /// assert_eq!(cell.set(String::from("puppy")), Err(String::from("puppy")));
66    /// assert_eq!(cell.get(), Some(&"kitty".to_string()));
67    /// ```
68    #[inline]
69    #[must_use]
70    #[unstable(feature = "once_cell_new_init", issue = "159859")]
71    pub const fn new_init(init_value: T) -> OnceCell<T> {
72        OnceCell { inner: UnsafeCell::new(Some(init_value)) }
73    }
74
75    /// Gets the reference to the underlying value.
76    ///
77    /// Returns `None` if the cell is uninitialized.
78    #[inline]
79    #[stable(feature = "once_cell", since = "1.70.0")]
80    pub fn get(&self) -> Option<&T> {
81        // SAFETY: Safe due to `inner`'s invariant
82        unsafe { &*self.inner.get() }.as_ref()
83    }
84
85    /// Gets the mutable reference to the underlying value.
86    ///
87    /// Returns `None` if the cell is uninitialized.
88    #[inline]
89    #[stable(feature = "once_cell", since = "1.70.0")]
90    pub fn get_mut(&mut self) -> Option<&mut T> {
91        self.inner.get_mut().as_mut()
92    }
93
94    /// Initializes the contents of the cell to `value`.
95    ///
96    /// # Errors
97    ///
98    /// This method returns `Ok(())` if the cell was uninitialized
99    /// and `Err(value)` if it was already initialized.
100    ///
101    /// # Examples
102    ///
103    /// ```
104    /// use std::cell::OnceCell;
105    ///
106    /// let cell = OnceCell::new();
107    /// assert!(cell.get().is_none());
108    ///
109    /// assert_eq!(cell.set(92), Ok(()));
110    /// assert_eq!(cell.set(62), Err(62));
111    ///
112    /// assert!(cell.get().is_some());
113    /// ```
114    #[inline]
115    #[stable(feature = "once_cell", since = "1.70.0")]
116    #[rustc_should_not_be_called_on_const_items]
117    pub fn set(&self, value: T) -> Result<(), T> {
118        match self.try_insert(value) {
119            Ok(_) => Ok(()),
120            Err((_, value)) => Err(value),
121        }
122    }
123
124    /// Initializes the contents of the cell to `value` if the cell was
125    /// uninitialized, then returns a reference to it.
126    ///
127    /// # Errors
128    ///
129    /// This method returns `Ok(&value)` if the cell was uninitialized
130    /// and `Err((&current_value, value))` if it was already initialized.
131    ///
132    /// # Examples
133    ///
134    /// ```
135    /// #![feature(once_cell_try_insert)]
136    ///
137    /// use std::cell::OnceCell;
138    ///
139    /// let cell = OnceCell::new();
140    /// assert!(cell.get().is_none());
141    ///
142    /// assert_eq!(cell.try_insert(92), Ok(&92));
143    /// assert_eq!(cell.try_insert(62), Err((&92, 62)));
144    ///
145    /// assert!(cell.get().is_some());
146    /// ```
147    #[inline]
148    #[unstable(feature = "once_cell_try_insert", issue = "116693")]
149    #[rustc_should_not_be_called_on_const_items]
150    pub fn try_insert(&self, value: T) -> Result<&T, (&T, T)> {
151        if let Some(old) = self.get() {
152            return Err((old, value));
153        }
154
155        // SAFETY: This is the only place where we set the slot, no races
156        // due to reentrancy/concurrency are possible, and we've
157        // checked that slot is currently `None`, so this write
158        // maintains the `inner`'s invariant.
159        let slot = unsafe { &mut *self.inner.get() };
160        Ok(slot.insert(value))
161    }
162
163    /// Gets the contents of the cell, initializing it to `f()`
164    /// if the cell was uninitialized.
165    ///
166    /// # Panics
167    ///
168    /// If `f()` panics, the panic is propagated to the caller, and the cell
169    /// remains uninitialized.
170    ///
171    /// It is an error to reentrantly initialize the cell from `f`. Doing
172    /// so results in a panic.
173    ///
174    /// # Examples
175    ///
176    /// ```
177    /// use std::cell::OnceCell;
178    ///
179    /// let cell = OnceCell::new();
180    /// let value = cell.get_or_init(|| 92);
181    /// assert_eq!(value, &92);
182    /// let value = cell.get_or_init(|| unreachable!());
183    /// assert_eq!(value, &92);
184    /// ```
185    #[inline]
186    #[stable(feature = "once_cell", since = "1.70.0")]
187    #[rustc_should_not_be_called_on_const_items]
188    pub fn get_or_init<F>(&self, f: F) -> &T
189    where
190        F: FnOnce() -> T,
191    {
192        match self.get_or_try_init(|| Ok::<T, !>(f())) {
193            Ok(val) => val,
194        }
195    }
196
197    /// Gets the mutable reference of the contents of the cell,
198    /// initializing it to `f()` if the cell was uninitialized.
199    ///
200    /// # Panics
201    ///
202    /// If `f()` panics, the panic is propagated to the caller, and the cell
203    /// remains uninitialized.
204    ///
205    /// # Examples
206    ///
207    /// ```
208    /// #![feature(once_cell_get_mut)]
209    ///
210    /// use std::cell::OnceCell;
211    ///
212    /// let mut cell = OnceCell::new();
213    /// let value = cell.get_mut_or_init(|| 92);
214    /// assert_eq!(*value, 92);
215    ///
216    /// *value += 2;
217    /// assert_eq!(*value, 94);
218    ///
219    /// let value = cell.get_mut_or_init(|| unreachable!());
220    /// assert_eq!(*value, 94);
221    /// ```
222    #[inline]
223    #[unstable(feature = "once_cell_get_mut", issue = "121641")]
224    pub fn get_mut_or_init<F>(&mut self, f: F) -> &mut T
225    where
226        F: FnOnce() -> T,
227    {
228        match self.get_mut_or_try_init(|| Ok::<T, !>(f())) {
229            Ok(val) => val,
230        }
231    }
232
233    /// Gets the contents of the cell, initializing it to `f()` if
234    /// the cell was uninitialized. If the cell was uninitialized
235    /// and `f()` failed, an error is returned.
236    ///
237    /// # Panics
238    ///
239    /// If `f()` panics, the panic is propagated to the caller, and the cell
240    /// remains uninitialized.
241    ///
242    /// It is an error to reentrantly initialize the cell from `f`. Doing
243    /// so results in a panic.
244    ///
245    /// # Examples
246    ///
247    /// ```
248    /// #![feature(once_cell_try)]
249    ///
250    /// use std::cell::OnceCell;
251    ///
252    /// let cell = OnceCell::new();
253    /// assert_eq!(cell.get_or_try_init(|| Err(())), Err(()));
254    /// assert!(cell.get().is_none());
255    /// let value = cell.get_or_try_init(|| -> Result<i32, ()> {
256    ///     Ok(92)
257    /// });
258    /// assert_eq!(value, Ok(&92));
259    /// assert_eq!(cell.get(), Some(&92))
260    /// ```
261    #[unstable(feature = "once_cell_try", issue = "109737")]
262    #[rustc_should_not_be_called_on_const_items]
263    pub fn get_or_try_init<F, E>(&self, f: F) -> Result<&T, E>
264    where
265        F: FnOnce() -> Result<T, E>,
266    {
267        if let Some(val) = self.get() {
268            return Ok(val);
269        }
270        self.try_init(f)
271    }
272
273    /// Gets the mutable reference of the contents of the cell, initializing
274    /// it to `f()` if the cell was uninitialized. If the cell was uninitialized
275    /// and `f()` failed, an error is returned.
276    ///
277    /// # Panics
278    ///
279    /// If `f()` panics, the panic is propagated to the caller, and the cell
280    /// remains uninitialized.
281    ///
282    /// # Examples
283    ///
284    /// ```
285    /// #![feature(once_cell_get_mut)]
286    ///
287    /// use std::cell::OnceCell;
288    ///
289    /// let mut cell: OnceCell<u32> = OnceCell::new();
290    ///
291    /// // Failed attempts to initialize the cell do not change its contents
292    /// assert!(cell.get_mut_or_try_init(|| "not a number!".parse()).is_err());
293    /// assert!(cell.get().is_none());
294    ///
295    /// let value = cell.get_mut_or_try_init(|| "1234".parse());
296    /// assert_eq!(value, Ok(&mut 1234));
297    ///
298    /// let Ok(value) = value else { return; };
299    /// *value += 2;
300    /// assert_eq!(cell.get(), Some(&1236))
301    /// ```
302    #[unstable(feature = "once_cell_get_mut", issue = "121641")]
303    pub fn get_mut_or_try_init<F, E>(&mut self, f: F) -> Result<&mut T, E>
304    where
305        F: FnOnce() -> Result<T, E>,
306    {
307        if self.get().is_none() {
308            self.try_init(f)?;
309        }
310        Ok(self.get_mut().unwrap())
311    }
312
313    // Avoid inlining the initialization closure into the common path that fetches
314    // the already initialized value
315    #[cold]
316    fn try_init<F, E>(&self, f: F) -> Result<&T, E>
317    where
318        F: FnOnce() -> Result<T, E>,
319    {
320        let val = f()?;
321        // Note that *some* forms of reentrant initialization might lead to
322        // UB (see `reentrant_init` test). I believe that just removing this
323        // `panic`, while keeping `try_insert` would be sound, but it seems
324        // better to panic, rather than to silently use an old value.
325        if let Ok(val) = self.try_insert(val) { Ok(val) } else { panic!("reentrant init") }
326    }
327
328    /// Consumes the cell, returning the wrapped value.
329    ///
330    /// Returns `None` if the cell was uninitialized.
331    ///
332    /// # Examples
333    ///
334    /// ```
335    /// use std::cell::OnceCell;
336    ///
337    /// let cell: OnceCell<String> = OnceCell::new();
338    /// assert_eq!(cell.into_inner(), None);
339    ///
340    /// let cell = OnceCell::new();
341    /// let _ = cell.set("hello".to_owned());
342    /// assert_eq!(cell.into_inner(), Some("hello".to_owned()));
343    /// ```
344    #[inline]
345    #[stable(feature = "once_cell", since = "1.70.0")]
346    #[rustc_const_stable(feature = "const_cell_into_inner", since = "1.83.0")]
347    #[rustc_allow_const_fn_unstable(const_precise_live_drops)]
348    pub const fn into_inner(self) -> Option<T> {
349        // Because `into_inner` takes `self` by value, the compiler statically verifies
350        // that it is not currently borrowed. So it is safe to move out `Option<T>`.
351        self.inner.into_inner()
352    }
353
354    /// Takes the value out of this `OnceCell`, moving it back to an uninitialized state.
355    ///
356    /// Has no effect and returns `None` if the `OnceCell` is uninitialized.
357    ///
358    /// Safety is guaranteed by requiring a mutable reference.
359    ///
360    /// # Examples
361    ///
362    /// ```
363    /// use std::cell::OnceCell;
364    ///
365    /// let mut cell: OnceCell<String> = OnceCell::new();
366    /// assert_eq!(cell.take(), None);
367    ///
368    /// let mut cell = OnceCell::new();
369    /// let _ = cell.set("hello".to_owned());
370    /// assert_eq!(cell.take(), Some("hello".to_owned()));
371    /// assert_eq!(cell.get(), None);
372    /// ```
373    #[inline]
374    #[stable(feature = "once_cell", since = "1.70.0")]
375    pub fn take(&mut self) -> Option<T> {
376        mem::take(self).into_inner()
377    }
378}
379
380#[stable(feature = "once_cell", since = "1.70.0")]
381#[rustc_const_unstable(feature = "const_default", issue = "143894")]
382const impl<T> Default for OnceCell<T> {
383    #[inline]
384    fn default() -> Self {
385        Self::new()
386    }
387}
388
389#[stable(feature = "once_cell", since = "1.70.0")]
390impl<T: fmt::Debug> fmt::Debug for OnceCell<T> {
391    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
392        let mut d = f.debug_tuple("OnceCell");
393        match self.get() {
394            Some(v) => d.field(v),
395            None => d.field(&format_args!("<uninit>")),
396        };
397        d.finish()
398    }
399}
400
401#[stable(feature = "once_cell", since = "1.70.0")]
402impl<T: Clone> Clone for OnceCell<T> {
403    #[inline]
404    fn clone(&self) -> OnceCell<T> {
405        match self.get() {
406            Some(value) => OnceCell::from(value.clone()),
407            None => OnceCell::new(),
408        }
409    }
410}
411
412#[stable(feature = "once_cell", since = "1.70.0")]
413impl<T: PartialEq> PartialEq for OnceCell<T> {
414    #[inline]
415    fn eq(&self, other: &Self) -> bool {
416        self.get() == other.get()
417    }
418}
419
420#[stable(feature = "once_cell", since = "1.70.0")]
421impl<T: Eq> Eq for OnceCell<T> {}
422
423#[stable(feature = "once_cell", since = "1.70.0")]
424#[rustc_const_unstable(feature = "const_convert", issue = "143773")]
425const impl<T> From<T> for OnceCell<T> {
426    /// Creates a new `OnceCell<T>` which already contains the given `value`.
427    #[inline]
428    fn from(value: T) -> Self {
429        OnceCell { inner: UnsafeCell::new(Some(value)) }
430    }
431}
432
433// Just like for `Cell<T>` this isn't needed, but results in nicer error messages.
434#[stable(feature = "once_cell", since = "1.70.0")]
435impl<T> !Sync for OnceCell<T> {}