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
use std::io::{BufRead, Read as _};

use crate::{
    body_parser::{BodyParseError, BodyParseOutput, BodyParser},
    CR, CRLF, LF,
};

//
//
//
const LENGTH_MAX_LEN: usize = 4; // b"FFFF"
const DATA_DEFAULT_LEN: usize = 512;

//
//
//
#[derive(Default)]
pub struct ChunkedBodyParser {
    //
    state: State,
    length_buf: Vec<u8>,
    length: u16,
    data_buf: Vec<u8>,
}

#[derive(Debug, PartialEq, Eq, PartialOrd, Ord)]
enum State {
    Idle,
    WaitLengthParse,
    WaitDataParse,
    WaitDataParsing,
    WaitCRLFParse(ActionAfterCRLFParsed),
}
impl Default for State {
    fn default() -> Self {
        Self::Idle
    }
}

#[derive(Debug, PartialEq, Eq, PartialOrd, Ord)]
enum ActionAfterCRLFParsed {
    Continue,
    Break,
}

impl ChunkedBodyParser {
    pub fn new() -> Self {
        Self {
            length_buf: Vec::with_capacity(LENGTH_MAX_LEN),
            data_buf: vec![0u8; DATA_DEFAULT_LEN],
            ..Default::default()
        }
    }

    pub fn with_data_buf(data_buf: Vec<u8>) -> Self {
        Self {
            length_buf: Vec::with_capacity(LENGTH_MAX_LEN),
            data_buf,
            ..Default::default()
        }
    }
}

//
//
//
impl BodyParser for ChunkedBodyParser {
    fn parse<R: BufRead>(
        &mut self,
        r: &mut R,
        body_buf: &mut Vec<u8>,
    ) -> Result<BodyParseOutput, BodyParseError> {
        let mut take = r.take(0);
        let mut parsed_num_bytes = 0_usize;

        loop {
            if self.state <= State::WaitLengthParse {
                let end_bytes_len = 2_usize;
                take.set_limit(LENGTH_MAX_LEN as u64 + end_bytes_len as u64);

                self.length_buf.clear();
                let n = take
                    .read_until(LF, &mut self.length_buf)
                    .map_err(BodyParseError::ReadError)?;

                if n < end_bytes_len {
                    return Ok(BodyParseOutput::Partial(parsed_num_bytes));
                }
                if !self.length_buf[..n].ends_with(&[LF]) {
                    if n >= LENGTH_MAX_LEN {
                        return Err(BodyParseError::TooLongChunksOfLength);
                    } else {
                        return Ok(BodyParseOutput::Partial(parsed_num_bytes));
                    }
                }
                if !self.length_buf[..n - 1].ends_with(&[CR]) {
                    return Err(BodyParseError::InvalidCRLF);
                }
                let length_bytes = &self.length_buf[..n - end_bytes_len];
                let length_str = core::str::from_utf8(length_bytes)
                    .map_err(|_| BodyParseError::InvalidChunksOfLength(None))?;
                let length = u16::from_str_radix(length_str, 16)
                    .map_err(|err| BodyParseError::InvalidChunksOfLength(Some(err)))?;

                self.length = length;
                parsed_num_bytes += n;

                if length == 0 {
                    self.state = State::WaitCRLFParse(ActionAfterCRLFParsed::Break);
                } else {
                    self.state = State::WaitDataParse;
                }
            }

            if self.state <= State::WaitDataParsing {
                take.set_limit(self.length as u64);

                let n = take
                    .read(&mut self.data_buf)
                    .map_err(BodyParseError::ReadError)?;
                body_buf.extend_from_slice(&self.data_buf[..n]);

                self.length -= n as u16;
                parsed_num_bytes += n;

                if self.length == 0 {
                    self.state = State::WaitCRLFParse(ActionAfterCRLFParsed::Continue);
                } else {
                    self.state = State::WaitDataParsing;

                    return Ok(BodyParseOutput::Partial(parsed_num_bytes));
                }
            }

            if let State::WaitCRLFParse(action) = &self.state {
                let end_bytes_len = 2_usize;
                take.set_limit(end_bytes_len as u64);

                self.length_buf.clear();
                let n = take
                    .read_until(LF, &mut self.length_buf)
                    .map_err(BodyParseError::ReadError)?;
                if n < end_bytes_len {
                    return Ok(BodyParseOutput::Partial(parsed_num_bytes));
                }
                if &self.length_buf[..n] != CRLF {
                    return Err(BodyParseError::InvalidCRLF);
                }
                parsed_num_bytes += n;

                match action {
                    ActionAfterCRLFParsed::Continue => {
                        self.state = State::WaitLengthParse;

                        continue;
                    }
                    ActionAfterCRLFParsed::Break => {
                        self.state = State::Idle;

                        break Ok(BodyParseOutput::Completed(parsed_num_bytes));
                    }
                }
            }

            unreachable!()
        }
    }
}