Skip to content

Commit

Permalink
Implement force_mut and get_mut for unsync::Lazy
Browse files Browse the repository at this point in the history
  • Loading branch information
danielSanchezQ committed Sep 1, 2022
1 parent 932c3ec commit c35d46d
Showing 1 changed file with 36 additions and 0 deletions.
36 changes: 36 additions & 0 deletions src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -742,6 +742,25 @@ pub mod unsync {
})
}

/// Forces the evaluation of this lazy value and returns a mutable reference to
/// the result.
///
/// This is equivalent to the `DerefMut` impl, but is explicit.
///
/// # Example
/// ```
/// use once_cell::unsync::Lazy;
///
/// let mut lazy = Lazy::new(|| 92);
///
/// assert_eq!(Lazy::force_mut(&mut lazy), &92);
/// assert_eq!(*lazy, 92);
/// ```
pub fn force_mut(this: &mut Lazy<T, F>) -> &mut T {
Self::force(this);
this.cell.get_mut().unwrap_or_else(|| unreachable!())
}

/// Gets the reference to the result of this lazy value if
/// it was initialized, otherwise returns `None`.
///
Expand All @@ -758,6 +777,23 @@ pub mod unsync {
pub fn get(this: &Lazy<T, F>) -> Option<&T> {
this.cell.get()
}

/// Gets the mutable reference to the result of this lazy value if
/// it was initialized, otherwise returns `None`.
///
/// # Example
/// ```
/// use once_cell::unsync::Lazy;
///
/// let mut lazy = Lazy::new(|| 92);
///
/// assert_eq!(Lazy::get_mut(&mut lazy), None);
/// assert_eq!(*lazy, 92);
/// assert_eq!(Lazy::get_mut(&mut lazy), Some(&mut 92));
/// ```
pub fn get_mut(this: &mut Lazy<T, F>) -> Option<&mut T> {
this.cell.get_mut()
}
}

impl<T, F: FnOnce() -> T> Deref for Lazy<T, F> {
Expand Down

0 comments on commit c35d46d

Please sign in to comment.