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
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
use Box;
use ;
/// Trait that allows the host to return custom error.
///
/// It should be useful for representing custom traps,
/// troubles at instantiation time or other host specific conditions.
///
/// Types that implement this trait can automatically be converted to `wasmi::Error` and `wasmi::Trap`
/// and will be represented as a boxed `HostError`. You can then use the various methods on `wasmi::Error`
/// to get your custom error type back
///
/// # Examples
///
/// ```rust
/// use std::fmt;
/// use wasmi_core::{Trap, HostError};
///
/// #[derive(Debug, Copy, Clone)]
/// struct MyError {
/// code: u32,
/// }
///
/// impl fmt::Display for MyError {
/// fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
/// write!(f, "MyError, code={}", self.code)
/// }
/// }
///
/// impl HostError for MyError { }
///
/// fn failable_fn() -> Result<(), Trap> {
/// let my_error = MyError { code: 42 };
/// // Note how you can just convert your errors to `wasmi::Error`
/// Err(my_error.into())
/// }
///
/// // Get a reference to the concrete error
/// match failable_fn() {
/// Err(trap) => {
/// let my_error: &MyError = trap.downcast_ref().unwrap();
/// assert_eq!(my_error.code, 42);
/// }
/// _ => panic!(),
/// }
///
/// // get the concrete error itself
/// match failable_fn() {
/// Err(err) => {
/// let my_error = match err.downcast_ref::<MyError>() {
/// Some(host_error) => host_error.clone(),
/// None => panic!("expected host error `MyError` but found: {}", err),
/// };
/// assert_eq!(my_error.code, 42);
/// }
/// _ => panic!(),
/// }
/// ```