From c7aca46fb37e4a4d13132f351abaae508cf7f428 Mon Sep 17 00:00:00 2001 From: Jasper De Sutter Date: Sat, 5 Oct 2019 23:09:16 +0200 Subject: [PATCH] make ensure! macro work with opaque error types fixes #175 --- src/lib.rs | 2 +- tests/opaque.rs | 28 +++++++++++++++++++++++++++- 2 files changed, 28 insertions(+), 2 deletions(-) diff --git a/src/lib.rs b/src/lib.rs index 93e375c2..6a327439 100644 --- a/src/lib.rs +++ b/src/lib.rs @@ -151,7 +151,7 @@ use std::error; macro_rules! ensure { ($predicate:expr, $context_selector:expr) => { if !$predicate { - return $context_selector.fail(); + return $context_selector.fail().map_err(core::convert::Into::into); } }; } diff --git a/tests/opaque.rs b/tests/opaque.rs index 3f8badae..1455c6df 100644 --- a/tests/opaque.rs +++ b/tests/opaque.rs @@ -1,5 +1,5 @@ mod inner { - use snafu::Snafu; + use snafu::{ensure, Snafu}; #[derive(Debug, Snafu)] pub struct Error(InnerError); @@ -8,6 +8,16 @@ mod inner { Ok(a()? + b()?) } + pub fn not_positive(value: i32) -> Result { + ensure!(value < 1, TooBig { count: value }); + Ok(value) + } + + pub fn boxed_inner(value: i32) -> Result> { + ensure!(value < 1, TooBig { count: value }); + Ok(value) + } + #[derive(Debug, Snafu)] enum InnerError { #[snafu(display = r#"("The value {} is too big", count)"#)] @@ -30,3 +40,19 @@ fn implements_error() { let e = inner::api().unwrap_err(); assert!(e.to_string().contains("too big")); } + +#[test] +fn ensure_opaque() { + assert!(inner::not_positive(-1).is_ok()); + + let e = inner::not_positive(2).unwrap_err(); + assert!(e.to_string().contains("too big")); +} + +#[test] +fn ensure_boxed() { + assert!(inner::boxed_inner(-1).is_ok()); + + let e = inner::boxed_inner(2).unwrap_err(); + assert!(e.to_string().contains("too big")); +}