Skip to content

Commit f65ea0c

Browse files
committed
core: Add extension methods for option
1 parent 392d3c8 commit f65ea0c

File tree

2 files changed

+29
-0
lines changed

2 files changed

+29
-0
lines changed

src/libcore/core.rs

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -7,6 +7,7 @@ import option = option::option;
77
import path = path::path;
88
import vec::vec_len;
99
import str::extensions;
10+
import option::extensions;
1011
export path, option, some, none, vec_len, unreachable;
1112
export extensions;
1213

src/libcore/option.rs

Lines changed: 28 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -87,6 +87,34 @@ fn unwrap<T>(-opt: option<T>) -> T unsafe {
8787
ret liberated_value;
8888
}
8989

90+
impl extensions<T:copy> for option<T> {
91+
#[doc = "
92+
Update an optional value by optionally running its content through a
93+
function that returns an option.
94+
"]
95+
fn chain<U>(f: fn(T) -> option<U>) -> option<U> { chain(self, f) }
96+
#[doc = "Returns the contained value or a default"]
97+
fn from_maybe(def: T) -> T { from_maybe(self, def) }
98+
#[doc = "Applies a function to the contained value or returns a default"]
99+
fn maybe<U: copy>(def: U, f: fn(T) -> U) -> U { maybe(self, def, f) }
100+
#[doc = "Performs an operation on the contained value or does nothing"]
101+
fn may(f: fn(T)) { may(self, f) }
102+
#[doc = "
103+
Gets the value out of an option
104+
105+
# Failure
106+
107+
Fails if the value equals `none`
108+
"]
109+
fn get() -> T { get(self) }
110+
#[doc = "Returns true if the option equals `none`"]
111+
fn is_none() -> bool { is_none(self) }
112+
#[doc = "Returns true if the option contains some value"]
113+
fn is_some() -> bool { is_some(self) }
114+
#[doc = "Maps a `some` value from one type to another"]
115+
fn map<U:copy>(f: fn(T) -> U) -> option<U> { map(self, f) }
116+
}
117+
90118
#[test]
91119
fn test_unwrap_ptr() {
92120
let x = ~0;

0 commit comments

Comments
 (0)