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
use std::io::{Error as IoError, ErrorKind as IoErrorKind};

use http::{
    header::{CONTENT_LENGTH, TRANSFER_ENCODING},
    HeaderMap, HeaderValue, Version,
};

use crate::CHUNKED;

//
//
//
// ref https://github.com/apple/swift-nio/blob/2.20.2/Sources/NIOHTTP1/HTTPEncoder.swift#L89
#[derive(Debug, PartialEq, Eq, Clone)]
pub enum BodyFraming {
    ContentLength(usize),
    Chunked,
    Neither,
}

impl BodyFraming {
    pub fn update_content_length_value(&mut self, value: usize) -> Result<(), IoError> {
        match self {
            Self::ContentLength(n) => {
                *n = value;
                Ok(())
            }
            _ => Err(IoError::new(
                IoErrorKind::InvalidInput,
                "Not in ContentLength",
            )),
        }
    }
}

pub trait BodyFramingDetector {
    fn detect(&self) -> Result<BodyFraming, IoError>;
}
impl BodyFramingDetector for (&HeaderMap<HeaderValue>, &Version) {
    fn detect(&self) -> Result<BodyFraming, IoError> {
        let (headers, version) = *self;

        if let Some(header_value) = headers.get(CONTENT_LENGTH) {
            let value_str = header_value
                .to_str()
                .map_err(|err| IoError::new(IoErrorKind::InvalidInput, err))?;
            let value: usize = value_str
                .parse()
                .map_err(|err| IoError::new(IoErrorKind::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)
    }
}

#[cfg(test)]
mod tests {
    use super::*;

    #[test]
    fn detect() -> Result<(), Box<dyn std::error::Error>> {
        let mut header_map = HeaderMap::new();

        header_map.insert("Content-Length", "1".parse().unwrap());
        assert_eq!(
            (&header_map, &Version::HTTP_11).detect()?,
            BodyFraming::ContentLength(1)
        );

        header_map.clear();
        header_map.insert("Transfer-Encoding", "chunked".parse().unwrap());
        assert_eq!(
            (&header_map, &Version::HTTP_10).detect()?,
            BodyFraming::Neither
        );
        assert_eq!(
            (&header_map, &Version::HTTP_11).detect()?,
            BodyFraming::Chunked
        );

        header_map.clear();
        assert_eq!(
            (&header_map, &Version::HTTP_11).detect()?,
            BodyFraming::Neither
        );

        Ok(())
    }
}