Skip to content

Perform Ok-wrapping in try_block macro #1

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

Open
wants to merge 3 commits into
base: master
Choose a base branch
from
Open
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
2 changes: 1 addition & 1 deletion examples/simple/src/main.rs
Original file line number Diff line number Diff line change
Expand Up @@ -14,7 +14,7 @@ fn main() {
let result: Result<_, ()> = try_block! {
let a = do_one(x)?;
let b = do_two(a)?;
Ok(b)
b
};

println!("{:?}", result);
Expand Down
58 changes: 50 additions & 8 deletions src/lib.rs
Original file line number Diff line number Diff line change
@@ -1,7 +1,23 @@
/// Macro for ok-wrapping any `Try` type. This works on stable through dark type magic.
///
/// Note that type inference is very finicky; you should give this a type ascription ASAP.
/// ```
/// # use try_block::wrap_ok;
/// let r: Result<_, ()> = wrap_ok!(1);
/// assert_eq!(r, Ok(1));
/// ```
#[macro_export]
macro_rules! wrap_ok {
($e:expr) => {{
::std::iter::empty().try_fold($e, |_, x: std::convert::Infallible| match x {})
}};
}

/// Macro to make your error-handling blocks (appear) lambda-less
/// and perform Ok-wrapping on the final value.
///
/// #### Before:
/// ```
/// ```ignore
/// let result: Result<T, E> = || {
/// let a = do_one(x)?;
/// let b = do_two(a)?;
Expand All @@ -10,21 +26,47 @@
/// ```
///
/// #### After:
/// ```
/// ```
/// # use try_block::try_block;
/// # type T = (); type E = ();
/// # fn do_one((): T) -> Result<T, E> { Ok(()) }
/// # fn do_two((): T) -> Result<T, E> { Ok(()) }
/// # let x = ();
/// let result: Result<T, E> = try_block! {
/// let a = do_one(x)?;
/// let b = do_two(a)?;
/// Ok(b)
/// b
/// };
/// ```

#[macro_export]
macro_rules! try_block {
{ $($token:tt)* } => {{
let l = || {
$($token)*
};
l()
( || $crate::wrap_ok!(
{ $($token)* }
))()
}}
}

#[cfg(test)]
mod tests {
#[test]
fn parse_sum() {
let result: Result<_, std::num::ParseIntError> = try_block! {
let x = "1".parse::<i32>()?;
let x = "2".parse::<i32>()? + x * 10;
let x = "3".parse::<i32>()? + x * 10;
x
};
assert_eq!(result, Ok(123));
}

#[test]
fn option() {
assert_eq!(
Some(520),
try_block! {
"400".parse::<i32>().ok()? + "20".parse::<i32>().ok()? * "6".parse::<i32>().ok()?
},
);
}
}