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
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
use crate::{Pipe, Result};
use std::marker::PhantomData;
use tuplify::Unpack;

/// Or combinator
pub trait OrExt<I, O, E, R> {
    /// Apply the second [Pipe] if the first fails
    ///
    /// Example:
    /// ```
    /// # use fatal_error::FatalError;
    /// # use pipe_chain::{Pipe, OrExt, tag, str::TagStrError, Incomplete};
    /// # use std::error::Error as StdError;
    /// # #[derive(Debug, PartialEq, Eq)]
    /// # enum Error {
    /// #     Incomplete(Incomplete),
    /// #     Tag(TagStrError),
    /// # }
    /// #
    /// # impl std::fmt::Display for Error {
    /// #     fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
    /// #        write!(f, "{self:?}")
    /// #     }
    /// # }
    /// # impl StdError for Error {}
    /// #
    /// # impl From<Incomplete> for Error {
    /// #     fn from(value: Incomplete) -> Error { Error::Incomplete(value) }
    /// # }
    /// #
    /// # impl From<TagStrError> for Error {
    /// #     fn from(value: TagStrError) -> Error { Error::Tag(value) }
    /// # }
    /// assert_eq!(tag::<Error, _, _>("foo").or(tag("bar")).apply("foo"), Ok(("", ("foo",))));
    ///
    /// assert_eq!(tag::<Error, _, _>("foo").or(tag("boo")).apply("boo"), Ok(("", ("boo",))));
    ///
    /// assert_eq!(
    ///     tag::<Error, _, _>("foo").or(tag("boo")).apply("something"),
    ///     Err(FatalError::Error(Error::Tag(TagStrError("boo".into(), "som".into()))))
    /// );
    /// ```
    fn or<P>(self, p: P) -> Or<Self, P>
    where
        Self: Sized,
        I: Clone,
        P: Pipe<I, O, E, R>,
    {
        Or::new(self, p)
    }

    /// Apply the second [Pipe] if the first fails discarding the output of the second pipe
    ///
    /// Example:
    /// ```
    /// # use fatal_error::FatalError;
    /// # use pipe_chain::{Pipe, OrExt, tag, str::TagStrError, Incomplete};
    /// # use std::error::Error as StdError;
    /// # #[derive(Debug, PartialEq, Eq)]
    /// # enum Error {
    /// #     Incomplete(Incomplete),
    /// #     Tag(TagStrError),
    /// # }
    /// #
    /// # impl std::fmt::Display for Error {
    /// #     fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
    /// #        write!(f, "{self:?}")
    /// #     }
    /// # }
    /// # impl StdError for Error {}
    /// #
    /// # impl From<Incomplete> for Error {
    /// #     fn from(value: Incomplete) -> Error { Error::Incomplete(value) }
    /// # }
    /// #
    /// # impl From<TagStrError> for Error {
    /// #     fn from(value: TagStrError) -> Error { Error::Tag(value) }
    /// # }
    /// assert_eq!(
    ///     tag::<Error, _, _>("foo").or_self(tag("bar")).apply("foo"),
    ///     Ok(("", (Some("foo"),)))
    /// );
    ///
    /// assert_eq!(
    ///     tag::<Error, _, _>("foo").or_self(tag("boo")).apply("boo"),
    ///     Ok(("", (None,)))
    /// );
    ///
    /// assert_eq!(
    ///     tag::<Error, _, _>("foo").or_self(tag("boo")).apply("something"),
    ///     Err(FatalError::Error(Error::Tag(TagStrError("boo".into(), "som".into()))))
    /// );
    /// ```
    fn or_self<O2, P>(self, p: P) -> OrSelf<O, O2, Self, P>
    where
        Self: Sized,
        O: Unpack,
        I: Clone,
        P: Pipe<I, O2, E, R>,
    {
        OrSelf::new(self, p)
    }

    /// Apply the second [Pipe] if the first fails discarding the output of the first pipe
    ///
    /// Example:
    /// ```
    /// # use fatal_error::FatalError;
    /// # use pipe_chain::{Pipe, OrExt, tag, str::TagStrError, Incomplete};
    /// # use std::error::Error as StdError;
    /// # #[derive(Debug, PartialEq, Eq)]
    /// # enum Error {
    /// #     Incomplete(Incomplete),
    /// #     Tag(TagStrError),
    /// # }
    /// #
    /// # impl std::fmt::Display for Error {
    /// #     fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
    /// #        write!(f, "{self:?}")
    /// #     }
    /// # }
    /// # impl StdError for Error {}
    /// #
    /// # impl From<Incomplete> for Error {
    /// #     fn from(value: Incomplete) -> Error { Error::Incomplete(value) }
    /// # }
    /// #
    /// # impl From<TagStrError> for Error {
    /// #     fn from(value: TagStrError) -> Error { Error::Tag(value) }
    /// # }
    /// assert_eq!(
    ///     tag::<Error, _, _>("foo").or_other(tag("bar")).apply("foo"),
    ///     Ok(("", (None,)))
    /// );
    ///
    /// assert_eq!(
    ///     tag::<Error, _, _>("foo").or_other(tag("boo")).apply("boo"),
    ///     Ok(("", (Some("boo"),)))
    /// );
    ///
    /// assert_eq!(
    ///     tag::<Error, _, _>("foo").or_other(tag("boo")).apply("something"),
    ///     Err(FatalError::Error(Error::Tag(TagStrError("boo".into(), "som".into()))))
    /// );
    /// ```
    fn or_other<O2, P>(self, p: P) -> OrOther<O, O2, Self, P>
    where
        Self: Sized,
        I: Clone,
        O2: Unpack,
        P: Pipe<I, O2, E, R>,
    {
        OrOther::new(self, p)
    }
}

impl<I, O, E, R, P> OrExt<I, O, E, R> for P where P: Pipe<I, O, E, R> {}

/// [OrExt::or] implementation
pub struct Or<P, P1> {
    p:  P,
    p1: P1,
}

impl<P, P1> Or<P, P1> {
    fn new(p: P, p1: P1) -> Self { Self { p, p1 } }
}

impl<I, O, E, R, P, P1> Pipe<I, O, E, R> for Or<P, P1>
where
    P: Pipe<I, O, E, R>,
    P1: Pipe<I, O, E, R>,
    I: Clone,
{
    fn apply(&mut self, input: I) -> Result<R, O, E> {
        match self.p.apply(input.clone()) {
            x @ Ok(_) => x,
            Err(x) => {
                x.fatality()?;
                self.p1.apply(input)
            }
        }
    }
}

/// [OrExt::or_self] implementation
pub struct OrSelf<O, O2, P, P1> {
    p:  P,
    p1: P1,
    o:  PhantomData<O>,
    o2: PhantomData<O2>,
}

impl<O, O2, P, P1> OrSelf<O, O2, P, P1> {
    fn new(p: P, p1: P1) -> Self { Self { p, p1, o: PhantomData, o2: PhantomData } }
}

impl<I, O, O2, E, R, P, P1> Pipe<I, (Option<O::Output>,), E, R> for OrSelf<O, O2, P, P1>
where
    O: Unpack,
    P: Pipe<I, O, E, R>,
    P1: Pipe<I, O2, E, R>,
    I: Clone,
{
    fn apply(&mut self, input: I) -> Result<R, (Option<O::Output>,), E> {
        match self.p.apply(input.clone()).map(|(x, y)| (x, (Some(y.unpack()),))) {
            x @ Ok(_) => x,
            Err(x) => {
                x.fatality()?;
                self.p1.apply(input).map(|(x, _)| (x, (None,)))
            }
        }
    }
}

/// [OrExt::or_other] implementation
pub struct OrOther<O, O2, P, P1> {
    p:  P,
    p1: P1,
    o:  PhantomData<O>,
    o2: PhantomData<O2>,
}

impl<O, O2, P, P1> OrOther<O, O2, P, P1> {
    fn new(p: P, p1: P1) -> Self { Self { p, p1, o: PhantomData, o2: PhantomData } }
}

impl<I, O, O2, E, R, P, P1> Pipe<I, (Option<O2::Output>,), E, R> for OrOther<O, O2, P, P1>
where
    O2: Unpack,
    P: Pipe<I, O, E, R>,
    P1: Pipe<I, O2, E, R>,
    I: Clone,
{
    fn apply(&mut self, input: I) -> Result<R, (Option<O2::Output>,), E> {
        match self.p.apply(input.clone()).map(|(x, _)| (x, (None,))) {
            x @ Ok(_) => x,
            Err(x) => {
                x.fatality()?;
                self.p1.apply(input).map(|(x, y)| (x, (Some(y.unpack()),)))
            }
        }
    }
}

/// [any_of] implementation detail
pub trait AnyOf<I, O, E, R> {
    /// Process the input
    fn apply_any_of(&mut self, input: I) -> Result<R, O, E>;
}

/// Similar to [OrExt::or] but with many possibilities at once
///
/// Example
/// ```
/// # use fatal_error::FatalError;
/// # use pipe_chain::{Pipe, any_of, tag, str::TagStrError, Incomplete};
/// # use std::error::Error as StdError;
/// # #[derive(Debug, PartialEq, Eq)]
/// # enum Error {
/// #     Incomplete(Incomplete),
/// #     Tag(TagStrError),
/// # }
/// #
/// # impl std::fmt::Display for Error {
/// #     fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
/// #        write!(f, "{self:?}")
/// #     }
/// # }
/// # impl StdError for Error {}
/// #
/// # impl From<Incomplete> for Error {
/// #     fn from(value: Incomplete) -> Error { Error::Incomplete(value) }
/// # }
/// #
/// # impl From<TagStrError> for Error {
/// #     fn from(value: TagStrError) -> Error { Error::Tag(value) }
/// # }
/// let mut p = any_of((tag::<Error, _, _>("foo"), tag("bar"), tag("baz")));
///
/// assert_eq!(p.apply("foo"), Ok(("", ("foo",))));
///
/// assert_eq!(p.apply("bar"), Ok(("", ("bar",))));
///
/// assert_eq!(p.apply("baz"), Ok(("", ("baz",))));
///
/// assert_eq!(
///     p.apply("something"),
///     Err(FatalError::Error(Error::Tag(TagStrError("baz".into(), "som".into()))))
/// );
/// ```
pub fn any_of<I, O, E, R>(mut p: impl AnyOf<I, O, E, R>) -> impl Pipe<I, O, E, R> {
    move |x| p.apply_any_of(x)
}

macro_rules! any_of_impl {
    ($_head:ident) => {};
    ($head:ident $($tail:ident) *) => {
        any_of_impl!($($tail) *);

        impl<I: Clone, O, E, R, $head: Pipe<I, O, E, R>, $($tail: Pipe<I, O, E, R>), *> AnyOf<I, O, E, R> for ($head, $($tail), *) {
            #[allow(non_snake_case)]
            fn apply_any_of(&mut self, input: I) -> Result<R, O, E> {
                let ($head, $($tail), *) = self;
                let e = $head.apply(input.clone());
                if e.as_ref().map_or_else(|x|x.is_fatal(), |_| true) { return e; }
                $(
                    let e = $tail.apply(input.clone());
                    if e.as_ref().map_or_else(|x|x.is_fatal(), |_| true) { return e; }
                ) *
                e
            }
        }
    };
}

any_of_impl!(T1 T2 T3 T4 T5 T6 T7 T8 T9 T10 T11 T12 T13 T14 T15 T16 T17 T18 T19 T20 T21 T22 T23 T24 T25 T26 T27 T28 T29 T30 T31 T32);