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.
This commit is contained in:
Tobin C. Harding 2025-06-12 10:57:03 +10:00
parent 9b88d87020
commit c736e73ae0
No known key found for this signature in database
GPG Key ID: 40BF9E4C269D6607
1 changed files with 26 additions and 0 deletions

View File

@ -142,6 +142,32 @@ impl<T: fmt::Debug> NumOpResult<T> {
}
}
/// Returns the contained Some value or a provided default.
///
/// Arguments passed to `unwrap_or` are eagerly evaluated; if you are passing the result of a
/// function call, it is recommended to use `unwrap_or_else`, which is lazily evaluated.
#[inline]
#[track_caller]
pub fn unwrap_or(self, default: T) -> T {
match self {
R::Valid(x) => x,
R::Error(_) => default,
}
}
/// Returns the contained `Some` value or computes it from a closure.
#[inline]
#[track_caller]
pub fn unwrap_or_else<F>(self, f: F) -> T
where
F: FnOnce() -> T,
{
match self {
R::Valid(x) => x,
R::Error(_) => f(),
}
}
/// Converts this `NumOpResult` to an `Option<T>`.
#[inline]
pub fn ok(self) -> Option<T> {