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
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
use crate::{parse_finish, parse_streaming, Paragraph, Streaming, SyntaxError};
use alloc::vec::Vec;
use core::{
    fmt,
    str::{from_utf8, Utf8Error},
};

/// A helper trait for stream input.
///
/// This trait is modeled on std's `Read`, but is separate so it's usable with `no_std`. When the
/// `std` feature is enabled (it is by default), this trait has a blanket implementation for every
/// type that implement std's `Read`.
pub trait BufParseInput {
    /// The error type returned by read operations.
    type Error;

    /// Read bytes into the provided buffer, up to its length, and return the number of bytes read.
    ///
    /// This function may read fewer bytes. If no more input is available, it should not modify the
    /// buffer and merely return 0.
    fn read(&mut self, buf: &mut [u8]) -> Result<usize, Self::Error>;
}

#[cfg(feature = "std")]
impl<R: std::io::Read + ?Sized> BufParseInput for R {
    type Error = std::io::Error;

    fn read(&mut self, buf: &mut [u8]) -> Result<usize, Self::Error> {
        self.read(buf)
    }
}

/// An error type returned by [`BufParse`](struct.BufParse.html).
#[derive(Debug)]
pub enum BufParseError<'a> {
    /// The input stream was not valid UTF-8.
    InvalidUtf8(Utf8Error),
    /// There was a syntax error in the input stream.
    InvalidSyntax(SyntaxError<'a>),
}

impl fmt::Display for BufParseError<'_> {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        match self {
            BufParseError::InvalidUtf8(err) => write!(f, "invalid utf-8 in input: {}", err),
            BufParseError::InvalidSyntax(err) => write!(f, "invalid syntax: {}", err),
        }
    }
}

impl<'a> From<Utf8Error> for BufParseError<'a> {
    fn from(err: Utf8Error) -> Self {
        BufParseError::InvalidUtf8(err)
    }
}

impl<'a> From<SyntaxError<'a>> for BufParseError<'a> {
    fn from(err: SyntaxError<'a>) -> Self {
        BufParseError::InvalidSyntax(err)
    }
}

#[cfg(feature = "std")]
impl std::error::Error for BufParseError<'_> {
    fn source(&self) -> Option<&(dyn std::error::Error + 'static)> {
        match self {
            BufParseError::InvalidUtf8(err) => Some(err),
            BufParseError::InvalidSyntax(_) => None,
        }
    }
}

/// A streaming control file parser that buffers input internally.
///
/// This type handles incrementally reading and buffering input from a source implementing the
/// [`BufParseInput`](trait.BufParseInput.html) trait.
///
/// # Example
/// ```
/// # #[cfg(feature = "std")] {
/// use debcontrol::{BufParse, Streaming};
/// use std::fs::File;
///
/// # let file_name = format!("{}/tests/control", env!("CARGO_MANIFEST_DIR"));
/// let f = File::open(file_name).unwrap();
/// let mut buf_parse = BufParse::new(f, 4096);
/// while let Some(result) = buf_parse.try_next().unwrap() {
///     match result {
///         Streaming::Item(paragraph) => {
///             for field in paragraph.fields {
///                 println!("{}: {}", field.name, &field.value);
///             }
///         }
///         Streaming::Incomplete => buf_parse.buffer().unwrap()
///     }
/// }
/// # }
/// ```
#[derive(Debug)]
pub struct BufParse<R> {
    chunk_size: usize,
    buf: Vec<u8>,
    pos: usize,
    read: R,
    exhausted: bool,
}

impl<R: BufParseInput> BufParse<R> {
    /// Create a new parser.
    pub fn new(read: R, chunk_size: usize) -> Self {
        BufParse {
            chunk_size,
            buf: Vec::with_capacity(chunk_size),
            pos: 0,
            read,
            exhausted: false,
        }
    }

    /// Read the next chunk of input into the buffer.
    pub fn buffer(&mut self) -> Result<(), R::Error> {
        let size = self.chunk_size;

        // Only drain leading data if we can't append the chunk without reallocating.
        if self.buf.capacity() - self.buf.len() < size {
            self.buf.drain(..self.pos);
            self.pos = 0;
        }

        let end = self.buf.len();
        self.buf.resize(end + size, 0);
        let read = self.read.read(&mut self.buf[end..])?;
        self.buf.truncate(end + read);

        if read == 0 {
            self.exhausted = true;
        }

        Ok(())
    }

    /// Try to parse the next paragraph from the input.
    ///
    /// A syntax error encountered during parsing is returned immediately. Otherwise, the nature of
    /// the `Ok` result determines what to do next:
    ///
    /// * If it's `None`, all input has been parsed. Future calls will continue to return `None`.
    /// * If it's [`Streaming::Incomplete`](enum.Streaming.html#variant.Incomplete), there's not
    ///   enough buffered input to make a parsing decision. Call
    ///   [`buffer`](struct.BufParse.html#method.buffer) to read more input.
    /// * If it's [`Streaming::Item`](enum.Streaming.html#variant.Item), a paragraph was parsed.
    ///   Call `try_next` again after processing it.
    pub fn try_next(&mut self) -> Result<Option<Streaming<Paragraph>>, BufParseError> {
        let input = self.as_longest_utf8(&self.buf)?;

        match parse_streaming(input)? {
            Streaming::Item((rest, paragraph)) => {
                let parsed = input.len() - rest.len();
                self.pos += parsed;
                Ok(Some(Streaming::Item(paragraph)))
            }
            Streaming::Incomplete => {
                if self.exhausted {
                    let input = self.as_utf8(&self.buf)?;
                    let result = parse_finish(input)?;
                    self.pos += input.len();
                    Ok(result.map(Streaming::Item))
                } else {
                    Ok(Some(Streaming::Incomplete))
                }
            }
        }
    }

    /// Consume this `BufParse` and return the wrapped input source.
    ///
    /// Any input that was already buffered will be lost.
    pub fn into_inner(self) -> R {
        self.read
    }

    /// Return the longest valid UTF-8 substring.
    fn as_longest_utf8<'a>(&'_ self, buf: &'a [u8]) -> Result<&'a str, Utf8Error> {
        self.as_utf8(buf).or_else(|err| match err.error_len() {
            Some(_) => Err(err),
            None => {
                let valid = &buf[self.pos..self.pos + err.valid_up_to()];
                from_utf8(valid)
            }
        })
    }

    /// Return the entire buffer as a str slice.
    fn as_utf8<'a>(&'_ self, buf: &'a [u8]) -> Result<&'a str, Utf8Error> {
        from_utf8(&buf[self.pos..])
    }
}

#[cfg(test)]
mod tests {
    use super::*;
    use alloc::{
        string::{String, ToString},
        vec,
    };
    use assert_matches::assert_matches;
    use core::cmp::min;
    use indoc::indoc;

    #[derive(Debug, PartialEq, Eq, Clone)]
    struct Bytes<'a> {
        bytes: &'a [u8],
        pos: usize,
    }

    impl<'a> Bytes<'a> {
        pub fn new(bytes: &'a [u8]) -> Self {
            Bytes { bytes, pos: 0 }
        }
    }

    impl<'a> BufParseInput for Bytes<'a> {
        type Error = ();

        fn read(&mut self, buf: &mut [u8]) -> Result<usize, Self::Error> {
            let to_read = min(self.bytes.len() - self.pos, buf.len());
            buf[..to_read].copy_from_slice(&self.bytes[self.pos..self.pos + to_read]);
            self.pos += to_read;
            Ok(to_read)
        }
    }

    fn parse_input(input: &[u8], chunk_size: usize) -> Vec<(String, String)> {
        let mut parser = BufParse::new(Bytes::new(input), chunk_size);
        let mut fields = vec![];
        while let Some(result) = parser.try_next().unwrap() {
            match result {
                Streaming::Item(paragraph) => {
                    fields.extend(
                        paragraph
                            .fields
                            .into_iter()
                            .map(|field| (field.name.to_string(), field.value)),
                    );
                }
                Streaming::Incomplete => parser.buffer().unwrap(),
            }
        }
        fields
    }

    #[test]
    fn should_parse_input_in_a_single_chunk() {
        let result = parse_input(
            indoc!(
                "field: value
                another-field: value"
            )
            .as_bytes(),
            1000,
        );
        assert_eq!(
            result,
            vec![
                ("field".to_string(), "value".to_string()),
                ("another-field".to_string(), "value".to_string())
            ]
        );
    }

    #[test]
    fn should_handle_partial_utf8_on_chunk_boundary() {
        let result = parse_input("12345:äöüöäüääöüäöäüöüöä".as_bytes(), 7);
        assert_eq!(
            result,
            vec![("12345".to_string(), "äöüöäüääöüäöäüöüöä".to_string())]
        );
    }

    #[test]
    fn should_handle_partial_utf8_after_advancing_position() {
        let result = parse_input("1:2\n\n3:äöü".as_bytes(), 8);
        assert_eq!(
            result,
            vec![
                ("1".to_string(), "2".to_string()),
                ("3".to_string(), "äöü".to_string()),
            ]
        );
    }

    #[test]
    fn should_need_to_buffer_at_least_twice_for_nonempty_input() {
        let mut parse = BufParse::new(Bytes::new(b"a: b"), 100);
        parse.buffer().unwrap();
        assert_matches!(parse.try_next(), Ok(Some(Streaming::Incomplete)));
        parse.buffer().unwrap();
        assert_matches!(parse.try_next(), Ok(Some(Streaming::Item(_))));
        assert_matches!(parse.try_next(), Ok(None));
    }

    #[test]
    fn should_keep_returning_none_when_input_is_exhausted() {
        let mut parse = BufParse::new(Bytes::new(b""), 10);
        parse.buffer().unwrap();
        assert_matches!(parse.try_next(), Ok(None));
        assert_matches!(parse.try_next(), Ok(None));
        assert_matches!(parse.try_next(), Ok(None));
    }

    #[test]
    fn should_fail_on_invalid_utf8_inside_chunk() {
        let mut parse = BufParse::new(Bytes::new(b"abc: a\xe2\x82\x28bcd efgh"), 100);
        parse.buffer().unwrap();
        assert_matches!(parse.try_next(), Err(BufParseError::InvalidUtf8(_)));
        assert_matches!(parse.try_next(), Err(BufParseError::InvalidUtf8(_)));
    }

    #[test]
    fn should_fail_on_invalid_utf8_on_chunk_border() {
        let mut parse = BufParse::new(Bytes::new(b"abc: ab\xe2\x82\x28bcd efgh"), 8);
        parse.buffer().unwrap();
        assert_matches!(parse.try_next(), Ok(Some(Streaming::Incomplete)));
        parse.buffer().unwrap();
        assert_matches!(parse.try_next(), Err(BufParseError::InvalidUtf8(_)));
    }

    #[test]
    fn should_fail_on_trailing_invalid_utf8() {
        let mut parse = BufParse::new(Bytes::new(b"abc: a\xe2\x82\x28"), 100);
        parse.buffer().unwrap();
        assert_matches!(parse.try_next(), Err(BufParseError::InvalidUtf8(_)));
    }

    #[test]
    fn should_fail_on_trailing_partial_utf8() {
        let mut parse = BufParse::new(Bytes::new(b"abc: a\xe2\x82"), 100);
        parse.buffer().unwrap();
        assert_matches!(parse.try_next(), Ok(Some(Streaming::Incomplete)));
        parse.buffer().unwrap();
        assert_matches!(parse.try_next(), Err(BufParseError::InvalidUtf8(_)));
    }

    #[test]
    fn should_return_inner() {
        let input = Bytes::new(b"abcd");
        let parse = BufParse::new(input.clone(), 100);
        let inner = parse.into_inner();
        assert_eq!(inner, input);
    }
}