Skip to content

Commit

Permalink
Add borrow_with to LazyCell
Browse files Browse the repository at this point in the history
  • Loading branch information
archer884 committed Dec 7, 2016
1 parent ed58634 commit 5a34cdc
Showing 1 changed file with 23 additions and 0 deletions.
23 changes: 23 additions & 0 deletions src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -85,6 +85,21 @@ impl<T> LazyCell<T> {
unsafe { &*self.inner.get() }.as_ref()
}

/// Borrows the contents of this lazy cell for the duration of the cell
/// itself
///
/// If the underlying value of the cell has not yet been realized, the
/// cell is first filled using the function provided.
pub fn borrow_with<F: FnOnce() -> T>(&self, f: F) -> &T {
let mut slot = unsafe {&mut *self.inner.get() };
if slot.is_some() {
return slot.as_ref().unwrap()
}

*slot = Some(f());
slot.as_ref().unwrap()
}

/// Consumes this `LazyCell`, returning the underlying value.
pub fn into_inner(self) -> Option<T> {
unsafe { self.inner.into_inner() }
Expand Down Expand Up @@ -186,6 +201,14 @@ mod tests {
assert_eq!(lazycell.fill(1), Err(1));
}

#[test]
fn test_borrow_with() {
let lazycell = LazyCell::new();

let value = lazycell.borrow_with(|| 1);
assert_eq!(&1, value);
}

#[test]
fn test_into_inner() {
let lazycell = LazyCell::new();
Expand Down

0 comments on commit 5a34cdc

Please sign in to comment.