Skip to content

option::unwrap #1872

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Closed
wants to merge 2 commits into from
Closed
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
50 changes: 49 additions & 1 deletion src/libcore/option.rs
Original file line number Diff line number Diff line change
Expand Up @@ -84,8 +84,56 @@ fn may<T>(opt: t<T>, f: fn(T)) {
alt opt { none {/* nothing */ } some(t) { f(t); } }
}

/*
Function: unwrap

Moves a value out of an option type and returns it. Useful primarily
for getting strings, vectors and unique pointers out of option types
without copying them.
*/
fn unwrap<T>(-opt: t<T>) -> T unsafe {
let addr = alt opt {
some(x) { ptr::addr_of(x) }
none { fail "option none" }
};
let liberated_value = unsafe::reinterpret_cast(*addr);
unsafe::leak(opt);
ret liberated_value;
}

#[test]
fn test_unwrap_ptr() {
let x = ~0;
let addr_x = ptr::addr_of(*x);
let opt = some(x);
let y = unwrap(opt);
let addr_y = ptr::addr_of(*y);
assert addr_x == addr_y;
}

#[test]
fn test_unwrap_str() {
let x = "test";
let addr_x = str::as_buf(x) {|buf| ptr::addr_of(buf) };
let opt = some(x);
let y = unwrap(opt);
let addr_y = str::as_buf(y) {|buf| ptr::addr_of(buf) };
assert addr_x == addr_y;
}

#[test]
fn test() { let _x = some::<int>(10); }
fn test_unwrap_resource() {
resource r(b: @mutable bool) {
*b = true;
}
let b = @mutable false;
{
let x = r(b);
let opt = some(x);
let y = unwrap(opt);
}
assert *b == true;
}

// Local Variables:
// mode: rust;
Expand Down