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
use crate::{
    context::{ContextOperator, Value},
    Operator,
};

use super::Layer;

/// Optional layer.
/// It requires that the inner layer won't change the input and output of the input operator.
#[derive(Debug, Clone, Copy)]
pub struct OptionalLayer<L>(pub(crate) Option<L>);

impl<In, P, L> Layer<In, P> for OptionalLayer<L>
where
    P: ContextOperator<In>,
    L: Layer<In, P>,
    L::Operator: ContextOperator<In, Out = P::Out>,
{
    type Operator = Either<L::Operator, P>;

    type Out = P::Out;

    fn layer(&self, operator: P) -> Self::Operator {
        match &self.0 {
            Some(l) => Either::Left(l.layer(operator)),
            None => Either::Right(operator),
        }
    }
}

/// Either operator.
#[derive(Debug, Clone, Copy)]
pub enum Either<A, B> {
    /// Left.
    Left(A),
    /// Right.
    Right(B),
}

impl<In, Out, A, B> Operator<Value<In>> for Either<A, B>
where
    A: ContextOperator<In, Out = Out>,
    B: ContextOperator<In, Out = Out>,
{
    type Output = Value<Out>;

    fn next(&mut self, input: Value<In>) -> Self::Output {
        match self {
            Either::Left(a) => a.next(input),
            Either::Right(b) => b.next(input),
        }
    }
}