Skip to content

Commit c736e73

Browse files
committed
Add unwrap_or and unwrap_or_else to NumOpResult
Two useful combinators, add them. I copied the function signature and docs from stdlib and wrote the functions myself - thereby operating within licensing requirements.
1 parent 9b88d87 commit c736e73

File tree

1 file changed

+26
-0
lines changed

1 file changed

+26
-0
lines changed

units/src/result.rs

Lines changed: 26 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -142,6 +142,32 @@ impl<T: fmt::Debug> NumOpResult<T> {
142142
}
143143
}
144144

145+
/// Returns the contained Some value or a provided default.
146+
///
147+
/// Arguments passed to `unwrap_or` are eagerly evaluated; if you are passing the result of a
148+
/// function call, it is recommended to use `unwrap_or_else`, which is lazily evaluated.
149+
#[inline]
150+
#[track_caller]
151+
pub fn unwrap_or(self, default: T) -> T {
152+
match self {
153+
R::Valid(x) => x,
154+
R::Error(_) => default,
155+
}
156+
}
157+
158+
/// Returns the contained `Some` value or computes it from a closure.
159+
#[inline]
160+
#[track_caller]
161+
pub fn unwrap_or_else<F>(self, f: F) -> T
162+
where
163+
F: FnOnce() -> T,
164+
{
165+
match self {
166+
R::Valid(x) => x,
167+
R::Error(_) => f(),
168+
}
169+
}
170+
145171
/// Converts this `NumOpResult` to an `Option<T>`.
146172
#[inline]
147173
pub fn ok(self) -> Option<T> {

0 commit comments

Comments
 (0)