From c736e73ae020f80a29bf6dce7d6b7741df42e679 Mon Sep 17 00:00:00 2001 From: "Tobin C. Harding" Date: Thu, 12 Jun 2025 10:57:03 +1000 Subject: [PATCH] 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. --- units/src/result.rs | 26 ++++++++++++++++++++++++++ 1 file changed, 26 insertions(+) diff --git a/units/src/result.rs b/units/src/result.rs index c64ab5cbe..a6619ac68 100644 --- a/units/src/result.rs +++ b/units/src/result.rs @@ -142,6 +142,32 @@ impl NumOpResult { } } + /// 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(self, f: F) -> T + where + F: FnOnce() -> T, + { + match self { + R::Valid(x) => x, + R::Error(_) => f(), + } + } + /// Converts this `NumOpResult` to an `Option`. #[inline] pub fn ok(self) -> Option {