-
Notifications
You must be signed in to change notification settings - Fork 61
/
opaque.rs
58 lines (46 loc) · 1.31 KB
/
opaque.rs
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
mod inner {
use snafu::prelude::*;
#[derive(Debug, Snafu)]
pub struct Error(InnerError);
pub fn api() -> Result<i32, Error> {
Ok(a()? + b()?)
}
pub fn not_positive(value: i32) -> Result<i32, Error> {
ensure!(value < 1, TooBigSnafu { count: value });
Ok(value)
}
pub fn boxed_inner(value: i32) -> Result<i32, Box<dyn std::error::Error>> {
ensure!(value < 1, TooBigSnafu { count: value });
Ok(value)
}
#[derive(Debug, Snafu)]
enum InnerError {
#[snafu(display("The value {count} is too big"))]
TooBig { count: i32 },
}
fn a() -> Result<i32, InnerError> {
TooBigSnafu { count: 1 }.fail()
}
fn b() -> Result<i32, InnerError> {
TooBigSnafu { count: 2 }.fail()
}
}
#[test]
fn implements_error() {
fn check<T: std::error::Error>() {}
check::<inner::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"));
}