use std::mem; use std::sync::atomic::{AtomicU32, Ordering}; use std::sync::Arc; use std::time::Duration; use tokio::runtime; use tokio::sync::OnceCell; use tokio::sync::SetError; use tokio::time;
struct Foo {
value: Arc<AtomicU32>,
}
impl Drop for Foo { fn drop(&mutself) { self.value.fetch_add(1, Ordering::Release);
}
}
impl From<Arc<AtomicU32>> for Foo { fn from(value: Arc<AtomicU32>) -> Self {
Foo { value }
}
}
#[test] fn drop_cell() { let num_drops = Arc::new(AtomicU32::new(0));
{ let once_cell = OnceCell::new(); let prev = once_cell.set(Foo::from(num_drops.clone()));
assert!(prev.is_ok())
}
assert!(num_drops.load(Ordering::Acquire) == 1);
}
#[test] fn drop_cell_new_with() { let num_drops = Arc::new(AtomicU32::new(0));
{ let once_cell = OnceCell::new_with(Some(Foo::from(num_drops.clone())));
assert!(once_cell.initialized());
}
assert!(num_drops.load(Ordering::Acquire) == 1);
}
#[test] fn drop_into_inner() { let num_drops = Arc::new(AtomicU32::new(0));
let once_cell = OnceCell::new();
assert!(once_cell.set(Foo::from(num_drops.clone())).is_ok()); let fooer = once_cell.into_inner(); let count = num_drops.load(Ordering::Acquire);
assert!(count == 0);
drop(fooer); let count = num_drops.load(Ordering::Acquire);
assert!(count == 1);
}
#[test] fn drop_into_inner_new_with() { let num_drops = Arc::new(AtomicU32::new(0)); let fooer = Foo::from(num_drops.clone());
let once_cell = OnceCell::new_with(Some(fooer)); let fooer = once_cell.into_inner(); let count = num_drops.load(Ordering::Acquire);
assert!(count == 0);
mem::drop(fooer); let count = num_drops.load(Ordering::Acquire);
assert!(count == 1);
}
asyncfn sleep_and_set() -> u32 { // Simulate sleep by pausing time and waiting for another thread to // resume clock when calling `set`, then finding the cell being initialized // by this call
time::sleep(Duration::from_millis(2)).await; 5
}
Die Informationen auf dieser Webseite wurden
nach bestem Wissen sorgfältig zusammengestellt. Es wird jedoch weder Vollständigkeit, noch Richtigkeit,
noch Qualität der bereit gestellten Informationen zugesichert.
Bemerkung:
Die farbliche Syntaxdarstellung und die Messung sind noch experimentell.