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
use std::io;
use http::{
header::{CONTENT_LENGTH, TRANSFER_ENCODING},
HeaderMap, HeaderValue, Version,
};
use crate::CHUNKED;
#[derive(Debug, PartialEq, Eq, Clone)]
pub enum BodyFraming {
ContentLength(usize),
Chunked,
Neither,
}
impl BodyFraming {
pub fn update_content_length_value(&mut self, value: usize) -> io::Result<()> {
match self {
Self::ContentLength(n) => {
*n = value;
Ok(())
}
_ => Err(io::Error::new(
io::ErrorKind::InvalidInput,
"Not in ContentLength",
)),
}
}
}
pub trait BodyFramingDetector {
fn detect(&self) -> io::Result<BodyFraming>;
}
impl BodyFramingDetector for (&HeaderMap<HeaderValue>, &Version) {
fn detect(&self) -> io::Result<BodyFraming> {
let (headers, version) = *self;
if let Some(header_value) = headers.get(&CONTENT_LENGTH) {
let value_str = header_value
.to_str()
.map_err(|err| io::Error::new(io::ErrorKind::InvalidInput, err))?;
let value: usize = value_str
.parse()
.map_err(|err| io::Error::new(io::ErrorKind::InvalidInput, err))?;
return Ok(BodyFraming::ContentLength(value));
}
if version == &Version::HTTP_11 {
if let Some(header_value) = headers.get(&TRANSFER_ENCODING) {
if header_value == CHUNKED {
return Ok(BodyFraming::Chunked);
}
}
}
Ok(BodyFraming::Neither)
}
}