Skip to main content

sark_http/h1/codec/decode/
chunks.rs

1use std::num;
2
3use o3::{alloc, buffer::write::Sink as _};
4
5use crate::{
6    h1::{
7        chunk,
8        codec::decode::trailer,
9    },
10    payload::response::headers::{List, list},
11};
12
13const MAX_BODY_SIZE: usize = 100 * 1024 * 1024;
14
15#[derive(Debug)]
16pub enum Error {
17    Framing(chunk::Error),
18    Field(Conversion),
19    Allocation(alloc::Error),
20    Incomplete,
21}
22
23#[derive(Debug)]
24pub struct Conversion {
25    pub field: usize,
26    pub cause: list::Error,
27}
28
29pub(crate) struct Output<'field> {
30    pub(crate) body: Vec<u8>,
31    pub(crate) trailers: List<'field>,
32}
33
34impl<'field> Output<'field> {
35    pub(crate) fn drain(buf: &[u8], max_body: usize) -> Result<Option<Self>, Error> {
36        let mut decoder = Decoder::with_limit(max_body);
37        let mut body = Vec::new();
38        let mut input = buf;
39
40        loop {
41            let plan = decoder.decode(input)?;
42            match plan.commit(&mut decoder) {
43                Event::NeedMore(_) => return Ok(None),
44                Event::Chunk {
45                    bytes, consumed, ..
46                } => {
47                    // SAFETY: decode just admitted this consumed prefix on
48                    // this unchanged input; the event retains that exact borrow.
49                    input = unsafe { input.get_unchecked(consumed.get()..) };
50                    body.write_slice(bytes).map_err(Error::Allocation)?;
51                }
52                Event::Done { fields, .. } => {
53                    let trailers = Decoder::parse(fields).map_err(Error::Field)?;
54                    return Ok(Some(Self { body, trailers }));
55                }
56            }
57        }
58    }
59}
60
61pub enum Event<'a> {
62    NeedMore(Option<num::NonZero<usize>>),
63    Chunk {
64        consumed: num::NonZero<usize>,
65        bytes: &'a [u8],
66        boundary: chunk::Boundary,
67    },
68    Done {
69        consumed: num::NonZero<usize>,
70        fields: trailer::Fields<'a>,
71    },
72}
73
74pub struct Plan<'a> {
75    event: Prepared<'a>,
76}
77
78enum Prepared<'a> {
79    Event { next: Decoder, event: Event<'a> },
80    Trailer(trailer::Pending<'a>),
81}
82
83impl<'a> Plan<'a> {
84    pub fn commit(self, decoder: &mut Decoder) -> Event<'a> {
85        match self.event {
86            Prepared::Event { next, event } => {
87                *decoder = next;
88                event
89            }
90            Prepared::Trailer(_) => Event::NeedMore(None),
91        }
92    }
93
94    /// Transfers partial trailer admission together with its exact input borrow.
95    /// Retaining that prefix permits later input to be scanned only once.
96    pub fn into_trailer(self) -> Result<trailer::Pending<'a>, Self> {
97        match self.event {
98            Prepared::Trailer(pending) => Ok(pending),
99            event @ Prepared::Event { .. } => Err(Self { event }),
100        }
101    }
102}
103
104#[derive(Clone, Copy)]
105pub struct Decoder {
106    framer: chunk::Framer,
107    max_body: usize,
108}
109
110impl Default for Decoder {
111    fn default() -> Self {
112        Self::new()
113    }
114}
115
116impl Decoder {
117    pub const DEFAULT_MAX_BODY: usize = MAX_BODY_SIZE;
118
119    pub fn new() -> Self {
120        Self::with_limit(MAX_BODY_SIZE)
121    }
122
123    pub fn with_limit(max_body: usize) -> Self {
124        Self {
125            framer: chunk::Framer::new(),
126            max_body,
127        }
128    }
129
130    /// Bounds an emitted body fragment without copying or limiting framing
131    /// progress.
132    pub fn decode_max<'a>(&self, buf: &'a [u8], max: usize) -> Result<Plan<'a>, Error> {
133        let mut next = *self;
134        let event = next
135            .framer
136            .advance(buf, next.max_body, &chunk::Framing::DEFAULT, max)
137            .map_err(Error::Framing)?;
138        let event = match event {
139            chunk::Fragment::Data {
140                consumed,
141                bytes,
142                boundary,
143            } => Event::Chunk {
144                consumed,
145                bytes,
146                boundary,
147            },
148            chunk::Fragment::Trailer(partial) => {
149                return Ok(Plan {
150                    event: Prepared::Trailer(partial),
151                });
152            }
153            chunk::Fragment::Complete {
154                consumed,
155                bytes: lines,
156            } => Event::Done {
157                consumed,
158                fields: trailer::Fields::new(lines),
159            },
160            chunk::Fragment::More(consumed) => Event::NeedMore(num::NonZero::new(consumed)),
161        };
162        Ok(Plan {
163            event: Prepared::Event { next, event },
164        })
165    }
166
167    pub fn decode<'a>(&self, buf: &'a [u8]) -> Result<Plan<'a>, Error> {
168        self.decode_max(buf, usize::MAX)
169    }
170
171    pub(crate) fn require<'field>(buf: &[u8], max_body: usize) -> Result<Output<'field>, Error> {
172        Output::drain(buf, max_body)?.ok_or(Error::Incomplete)
173    }
174
175    pub fn body(buf: &[u8]) -> Result<Option<Vec<u8>>, Error> {
176        Ok(Output::drain(buf, MAX_BODY_SIZE)?.map(|result| result.body))
177    }
178
179    fn parse<'field>(fields: trailer::Fields<'_>) -> Result<List<'field>, Conversion> {
180        let mut trailers = List::new();
181        for (field, (name, value)) in fields.enumerate() {
182            trailers
183                .try_push(name, value)
184                .map_err(|cause| Conversion { field, cause })?;
185        }
186        Ok(trailers)
187    }
188}
189
190const _: () = {
191    assert!(core::mem::size_of::<Error>() <= 5 * core::mem::size_of::<usize>());
192    assert!(!core::mem::needs_drop::<Error>());
193};