From f65ea0c8123d02c61f3a15188470711d49fa2b6d Mon Sep 17 00:00:00 2001 From: Brian Anderson Date: Fri, 16 Mar 2012 17:49:58 -0700 Subject: [PATCH] core: Add extension methods for option --- src/libcore/core.rs | 1 + src/libcore/option.rs | 28 ++++++++++++++++++++++++++++ 2 files changed, 29 insertions(+) diff --git a/src/libcore/core.rs b/src/libcore/core.rs index 98c81d6d38f..cf06ad1b158 100644 --- a/src/libcore/core.rs +++ b/src/libcore/core.rs @@ -7,6 +7,7 @@ import path = path::path; import vec::vec_len; import str::extensions; +import option::extensions; export path, option, some, none, vec_len, unreachable; export extensions; diff --git a/src/libcore/option.rs b/src/libcore/option.rs index 748683121d5..d89593f14c4 100644 --- a/src/libcore/option.rs +++ b/src/libcore/option.rs @@ -87,6 +87,34 @@ fn unwrap(-opt: option) -> T unsafe { ret liberated_value; } +impl extensions for option { + #[doc = " + Update an optional value by optionally running its content through a + function that returns an option. + "] + fn chain(f: fn(T) -> option) -> option { chain(self, f) } + #[doc = "Returns the contained value or a default"] + fn from_maybe(def: T) -> T { from_maybe(self, def) } + #[doc = "Applies a function to the contained value or returns a default"] + fn maybe(def: U, f: fn(T) -> U) -> U { maybe(self, def, f) } + #[doc = "Performs an operation on the contained value or does nothing"] + fn may(f: fn(T)) { may(self, f) } + #[doc = " + Gets the value out of an option + + # Failure + + Fails if the value equals `none` + "] + fn get() -> T { get(self) } + #[doc = "Returns true if the option equals `none`"] + fn is_none() -> bool { is_none(self) } + #[doc = "Returns true if the option contains some value"] + fn is_some() -> bool { is_some(self) } + #[doc = "Maps a `some` value from one type to another"] + fn map(f: fn(T) -> U) -> option { map(self, f) } +} + #[test] fn test_unwrap_ptr() { let x = ~0; -- GitLab