From 8e71c21af0555018e18d7bd04877f0830cb15d4b Mon Sep 17 00:00:00 2001 From: Tim Chevalier Date: Thu, 3 Jan 2013 15:36:23 -0800 Subject: [PATCH] Add option::get_zero as per #3797 --- src/libcore/option.rs | 20 ++++++++++++++++++++ 1 file changed, 20 insertions(+) diff --git a/src/libcore/option.rs b/src/libcore/option.rs index e7c82cb8f6621..5b5b3b271fff0 100644 --- a/src/libcore/option.rs +++ b/src/libcore/option.rs @@ -49,6 +49,7 @@ use option; use ptr; use str; use util; +use num::Zero; /// The option type #[deriving_eq] @@ -170,6 +171,12 @@ pub pure fn is_some(opt: &Option) -> bool { !is_none(opt) } +pub pure fn get_zero(opt: Option) -> T { + //! Returns the contained value or zero (for this type) + + match opt { Some(copy x) => x, None => Zero::zero() } +} + pub pure fn get_default(opt: Option, def: T) -> T { //! Returns the contained value or a default @@ -333,6 +340,11 @@ impl Option { } } +impl Option { + #[inline(always)] + pure fn get_zero(self) -> T { get_zero(self) } +} + #[test] fn test_unwrap_ptr() { let x = ~0; @@ -407,6 +419,14 @@ fn test_option_while_some() { assert i == 11; } +#[test] +fn test_get_zero() { + let some_stuff = Some(42); + assert some_stuff.get_zero() == 42; + let no_stuff: Option = None; + assert no_stuff.get_zero() == 0; +} + // Local Variables: // mode: rust; // fill-column: 78;