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
use crate::{
    error::ParseError,
    stream::buf_reader::{Buffer, Bufferless, CombineBuffer},
};

use std::{
    fmt,
    io::{self, Read},
};

#[cfg(feature = "pin-project-lite")]
use std::pin::Pin;

#[derive(Debug)]
pub enum Error<E, P> {
    Parse(E),
    Io { position: P, error: io::Error },
}

impl<'a, P> From<Error<crate::easy::Errors<u8, &'a [u8], P>, P>>
    for crate::easy::Errors<u8, &'a [u8], P>
where
    P: Ord + Clone,
{
    fn from(e: Error<crate::easy::Errors<u8, &'a [u8], P>, P>) -> Self {
        match e {
            Error::Parse(e) => e,
            Error::Io { position, error } => {
                crate::easy::Errors::from_error(position, crate::easy::Error::Other(error.into()))
            }
        }
    }
}

impl<E, P> std::error::Error for Error<E, P>
where
    E: std::error::Error,
    P: fmt::Display + fmt::Debug,
{
}

impl<E: fmt::Display, P: fmt::Display> fmt::Display for Error<E, P> {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        match self {
            Error::Parse(e) => e.fmt(f),
            Error::Io { position: _, error } => error.fmt(f),
        }
    }
}

#[derive(Default)]
/// Used together with the `decode!` macro
pub struct Decoder<S, P, C = Buffer> {
    position: P,
    state: S,
    buffer: C,
    end_of_input: bool,
}

impl<S, P> Decoder<S, P, Buffer>
where
    P: Default,
    S: Default,
{
    /// Constructs a new [`Decoder`] with an internal buffer. Allows any `AsyncRead/Read` instance to
    /// be used when decoding but there may be data left in the internal buffer after decoding
    /// (accessible with [`Decoder::buffer`])
    pub fn new() -> Self {
        Decoder::default()
    }

    /// Constructs a new [`Decoder`] with an internal buffer. Allows any `AsyncRead/Read` instance to
    /// be used when decoding but there may be data left in the internal buffer after decoding
    /// (accessible with [`Decoder::buffer`])
    pub fn new_buffer() -> Self {
        Decoder::new()
    }
}

impl<S, P> Decoder<S, P, Bufferless>
where
    P: Default,
    S: Default,
{
    /// Constructs a new `Decoder` without an internal buffer. Requires the read instance to be
    /// wrapped with combine's [`BufReader`] instance to
    ///
    /// [`BufReader`]: super::buf_reader::BufReader
    pub fn new_bufferless() -> Self {
        Decoder::default()
    }
}

impl<S, P> Decoder<S, P> {
    pub fn buffer(&self) -> &[u8] {
        &self.buffer.0
    }
}

impl<S, P, C> Decoder<S, P, C> {
    #[doc(hidden)]
    pub fn advance<R>(&mut self, read: &mut R, removed: usize)
    where
        C: CombineBuffer<R>,
    {
        // Remove the data we have parsed and adjust `removed` to be the amount of data we
        // committed from `self.reader`
        self.buffer.advance(read, removed)
    }

    #[doc(hidden)]
    #[cfg(feature = "pin-project-lite")]
    pub fn advance_pin<R>(&mut self, read: Pin<&mut R>, removed: usize)
    where
        C: CombineBuffer<R>,
    {
        // Remove the data we have parsed and adjust `removed` to be the amount of data we
        // committed from `self.reader`
        self.buffer.advance_pin(read, removed);
    }

    pub fn position(&self) -> &P {
        &self.position
    }

    #[doc(hidden)]
    pub fn __inner(&mut self) -> (&mut S, &mut P, &C, bool) {
        (
            &mut self.state,
            &mut self.position,
            &self.buffer,
            self.end_of_input,
        )
    }
}

impl<S, P, C> Decoder<S, P, C>
where
    C: ,
{
    #[doc(hidden)]
    pub fn __before_parse<R>(&mut self, mut reader: R) -> io::Result<()>
    where
        R: Read,
        C: crate::stream::buf_reader::CombineSyncRead<R>,
    {
        if self.buffer.extend_buf_sync(&mut reader)? == 0 {
            self.end_of_input = true;
        }

        Ok(())
    }
}

#[cfg(feature = "tokio-02")]
impl<S, P, C> Decoder<S, P, C> {
    #[doc(hidden)]
    pub async fn __before_parse_tokio_02<R>(&mut self, mut reader: Pin<&mut R>) -> io::Result<()>
    where
        R: tokio_02_dep::io::AsyncRead,
        C: crate::stream::buf_reader::CombineRead<R, dyn tokio_02_dep::io::AsyncRead>,
    {
        let copied =
            futures_util_03::future::poll_fn(|cx| self.buffer.poll_extend_buf(cx, reader.as_mut()))
                .await?;
        if copied == 0 {
            self.end_of_input = true;
        }

        Ok(())
    }
}

#[cfg(feature = "tokio-03")]
impl<S, P, C> Decoder<S, P, C> {
    #[doc(hidden)]
    pub async fn __before_parse_tokio_03<R>(&mut self, mut reader: Pin<&mut R>) -> io::Result<()>
    where
        R: tokio_03_dep::io::AsyncRead,
        C: crate::stream::buf_reader::CombineRead<R, dyn tokio_03_dep::io::AsyncRead>,
    {
        let copied =
            futures_util_03::future::poll_fn(|cx| self.buffer.poll_extend_buf(cx, reader.as_mut()))
                .await?;
        if copied == 0 {
            self.end_of_input = true;
        }

        Ok(())
    }
}

#[cfg(feature = "tokio")]
impl<S, P, C> Decoder<S, P, C> {
    #[doc(hidden)]
    pub async fn __before_parse_tokio<R>(&mut self, mut reader: Pin<&mut R>) -> io::Result<()>
    where
        R: tokio_dep::io::AsyncRead,
        C: crate::stream::buf_reader::CombineRead<R, dyn tokio_dep::io::AsyncRead>,
    {
        let copied =
            futures_util_03::future::poll_fn(|cx| self.buffer.poll_extend_buf(cx, reader.as_mut()))
                .await?;
        if copied == 0 {
            self.end_of_input = true;
        }

        Ok(())
    }
}

#[cfg(feature = "futures-03")]
impl<S, P, C> Decoder<S, P, C> {
    #[doc(hidden)]
    pub async fn __before_parse_async<R>(&mut self, reader: Pin<&mut R>) -> io::Result<()>
    where
        R: futures_io_03::AsyncRead,
        C: crate::stream::buf_reader::CombineAsyncRead<R>,
    {
        let copied = self.buffer.extend_buf(reader).await?;

        if copied == 0 {
            self.end_of_input = true;
        }
        Ok(())
    }
}