diff --git a/tokio/src/sync/once_cell.rs b/tokio/src/sync/once_cell.rs index fa9b1f19f..8c9a4f625 100644 --- a/tokio/src/sync/once_cell.rs +++ b/tokio/src/sync/once_cell.rs @@ -77,6 +77,18 @@ impl Drop for OnceCell { } } +impl From for OnceCell { + fn from(value: T) -> Self { + let semaphore = Semaphore::new(0); + semaphore.close(); + OnceCell { + value_set: AtomicBool::new(true), + value: UnsafeCell::new(MaybeUninit::new(value)), + semaphore, + } + } +} + impl OnceCell { /// Creates a new uninitialized OnceCell instance. pub fn new() -> Self { @@ -93,13 +105,7 @@ impl OnceCell { /// [`OnceCell::new`]: crate::sync::OnceCell::new pub fn new_with(value: Option) -> Self { if let Some(v) = value { - let semaphore = Semaphore::new(0); - semaphore.close(); - OnceCell { - value_set: AtomicBool::new(true), - value: UnsafeCell::new(MaybeUninit::new(v)), - semaphore, - } + OnceCell::from(v) } else { OnceCell::new() } diff --git a/tokio/tests/sync_once_cell.rs b/tokio/tests/sync_once_cell.rs index 60f50d214..18eaf9382 100644 --- a/tokio/tests/sync_once_cell.rs +++ b/tokio/tests/sync_once_cell.rs @@ -266,3 +266,9 @@ fn drop_into_inner_new_with() { let count = NUM_DROPS.load(Ordering::Acquire); assert!(count == 1); } + +#[test] +fn from() { + let cell = OnceCell::from(2); + assert_eq!(*cell.get().unwrap(), 2); +}