Skip to content

Commit

Permalink
Support format string in try_with
Browse files Browse the repository at this point in the history
  • Loading branch information
WiSaGaN committed Mar 31, 2018
1 parent ba27a3d commit 2e53559
Show file tree
Hide file tree
Showing 2 changed files with 22 additions and 1 deletion.
4 changes: 4 additions & 0 deletions CHANGELOG.md
Expand Up @@ -2,6 +2,10 @@

This project roughly adheres to [Semantic Versioning](http://semver.org/). For 0.x.y releases, `x` is the major version in semver, while `y` is the minor version.

## 0.1.11 - 2018-03-31

* Support format string in `try_with` and `require_with`

## 0.1.10 - 2017-10-15

* Add `as_str`
Expand Down
19 changes: 18 additions & 1 deletion src/lib.rs
Expand Up @@ -151,6 +151,12 @@ pub type SimpleResult<T> = Result<T, SimpleError>;
/// },
/// }
/// }
///
/// // Use a format string
///
/// fn try_block_format(result: Result<(), SimpleError>, s: &str) -> Result<(), SimpleError> {
/// Ok(try_with!(result, "with {}", s))
/// }
/// # }
/// ```
#[macro_export]
Expand All @@ -160,7 +166,13 @@ macro_rules! try_with {
Err(err) => {
return Err(SimpleError::with($str.as_ref(), err));
},
})
});
($expr: expr, $fmt:expr, $($arg:tt)+) => (match $expr {
Ok(val) => val,
Err(err) => {
return Err(SimpleError::with(&format!($fmt, $($arg)+), err));
},
});
}

/// Helper macro for unwrapping `Option` values while returning early with a
Expand Down Expand Up @@ -294,10 +306,15 @@ mod tests {
Ok(try_with!(result, s))
}

fn try_block_format(result: Result<(), SimpleError>, s: &str) -> Result<(), SimpleError> {
Ok(try_with!(result, "with {}", s))
}

#[test]
fn macro_try_with() {
assert_eq!(Ok(()), try_block(Ok(()), ""));
assert_eq!(Err(SimpleError::new("try block error, error foo")), try_block(Err(SimpleError::new("error foo")), "try block error"));
assert_eq!(Err(SimpleError::new("with try block error, error foo")), try_block_format(Err(SimpleError::new("error foo")), "try block error"));
}

fn require_block(option: Option<()>, s: &str) -> Result<(), SimpleError> {
Expand Down

0 comments on commit 2e53559

Please sign in to comment.