-
Notifications
You must be signed in to change notification settings - Fork 17
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Add borrow_with to LazyCell #56
Changes from all commits
File filter
Filter by extension
Conversations
Jump to
Diff view
Diff view
There are no files selected for viewing
Original file line number | Diff line number | Diff line change |
---|---|---|
|
@@ -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() } | ||
|
@@ -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); | ||
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. Could you also test the positive case (i.e. There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. Yes, I'll make a note to write that up. I was also thinking a test to assert that the |
||
} | ||
|
||
#[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(); | ||
|
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
Could you rewrite the function to be: