Skip to content

Commit 910a32c

Browse files
committed
core: Add option::unwrap
This function uses some unsafe code to move the value out of an option.
1 parent 9d20ed7 commit 910a32c

File tree

1 file changed

+51
-0
lines changed

1 file changed

+51
-0
lines changed

src/libcore/option.rs

Lines changed: 51 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -84,6 +84,57 @@ fn may<T>(opt: t<T>, f: fn(T)) {
8484
alt opt { none {/* nothing */ } some(t) { f(t); } }
8585
}
8686

87+
/*
88+
Function: unwrap
89+
90+
Moves a value out of an option type and returns it. Useful primarily
91+
for getting strings, vectors and unique pointers out of option types
92+
without copying them.
93+
*/
94+
fn unwrap<T>(-opt: t<T>) -> T unsafe {
95+
let addr = alt opt {
96+
some(x) { ptr::addr_of(x) }
97+
none { fail "option none" }
98+
};
99+
let liberated_value = unsafe::reinterpret_cast(*addr);
100+
unsafe::leak(opt);
101+
ret liberated_value;
102+
}
103+
104+
#[test]
105+
fn test_unwrap_ptr() {
106+
let x = ~0;
107+
let addr_x = ptr::addr_of(*x);
108+
let opt = some(x);
109+
let y = unwrap(opt);
110+
let addr_y = ptr::addr_of(*y);
111+
assert addr_x == addr_y;
112+
}
113+
114+
#[test]
115+
fn test_unwrap_str() {
116+
let x = "test";
117+
let addr_x = str::as_buf(x) {|buf| ptr::addr_of(buf) };
118+
let opt = some(x);
119+
let y = unwrap(opt);
120+
let addr_y = str::as_buf(y) {|buf| ptr::addr_of(buf) };
121+
assert addr_x == addr_y;
122+
}
123+
124+
#[test]
125+
fn test_unwrap_resource() {
126+
resource r(i: @mutable int) {
127+
*i += 1;
128+
}
129+
let i = @mutable 0;
130+
{
131+
let x = r(i);
132+
let opt = some(x);
133+
let y = unwrap(opt);
134+
}
135+
assert *i == 1;
136+
}
137+
87138
// Local Variables:
88139
// mode: rust;
89140
// fill-column: 78;

0 commit comments

Comments
 (0)