From 845626410a2e42902882f9750a9f8e2b38cf5a36 Mon Sep 17 00:00:00 2001 From: sb64 <53383020+sb64@users.noreply.github.com> Date: Tue, 22 Jun 2021 07:11:01 -0600 Subject: [PATCH] sync: implement From for OnceCell (#3877) --- tokio/src/sync/once_cell.rs | 20 +++++++++++++------- tokio/tests/sync_once_cell.rs | 6 ++++++ 2 files changed, 19 insertions(+), 7 deletions(-) diff --git a/tokio/src/sync/once_cell.rs b/tokio/src/sync/once_cell.rs index fa9b1f19f54..8c9a4f62529 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 60f50d214e1..18eaf9382bd 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); +}