Skip to content

Commit

Permalink
sync: implement From<T> for OnceCell<T> (#3877)
Browse files Browse the repository at this point in the history
  • Loading branch information
sb64 committed Jun 22, 2021
1 parent 3207479 commit 8456264
Show file tree
Hide file tree
Showing 2 changed files with 19 additions and 7 deletions.
20 changes: 13 additions & 7 deletions tokio/src/sync/once_cell.rs
Expand Up @@ -77,6 +77,18 @@ impl<T> Drop for OnceCell<T> {
}
}

impl<T> From<T> for OnceCell<T> {
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<T> OnceCell<T> {
/// Creates a new uninitialized OnceCell instance.
pub fn new() -> Self {
Expand All @@ -93,13 +105,7 @@ impl<T> OnceCell<T> {
/// [`OnceCell::new`]: crate::sync::OnceCell::new
pub fn new_with(value: Option<T>) -> 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()
}
Expand Down
6 changes: 6 additions & 0 deletions tokio/tests/sync_once_cell.rs
Expand Up @@ -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);
}

0 comments on commit 8456264

Please sign in to comment.