#[macro_export]
macro_rules! on_result {
($expr:expr, $ok_var:pat => $ok_body:expr, $err_var:pat => $err_body:expr) => {
match $expr {
Ok($ok_var) => $ok_body,
Err($err_var) => $err_body,
}
};
}
#[cfg(test)]
mod test_on_result {
#[test]
fn test() {
assert_eq!(
on_result!(Ok::<usize, Box<dyn std::error::Error + 'static>>(10), val => val, _err => 20),
10
);
assert_eq!(
on_result!(Err::<usize, std::io::Error>(std::io::Error::from(std::io::ErrorKind::AlreadyExists)), val => val, _err => 20),
20
);
}
}
#[macro_export]
macro_rules! unwrap_or_panic_log {
($expr:expr) => {
match $expr {
Ok(val) => val,
Err(e) => {
tracing::error!("Error unwrapping: {:?}", e);
panic!("Unrecoverable error: {:?}", e);
}
}
};
}
#[cfg(test)]
mod test_unwrap_or_panic_log {
#[test]
fn test() {
assert_eq!(
unwrap_or_panic_log!(Ok::<usize, Box<dyn std::error::Error + 'static>>(10)),
10
);
}
}
#[macro_export]
macro_rules! is_ok {
($expr:expr, $($ok_value:expr),+ $(,)?) => {
match $expr {
Ok(val) => {
let values = [$($ok_value),*];
let mut result = false;
for v in values.iter() {
if val == *v {
result = true;
break;
}
}
result
},
Err(_) => false,
}
};
}
#[cfg(test)]
mod test_is_ok {
#[test]
fn test() {
assert!(is_ok!(
Ok::<usize, Box<dyn std::error::Error + 'static>>(10),
10
));
assert!(is_ok!(
Ok::<usize, Box<dyn std::error::Error + 'static>>(10),
20,
10
));
assert!(!is_ok!(
Ok::<usize, Box<dyn std::error::Error + 'static>>(10),
20
));
assert!(!is_ok!(
Err::<usize, std::io::Error>(std::io::Error::from(std::io::ErrorKind::AlreadyExists)),
10
));
}
}