Skip to content

Commit

Permalink
add destructor
Browse files Browse the repository at this point in the history
  • Loading branch information
b-naber committed Mar 26, 2021
1 parent 1f8753a commit 7b1be1a
Show file tree
Hide file tree
Showing 2 changed files with 15 additions and 1 deletion.
14 changes: 14 additions & 0 deletions tokio/src/sync/once_cell.rs
Original file line number Diff line number Diff line change
Expand Up @@ -4,6 +4,7 @@ use std::error::Error;
use std::fmt;
use std::future::Future;
use std::mem::MaybeUninit;
use std::ops::Drop;
use std::ptr;
use std::sync::atomic::{AtomicBool, Ordering};

Expand Down Expand Up @@ -67,6 +68,17 @@ impl<T: PartialEq> PartialEq for OnceCell<T> {

impl<T: Eq> Eq for OnceCell<T> {}

impl<T> Drop for OnceCell<T> {
fn drop(&mut self) {
if self.initialized() {
unsafe {
self.value
.with_mut(|ptr| ptr::drop_in_place((&mut *ptr).as_mut_ptr()));
};
}
}
}

impl<T> OnceCell<T> {
/// Creates a new uninitialized OnceCell instance.
pub fn new() -> Self {
Expand Down Expand Up @@ -253,6 +265,8 @@ impl<T> OnceCell<T> {
/// Returns `None` if the cell is uninitialized.
pub fn into_inner(self) -> Option<T> {
if self.initialized() {
// Set to uninitialized for the destructor of `OnceCell` to work properly
self.value_set.store(false, Ordering::Release);
Some(unsafe { self.value.with(|ptr| ptr::read(ptr).assume_init()) })
} else {
None
Expand Down
2 changes: 1 addition & 1 deletion tokio/tests/sync_once_cell.rs
Original file line number Diff line number Diff line change
Expand Up @@ -181,7 +181,7 @@ fn drop_into_inner() {

let once_cell = OnceCell::new();
let _ = once_cell.set(fooer);
let v = once_cell.into_inner();
let _v = once_cell.into_inner();
let count = NUM_DROPS.load(Ordering::Acquire);
assert!(count == 0);
}

0 comments on commit 7b1be1a

Please sign in to comment.