Skip to content

Commit b7c487c

Browse files
committed
Add ensure_eq!
Addresses the last of @dignifiedquire's comments; this should be enough to pass the review!
1 parent b08b763 commit b7c487c

File tree

2 files changed

+40
-1
lines changed

2 files changed

+40
-1
lines changed

src/macros.rs

Lines changed: 26 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -38,6 +38,32 @@ macro_rules! ensure {
3838
};
3939
}
4040

41+
/// Return early with an error if a condition is not satisfied.
42+
///
43+
/// This macro is equivalent to `if !$cond { return Err(From::from($err)); }`.
44+
///
45+
/// Analogously to `assert!`, `ensure!` takes a condition and exits the function
46+
/// if the condition fails. Unlike `assert!`, `ensure!` returns an `Error`
47+
/// rather than panicking.
48+
#[macro_export]
49+
macro_rules! ensure_eq {
50+
($left:expr, $right:expr, $msg:literal $(,)?) => {
51+
if $left != $right {
52+
return $crate::private::Err($crate::format_err!($msg));
53+
}
54+
};
55+
($left:expr, $right:expr, $err:expr $(,)?) => {
56+
if $left != $right {
57+
return $crate::private::Err($crate::format_err!($err));
58+
}
59+
};
60+
($left:expr, $right:expr, $fmt:expr, $($arg:tt)*) => {
61+
if $left != $right {
62+
return $crate::private::Err($crate::format_err!($fmt, $($arg)*));
63+
}
64+
};
65+
}
66+
4167
/// Construct an ad-hoc error from a string.
4268
///
4369
/// This evaluates to an `Error`. It can take either just a string, or a format

tests/error.rs

Lines changed: 14 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1,4 +1,4 @@
1-
use http_types::{bail, ensure, Error, ErrorKind, StatusCode};
1+
use http_types::{bail, ensure, ensure_eq, Error, ErrorKind, StatusCode};
22
use std::io;
33

44
#[test]
@@ -23,3 +23,16 @@ fn ensure() {
2323
assert_eq!(err.status(), StatusCode::InternalServerError);
2424
assert_eq!(err.kind(), ErrorKind::Other);
2525
}
26+
27+
#[test]
28+
fn ensure_eq() {
29+
fn inner() -> http_types::Result<()> {
30+
ensure_eq!(1, 1, "Oh yes");
31+
bail!("Oh no!");
32+
}
33+
let res = inner();
34+
assert!(res.is_err());
35+
let err = res.unwrap_err();
36+
assert_eq!(err.status(), StatusCode::InternalServerError);
37+
assert_eq!(err.kind(), ErrorKind::Other);
38+
}

0 commit comments

Comments
 (0)