http1_spec/
content_length_body_parser.rs1use std::io::{BufRead, Read as _};
2
3use crate::body_parser::{BodyParseError, BodyParseOutput, BodyParser};
4
5#[derive(Default)]
9pub struct ContentLengthBodyParser {
10 length: usize,
11}
12impl ContentLengthBodyParser {
13 pub fn new() -> Self {
14 Self::default()
15 }
16
17 pub fn set_length(&mut self, length: usize) {
18 self.length = length
19 }
20 pub fn get_length(&self) -> usize {
21 self.length
22 }
23}
24
25impl BodyParser for ContentLengthBodyParser {
29 fn parse<R: BufRead>(
30 &mut self,
31 r: &mut R,
32 body_buf: &mut Vec<u8>,
33 ) -> Result<BodyParseOutput, BodyParseError> {
34 let mut take = r.take(self.length as u64);
35
36 let n = take.read(body_buf).map_err(BodyParseError::ReadError)?;
37 self.length -= n;
38
39 if self.length == 0 {
40 Ok(BodyParseOutput::Completed(n))
41 } else {
42 Ok(BodyParseOutput::Partial(n))
43 }
44 }
45}