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
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
use crate::;
/// Properties of a generalized result type.
///
/// This unifies [`Result`] and `#[iex] Result`.
///
/// # Ownership
///
/// The semantics of ownership and capturing for `#[iex] Result` complicates the use of `map_err`
/// and `inspect_err` in some cases. Notably, using `f(...).map_err(|e| ...)` requires that `f(...)`
/// and `|e| ...` don't capture variables in incompatible ways:
///
/// ```compile_fail
/// use iex::{iex, Outcome};
///
/// struct Struct;
///
/// impl Struct {
/// #[iex]
/// fn errors(&mut self) -> Result<(), i32> {
/// Err(123)
/// }
/// fn error_mapper(&mut self, err: i32) -> i32 {
/// err + 1
/// }
/// #[iex]
/// fn calls(&mut self) -> Result<(), i32> {
/// // closure requires unique access to `*self` but it is already borrowed
/// self.errors().map_err(|err| self.error_mapper(err))
/// }
/// }
/// ```
///
/// `#[iex]` provides a workaround for this particular usecase. The patterns
/// `(..).map_err(#[iex(shares = ..)] ..)?` and similarly for `inspect_err` (only these patterns,
/// the `?` is required) allows you to share variables between the fallible function and the error
/// handler. A *mutable reference* to the variable will be visible to the fallible function, and the
/// *value* of the variable will be visible to the error handler. This applies to `self` too:
///
/// ```
/// use iex::{iex, Outcome};
///
/// struct Struct;
///
/// impl Struct {
/// #[iex]
/// fn errors(&mut self) -> Result<(), i32> {
/// Err(123)
/// }
/// fn error_mapper(&mut self, err: i32) -> i32 {
/// err + 1
/// }
/// #[iex]
/// fn calls(&mut self) -> Result<(), i32> {
/// Ok(self.errors().map_err(#[iex(shares = self)] |err| self.error_mapper(err))?)
/// }
/// }
/// ```
///
/// In a more complicated case, you would have to resort to the less efficient
/// [`into_result`](Self::into_result):
///
/// ```
/// use iex::{iex, Outcome};
///
/// struct Struct;
///
/// impl Struct {
/// #[iex]
/// fn errors(&mut self) -> Result<(), i32> {
/// Err(123)
/// }
/// fn error_mapper(&mut self, err: i32) -> i32 {
/// err + 1
/// }
/// #[iex]
/// fn calls(&mut self) -> Result<(), i32> {
/// self.errors().into_result().map_err(|err| self.error_mapper(err))
/// }
/// }
/// ```