Skip to content

Commit

Permalink
feat: add borrow_with to LazyCell
Browse files Browse the repository at this point in the history
Add a `borrow_with(|| foo)` convenience method to `LazyCell` so that
users may provide a function to automatically fill the cell in the event
that it is empty on attempting to borrow.
  • Loading branch information
archer884 committed Dec 7, 2016
1 parent ed58634 commit a15efa3
Show file tree
Hide file tree
Showing 2 changed files with 42 additions and 0 deletions.
1 change: 1 addition & 0 deletions CONTRIBUTORS.md
Original file line number Diff line number Diff line change
Expand Up @@ -3,5 +3,6 @@ alphabetical order.

* [Carl Lerche](https://github.com/carllerche)
* [Nikita Pekin](https://github.com/indiv0)
* [J/A](https://github.com/archer884)

[lazycell]: https://github.com/indiv0/lazycell
41 changes: 41 additions & 0 deletions src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -85,6 +85,20 @@ 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 cell has not yet been filled, 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() {
*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 +200,33 @@ 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_borrow_with_already_filled() {
let lazycell = LazyCell::new();
lazycell.fill(1).unwrap();

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

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

lazycell.fill(1).unwrap();

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

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

0 comments on commit a15efa3

Please sign in to comment.