summaryrefslogtreecommitdiffstats
path: root/library/std/src/sync/lazy_lock.rs
diff options
context:
space:
mode:
Diffstat (limited to 'library/std/src/sync/lazy_lock.rs')
-rw-r--r--library/std/src/sync/lazy_lock.rs37
1 files changed, 34 insertions, 3 deletions
diff --git a/library/std/src/sync/lazy_lock.rs b/library/std/src/sync/lazy_lock.rs
index a6bc468b0..3598598cf 100644
--- a/library/std/src/sync/lazy_lock.rs
+++ b/library/std/src/sync/lazy_lock.rs
@@ -25,6 +25,8 @@ union Data<T, F> {
///
/// # Examples
///
+/// Initialize static variables with `LazyLock`.
+///
/// ```
/// #![feature(lazy_cell)]
///
@@ -54,6 +56,24 @@ union Data<T, F> {
/// // Some("Hoyten")
/// }
/// ```
+/// Initialize fields with `LazyLock`.
+/// ```
+/// #![feature(lazy_cell)]
+///
+/// use std::sync::LazyLock;
+///
+/// #[derive(Debug)]
+/// struct UseCellLock {
+/// number: LazyLock<u32>,
+/// }
+/// fn main() {
+/// let lock: LazyLock<u32> = LazyLock::new(|| 0u32);
+///
+/// let data = UseCellLock { number: lock };
+/// println!("{}", *data.number);
+/// }
+/// ```
+
#[unstable(feature = "lazy_cell", issue = "109736")]
pub struct LazyLock<T, F = fn() -> T> {
once: Once,
@@ -69,6 +89,15 @@ impl<T, F: FnOnce() -> T> LazyLock<T, F> {
LazyLock { once: Once::new(), data: UnsafeCell::new(Data { f: ManuallyDrop::new(f) }) }
}
+ /// Creates a new lazy value that is already initialized.
+ #[inline]
+ #[cfg(test)]
+ pub(crate) fn preinit(value: T) -> LazyLock<T, F> {
+ let once = Once::new();
+ once.call_once(|| {});
+ LazyLock { once, data: UnsafeCell::new(Data { value: ManuallyDrop::new(value) }) }
+ }
+
/// Consumes this `LazyLock` returning the stored value.
///
/// Returns `Ok(value)` if `Lazy` is initialized and `Err(f)` otherwise.
@@ -193,10 +222,12 @@ impl<T: Default> Default for LazyLock<T> {
#[unstable(feature = "lazy_cell", issue = "109736")]
impl<T: fmt::Debug, F> fmt::Debug for LazyLock<T, F> {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
+ let mut d = f.debug_tuple("LazyLock");
match self.get() {
- Some(v) => f.debug_tuple("LazyLock").field(v).finish(),
- None => f.write_str("LazyLock(Uninit)"),
- }
+ Some(v) => d.field(v),
+ None => d.field(&format_args!("<uninit>")),
+ };
+ d.finish()
}
}