Skip to content

Commit

Permalink
feat: add LazyCell::borrow_mut method
Browse files Browse the repository at this point in the history
  • Loading branch information
matklad authored and indiv0 committed Nov 24, 2017
1 parent 2fb5278 commit fd419de
Showing 1 changed file with 27 additions and 2 deletions.
29 changes: 27 additions & 2 deletions src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -20,8 +20,8 @@
//! variation on `RefCell` which allows borrows to be tied to the lifetime of
//! the outer object.
//!
//! The limitation of a `LazyCell` is that after it is initialized, it can never
//! be modified.
//! The limitation of a `LazyCell` is that after it is initialized and shared,
//! it can be modified.
//!
//! # Example
//!
Expand Down Expand Up @@ -86,6 +86,15 @@ impl<T> LazyCell<T> {
unsafe { &*self.inner.get() }.as_ref()
}

/// Borrows the contents of this lazy cell mutably for the duration of the cell
/// itself.
///
/// This function will return `Some` if the cell has been previously
/// initialized, and `None` if it has not yet been initialized.
pub fn borrow_mut(&mut self) -> Option<&mut T> {
unsafe { &mut *self.inner.get() }.as_mut()
}

/// Borrows the contents of this lazy cell for the duration of the cell
/// itself.
///
Expand Down Expand Up @@ -224,6 +233,22 @@ mod tests {
assert_eq!(value, Some(1));
}

#[test]
fn test_borrow_mut() {
let mut lazycell = LazyCell::new();
assert!(lazycell.borrow_mut().is_none());

lazycell.fill(1).unwrap();
assert_eq!(lazycell.borrow_mut(), Some(&mut 1));

*lazycell.borrow_mut().unwrap() = 2;
assert_eq!(lazycell.borrow_mut(), Some(&mut 2));

// official way to reset the cell
lazycell = LazyCell::new();
assert!(lazycell.borrow_mut().is_none());
}

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

0 comments on commit fd419de

Please sign in to comment.