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 super::{Codec, Frame};
use std::{io, sync::Arc};

/// Represents a codec that invokes one of two codecs based on the given predicate
#[derive(Debug, Default, PartialEq, Eq)]
pub struct PredicateCodec<T, U, P> {
    left: T,
    right: U,
    predicate: Arc<P>,
}

impl<T, U, P> PredicateCodec<T, U, P> {
    /// Creates a new predicate codec where the left codec is invoked if the predicate returns true
    /// and the right codec is invoked if the predicate returns false
    pub fn new(left: T, right: U, predicate: P) -> Self {
        Self {
            left,
            right,
            predicate: Arc::new(predicate),
        }
    }

    /// Returns reference to left codec
    pub fn as_left(&self) -> &T {
        &self.left
    }

    /// Consumes the chain and returns the left codec
    pub fn into_left(self) -> T {
        self.left
    }

    /// Returns reference to right codec
    pub fn as_right(&self) -> &U {
        &self.right
    }

    /// Consumes the chain and returns the right codec
    pub fn into_right(self) -> U {
        self.right
    }

    /// Consumes the chain and returns the left and right codecs
    pub fn into_left_right(self) -> (T, U) {
        (self.left, self.right)
    }
}

impl<T, U, P> Clone for PredicateCodec<T, U, P>
where
    T: Clone,
    U: Clone,
{
    fn clone(&self) -> Self {
        Self {
            left: self.left.clone(),
            right: self.right.clone(),
            predicate: Arc::clone(&self.predicate),
        }
    }
}

impl<T, U, P> Codec for PredicateCodec<T, U, P>
where
    T: Codec + Clone,
    U: Codec + Clone,
    P: Fn(&Frame) -> bool,
{
    fn encode<'a>(&mut self, frame: Frame<'a>) -> io::Result<Frame<'a>> {
        if (self.predicate)(&frame) {
            Codec::encode(&mut self.left, frame)
        } else {
            Codec::encode(&mut self.right, frame)
        }
    }

    fn decode<'a>(&mut self, frame: Frame<'a>) -> io::Result<Frame<'a>> {
        if (self.predicate)(&frame) {
            Codec::decode(&mut self.left, frame)
        } else {
            Codec::decode(&mut self.right, frame)
        }
    }
}

#[cfg(test)]
mod tests {
    use super::*;
    use test_log::test;

    #[derive(Copy, Clone)]
    struct TestCodec<'a> {
        msg: &'a str,
    }

    impl<'a> TestCodec<'a> {
        pub fn new(msg: &'a str) -> Self {
            Self { msg }
        }
    }

    impl Codec for TestCodec<'_> {
        fn encode<'a>(&mut self, frame: Frame<'a>) -> io::Result<Frame<'a>> {
            let mut item = frame.into_item().to_vec();
            item.extend_from_slice(self.msg.as_bytes());
            Ok(Frame::from(item))
        }

        fn decode<'a>(&mut self, frame: Frame<'a>) -> io::Result<Frame<'a>> {
            let item = frame.into_item().to_vec();
            let frame = Frame::new(item.strip_suffix(self.msg.as_bytes()).ok_or_else(|| {
                io::Error::new(
                    io::ErrorKind::InvalidData,
                    format!(
                        "Decode failed because did not end with suffix: {}",
                        self.msg
                    ),
                )
            })?);
            Ok(frame.into_owned())
        }
    }

    #[derive(Copy, Clone)]
    struct ErrCodec;

    impl Codec for ErrCodec {
        fn encode<'a>(&mut self, _frame: Frame<'a>) -> io::Result<Frame<'a>> {
            Err(io::Error::from(io::ErrorKind::InvalidData))
        }

        fn decode<'a>(&mut self, _frame: Frame<'a>) -> io::Result<Frame<'a>> {
            Err(io::Error::from(io::ErrorKind::InvalidData))
        }
    }

    #[test]
    fn encode_should_invoke_left_codec_if_predicate_returns_true() {
        let mut codec = PredicateCodec::new(
            TestCodec::new("hello"),
            TestCodec::new("world"),
            |_: &Frame| true,
        );
        let frame = codec.encode(Frame::new(b"some bytes")).unwrap();
        assert_eq!(frame, b"some byteshello");
    }

    #[test]
    fn encode_should_invoke_right_codec_if_predicate_returns_false() {
        let mut codec = PredicateCodec::new(
            TestCodec::new("hello"),
            TestCodec::new("world"),
            |_: &Frame| false,
        );
        let frame = codec.encode(Frame::new(b"some bytes")).unwrap();
        assert_eq!(frame, b"some bytesworld");
    }

    #[test]
    fn decode_should_invoke_left_codec_if_predicate_returns_true() {
        let mut codec = PredicateCodec::new(
            TestCodec::new("hello"),
            TestCodec::new("world"),
            |_: &Frame| true,
        );
        let frame = codec.decode(Frame::new(b"some byteshello")).unwrap();
        assert_eq!(frame, b"some bytes");
    }

    #[test]
    fn decode_should_invoke_right_codec_if_predicate_returns_false() {
        let mut codec = PredicateCodec::new(
            TestCodec::new("hello"),
            TestCodec::new("world"),
            |_: &Frame| false,
        );
        let frame = codec.decode(Frame::new(b"some bytesworld")).unwrap();
        assert_eq!(frame, b"some bytes");
    }
}