Skip to content

Commit

Permalink
cells: add more common functions to OptionalCell
Browse files Browse the repository at this point in the history
  • Loading branch information
bradjc committed Jun 26, 2018
1 parent 37678b8 commit 3c08db3
Showing 1 changed file with 24 additions and 0 deletions.
24 changes: 24 additions & 0 deletions libraries/tock-cells/src/optional_cell.rs
Expand Up @@ -24,6 +24,16 @@ impl<T: Copy> OptionalCell<T> {
}
}

/// Check if the cell is None.
pub fn is_none(&self) -> bool {
self.value.get().is_none()
}

/// Check if the cell contains something.
pub fn is_some(&self) -> bool {
self.value.get().is_some()
}

/// Update the stored value.
pub fn set(&self, val: T) {
self.value.set(Some(val));
Expand All @@ -34,11 +44,25 @@ impl<T: Copy> OptionalCell<T> {
self.value.set(None);
}

/// Return the contained value and replace it with None.
pub fn take(&self) -> Option<T> {
self.value.take()
}

/// Call a closure on the value if the value exists.
pub fn map<F, R>(&self, closure: F) -> Option<R>
where
F: FnOnce(&mut T) -> R,
{
self.value.get().map(|mut val| closure(&mut val))
}

/// Call a closure on the value if the value exists, or return value
/// instead.
pub fn map_or<F, R>(&self, value: R, closure: F) -> R
where
F: FnOnce(&mut T) -> R,
{
self.value.get().map_or(value, |mut val| closure(&mut val))
}
}

0 comments on commit 3c08db3

Please sign in to comment.