Skip to content

std: Add impl of FnOnce to AssertRecoverSafe #32102

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

Merged
merged 1 commit into from
Mar 11, 2016
Merged
Show file tree
Hide file tree
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
1 change: 1 addition & 0 deletions src/libstd/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -230,6 +230,7 @@
#![feature(float_extras)]
#![feature(float_from_str_radix)]
#![feature(fnbox)]
#![feature(fn_traits)]
#![feature(heap_api)]
#![feature(hashmap_hasher)]
#![feature(inclusive_range)]
Expand Down
36 changes: 35 additions & 1 deletion src/libstd/panic.rs
Original file line number Diff line number Diff line change
Expand Up @@ -129,6 +129,9 @@ pub trait RefRecoverSafe {}
///
/// # Examples
///
/// One way to use `AssertRecoverSafe` is to assert that the entire closure
/// itself is recover safe, bypassing all checks for all variables:
///
/// ```
/// #![feature(recover, std_panic)]
///
Expand All @@ -144,10 +147,33 @@ pub trait RefRecoverSafe {}
/// // });
///
/// // This, however, will compile due to the `AssertRecoverSafe` wrapper
/// let result = panic::recover(AssertRecoverSafe::new(|| {
/// variable += 3;
/// }));
/// // ...
/// ```
///
/// Wrapping the entire closure amounts to a blanket assertion that all captured
/// variables are recover safe. This has the downside that if new captures are
/// added in the future, they will also be considered recover safe. Therefore,
/// you may prefer to just wrap individual captures, as shown below. This is
/// more annotation, but it ensures that if a new capture is added which is not
/// recover safe, you will get a compilation error at that time, which will
/// allow you to consider whether that new capture in fact represent a bug or
/// not.
///
/// ```
/// #![feature(recover, std_panic)]
///
/// use std::panic::{self, AssertRecoverSafe};
///
/// let mut variable = 4;
/// let other_capture = 3;
///
/// let result = {
/// let mut wrapper = AssertRecoverSafe::new(&mut variable);
/// panic::recover(move || {
/// **wrapper += 3;
/// **wrapper += other_capture;
/// })
/// };
/// // ...
Expand Down Expand Up @@ -215,6 +241,14 @@ impl<T> DerefMut for AssertRecoverSafe<T> {
}
}

impl<R, F: FnOnce() -> R> FnOnce<()> for AssertRecoverSafe<F> {
type Output = R;

extern "rust-call" fn call_once(self, _args: ()) -> R {
(self.0)()
}
}

/// Invokes a closure, capturing the cause of panic if one occurs.
///
/// This function will return `Ok` with the closure's result if the closure
Expand Down