Skip to content
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

Optional cell enhancements #1056

Merged
merged 7 commits into from Jul 7, 2018
Merged
20 changes: 20 additions & 0 deletions libraries/tock-cells/src/optional_cell.rs
Expand Up @@ -44,6 +44,20 @@ impl<T: Copy> OptionalCell<T> {
self.value.set(None);
}

/// Replace the contents with the value from the supplied `Option`,
/// or empty this `OptionalCell` if the supplied `Option` is `None`.
pub fn replace(&self, option: Option<T>) {
match option {
Some(v) => self.set(v),
None => self.clear(),
}
}

/// Returns the contained value, or panics if contents is `None`.
pub fn expect(&self, msg: &str) -> T {
self.value.get().expect(msg)
}

/// Return the contained value and replace it with None.
pub fn take(&self) -> Option<T> {
self.value.take()
Expand Down Expand Up @@ -80,4 +94,10 @@ impl<T: Copy> OptionalCell<T> {
.get()
.map_or_else(default, |mut val| closure(&mut val))
}

/// If the cell is empty, return `None`. Otherwise, call a closure
/// with the value of the cell and return the result.
pub fn and_then<U, F: FnOnce(T) -> Option<U>>(&self, f: F) -> Option<U> {
self.value.get().and_then(f)
}
}