sync: implement From<T> for OnceCell<T> (#3877)

This commit is contained in:
sb64 2021-06-22 07:11:01 -06:00 committed by GitHub
parent 3207479fa7
commit 845626410a
No known key found for this signature in database
GPG Key ID: 4AEE18F83AFDEB23
2 changed files with 19 additions and 7 deletions

View File

@ -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 {
@ -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()
}

View File

@ -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);
}