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