Skip to main content

xila_http/
response.rs

1use crate::{get_body, parse_header, split_lines};
2
3pub struct HttpResponseParser<'a>(&'a [u8]);
4
5impl<'a> HttpResponseParser<'a> {
6    pub fn from_buffer(buffer: &'a [u8]) -> Self {
7        HttpResponseParser(buffer)
8    }
9
10    pub fn split_lines(&self) -> impl Iterator<Item = &'a [u8]> + Clone + 'a {
11        split_lines(self.0)
12    }
13
14    pub fn get_status_code(&self) -> Option<u16> {
15        let mut lines = self.split_lines();
16
17        let status_line = lines.next()?;
18
19        let mut parts = status_line.splitn(3, |&b| b == b' ');
20
21        parts.next()?; // Skip HTTP version
22        let status_code_str = parts.next()?;
23
24        let status_code_str = core::str::from_utf8(status_code_str).ok()?;
25        let status_code = status_code_str.parse::<u16>().ok()?;
26
27        Some(status_code)
28    }
29
30    pub fn get_headers(&self) -> impl Iterator<Item = (&'a str, &'a str)> + 'a {
31        let mut lines = self.split_lines();
32
33        // Skip request line
34        lines.next();
35
36        lines
37            .take_while(|line| !line.is_empty())
38            .filter_map(parse_header)
39    }
40
41    pub fn get_body(&self) -> Option<&'a [u8]> {
42        get_body(self.0)
43    }
44}
45
46pub struct HttpResponseBuilder<'a> {
47    buffer: &'a mut [u8],
48    position: usize,
49}
50
51impl<'a> HttpResponseBuilder<'a> {
52    pub const LINE_ENDING: &'static [u8] = b"\r\n";
53
54    pub fn from_buffer(buffer: &'a mut [u8]) -> Self {
55        buffer.fill(0);
56
57        HttpResponseBuilder {
58            buffer,
59            position: 0,
60        }
61    }
62
63    pub fn add_line(&mut self, buffer: &[u8]) -> Option<()> {
64        let total_length = buffer.len() + Self::LINE_ENDING.len();
65
66        let destination_buffer = self
67            .buffer
68            .get_mut(self.position..self.position + total_length)?;
69
70        destination_buffer[..buffer.len()].copy_from_slice(buffer);
71        destination_buffer[buffer.len()..buffer.len() + Self::LINE_ENDING.len()]
72            .copy_from_slice(Self::LINE_ENDING);
73
74        self.position += total_length;
75
76        Some(())
77    }
78
79    pub fn add_line_iterator<'b, I>(&mut self, iter: I) -> Option<()>
80    where
81        I: Iterator<Item = &'b [u8]>,
82    {
83        // add in the same line all the parts from the iterator
84        let mut position = self.position; // temporary position, will be commited if all parts fit
85
86        for part in iter {
87            let part_length = part.len();
88
89            let destination_buffer = self.buffer.get_mut(position..position + part_length)?;
90
91            destination_buffer.copy_from_slice(part);
92            position += part_length;
93        }
94
95        let destination_buffer = self
96            .buffer
97            .get_mut(position..position + Self::LINE_ENDING.len())?;
98        destination_buffer.copy_from_slice(Self::LINE_ENDING);
99        position += Self::LINE_ENDING.len();
100
101        self.position = position;
102
103        Some(())
104    }
105
106    pub fn add_status_code(&mut self, status_code: u16) -> Option<()> {
107        let mut digits = [0; 5];
108        self.add_line_iterator(
109            [
110                b"HTTP/1.1 ".as_slice(),
111                crate::number(status_code as usize, 10, &mut digits),
112                b" ",
113            ]
114            .into_iter(),
115        )
116    }
117
118    pub fn add_header(&mut self, name: &str, value: &[u8]) -> Option<()> {
119        self.add_line_iterator([name.as_bytes(), b": ", value].into_iter())
120    }
121
122    pub fn add_body(&mut self, body: &[u8]) -> Option<()> {
123        let destination_buffer = self
124            .buffer
125            .get_mut(self.position..self.position + body.len())?;
126
127        destination_buffer.copy_from_slice(body);
128        self.position += body.len();
129
130        Some(())
131    }
132
133    pub fn add_chunk(&mut self, chunk: &[u8]) -> Option<()> {
134        let mut digits = [0; usize::BITS as usize / 4];
135        self.add_line(crate::number(chunk.len(), 16, &mut digits))?;
136        self.add_line(chunk)?;
137        Some(())
138    }
139
140    /// Write the terminating chunk (without trailers).
141    pub fn finish_chunks(&mut self) -> Option<()> {
142        self.add_body(b"0\r\n\r\n")
143    }
144
145    pub fn get_position(&self) -> usize {
146        self.position
147    }
148}