Skip to content

Commit

Permalink
Merge pull request #100 from sunshowers/reset
Browse files Browse the repository at this point in the history
add a `take` method which takes a mutable reference
  • Loading branch information
matklad authored May 13, 2020
2 parents 4f974ef + 4d8cbfd commit 8a322d0
Showing 1 changed file with 48 additions and 2 deletions.
50 changes: 48 additions & 2 deletions src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -246,7 +246,7 @@ mod imp;
pub mod unsync {
use core::{
cell::{Cell, UnsafeCell},
fmt,
fmt, mem,
ops::{Deref, DerefMut},
};

Expand Down Expand Up @@ -455,6 +455,29 @@ pub mod unsync {
Ok(self.get().unwrap())
}

/// Takes the value out of this `OnceCell`, moving it back to an uninitialized state.
///
/// Has no effect and returns `None` if the `OnceCell` hasn't been initialized.
///
/// Safety is guaranteed by requiring a mutable reference.
///
/// # Examples
///
/// ```
/// use once_cell::unsync::OnceCell;
///
/// let mut cell: OnceCell<String> = OnceCell::new();
/// assert_eq!(cell.take(), None);
///
/// let mut cell = OnceCell::new();
/// cell.set("hello".to_string()).unwrap();
/// assert_eq!(cell.take(), Some("hello".to_string()));
/// assert_eq!(cell.get(), None);
/// ```
pub fn take(&mut self) -> Option<T> {
mem::take(self).into_inner()
}

/// Consumes the `OnceCell`, returning the wrapped value.
///
/// Returns `None` if the cell was empty.
Expand Down Expand Up @@ -581,7 +604,7 @@ pub mod unsync {
pub mod sync {
use std::{
cell::Cell,
fmt,
fmt, mem,
ops::{Deref, DerefMut},
panic::RefUnwindSafe,
};
Expand Down Expand Up @@ -809,6 +832,29 @@ pub mod sync {
Ok(unsafe { self.get_unchecked() })
}

/// Takes the value out of this `OnceCell`, moving it back to an uninitialized state.
///
/// Has no effect and returns `None` if the `OnceCell` hasn't been initialized.
///
/// Safety is guaranteed by requiring a mutable reference.
///
/// # Examples
///
/// ```
/// use once_cell::sync::OnceCell;
///
/// let mut cell: OnceCell<String> = OnceCell::new();
/// assert_eq!(cell.take(), None);
///
/// let mut cell = OnceCell::new();
/// cell.set("hello".to_string()).unwrap();
/// assert_eq!(cell.take(), Some("hello".to_string()));
/// assert_eq!(cell.get(), None);
/// ```
pub fn take(&mut self) -> Option<T> {
mem::take(self).into_inner()
}

/// Consumes the `OnceCell`, returning the wrapped value. Returns
/// `None` if the cell was empty.
///
Expand Down

0 comments on commit 8a322d0

Please sign in to comment.