Skip to main content

sark_http/h1/codec/decode/
trailer.rs

1use core::{mem, num::NonZero};
2
3use chunk::trailer;
4pub use chunk::trailer::Pending;
5use o3::{
6    buffer::{
7        resident,
8        storage::Owned,
9        write::{Sink as _, SpareExt as _, consume},
10    },
11    mem::Rejected,
12};
13
14use crate::{
15    field,
16    h1::{chunk, field::Entry},
17};
18
19/// Append-only ownership of the trailer prefix and its admitted syntax state.
20pub struct State<'d> {
21    source: Owned<resident::Budget<'d>>,
22    parser: trailer::Cursor,
23}
24
25/// Newly admitted input retained with its original owner through capacity growth.
26#[must_use = "append the admitted bytes to transfer their framing proof"]
27pub struct Plan<'input, 'd, P = Phase> {
28    state: State<'d>,
29    bytes: &'input [u8],
30    next: P,
31}
32
33pub struct Phase(Next);
34
35enum Next {
36    More {
37        cursor: trailer::Cursor,
38        consumed: Option<NonZero<usize>>,
39    },
40    Complete(NonZero<usize>),
41}
42
43pub struct More {
44    cursor: trailer::Cursor,
45}
46
47pub struct Ready;
48
49#[must_use]
50pub struct Append<'input, 'd>(Plan<'input, 'd, Ready>);
51
52/// The exact completed trailer owner, excluding the terminating empty line.
53pub struct Complete<'d> {
54    source: Owned<resident::Budget<'d>>,
55}
56
57#[derive(Debug)]
58pub enum StoreError {
59    Prefix(NonZero<usize>),
60    Capacity(consume::Error),
61}
62
63impl Pending<'_> {
64    pub const CAPACITY: usize = chunk::Framing::DEFAULT.trailer_bytes;
65
66    /// Copies the exact borrowed prefix before transferring its parsing proof.
67    pub fn try_store<'d>(
68        self,
69        mut target: Owned<resident::Budget<'d>>,
70    ) -> Result<State<'d>, Rejected<(Self, Owned<resident::Budget<'d>>), StoreError>> {
71        if let Err(error) = StoreError::copy(&mut target, self.bytes) {
72            return Err(Rejected::new((self, target), error));
73        }
74        Ok(State {
75            source: target,
76            parser: self.cursor,
77        })
78    }
79}
80
81impl<'d> State<'d> {
82    pub fn len(&self) -> usize {
83        self.source.len()
84    }
85
86    pub fn is_empty(&self) -> bool {
87        self.source.is_empty()
88    }
89
90    pub fn prepare<'input>(
91        self,
92        input: &'input [u8],
93    ) -> Result<Plan<'input, 'd>, Rejected<Self, chunk::Error>> {
94        let (next, bytes) = match self.parser.scan(input, &chunk::Framing::DEFAULT) {
95            Ok(next) => next,
96            Err(error) => return Err(Rejected::new(self, error)),
97        };
98        let next = match next {
99            trailer::Progress::More { next, consumed } => Next::More {
100                cursor: next,
101                consumed,
102            },
103            trailer::Progress::Complete { consumed, .. } => Next::Complete(consumed),
104        };
105        Ok(Plan {
106            state: self,
107            bytes,
108            next: Phase(next),
109        })
110    }
111}
112
113impl<'input, 'd> Plan<'input, 'd> {
114    pub fn split(
115        self,
116    ) -> Result<
117        (Plan<'input, 'd, Ready>, NonZero<usize>),
118        (Plan<'input, 'd, More>, Option<NonZero<usize>>),
119    > {
120        match self.next.0 {
121            Next::Complete(consumed) => Ok((
122                Plan {
123                    state: self.state,
124                    bytes: self.bytes,
125                    next: Ready,
126                },
127                consumed,
128            )),
129            Next::More { cursor, consumed } => Err((
130                Plan {
131                    state: self.state,
132                    bytes: self.bytes,
133                    next: More { cursor },
134                },
135                consumed,
136            )),
137        }
138    }
139}
140
141impl<'d, P> Plan<'_, 'd, P> {
142    pub fn len(&self) -> usize {
143        self.state.len()
144    }
145
146    pub fn is_empty(&self) -> bool {
147        self.state.is_empty()
148    }
149
150    pub fn cancel(self) -> State<'d> {
151        self.state
152    }
153
154    /// Copies only the retained prefix; the new input's admission remains intact.
155    pub fn try_grow(
156        &mut self,
157        mut target: Owned<resident::Budget<'d>>,
158    ) -> Result<(), Rejected<Owned<resident::Budget<'d>>, StoreError>> {
159        if let Err(error) = StoreError::copy(&mut target, self.state.source.as_slice()) {
160            return Err(Rejected::new(target, error));
161        }
162        self.state.source = target;
163        Ok(())
164    }
165}
166
167impl<'d> Plan<'_, 'd, More> {
168    pub fn try_append(&mut self) -> Result<(), consume::Error> {
169        let mut spare = self.state.source.spare();
170        spare.write_slice(self.bytes)?;
171        spare.commit();
172        self.state.parser = self.next.cursor;
173        self.bytes = &[];
174        Ok(())
175    }
176}
177
178impl<'input, 'd> Plan<'input, 'd, Ready> {
179    /// Borrows completed field lines before appending or releasing either source.
180    pub fn fields(&self) -> [&[u8]; 2] {
181        let prefix = self.state.source.as_slice();
182        let left = prefix.len() - 2usize.saturating_sub(self.bytes.len());
183        let right = self.bytes.len().saturating_sub(2);
184        // SAFETY: Ready is constructed only from the completed trailer phase,
185        // which admitted the final CRLF across this unchanged retained prefix
186        // and exact borrowed input. Removing those two bytes cannot exceed
187        // either source, including a CRLF split between the two owners.
188        unsafe {
189            [
190                prefix.get_unchecked(..left),
191                self.bytes.get_unchecked(..right),
192            ]
193        }
194    }
195
196    pub fn try_append(self) -> Result<Append<'input, 'd>, Rejected<Self, consume::Error>> {
197        let source = &self.state.source;
198        match consume::Error::check(self.bytes.len(), source.capacity() - source.len()) {
199            Ok(()) => Ok(Append(self)),
200            Err(error) => Err(Rejected::new(self, error)),
201        }
202    }
203}
204
205impl<'input, 'd> Append<'input, 'd> {
206    pub fn cancel(self) -> Plan<'input, 'd, Ready> {
207        self.0
208    }
209
210    pub fn commit(self) -> Complete<'d> {
211        let plan = self.0;
212        let mut source = plan.state.source;
213        let start = source.len();
214        let bytes = plan.bytes;
215        // SAFETY: admission retained this exclusive owner with room for all bytes.
216        // Ready proved the final CRLF spans the two disjoint slices.
217        unsafe {
218            if bytes.len() > 2 {
219                bytes
220                    .as_ptr()
221                    .copy_to_nonoverlapping(source.as_mut_ptr().add(start), bytes.len() - 2);
222            }
223            source.set_len(start + bytes.len() - 2);
224        }
225        Complete { source }
226    }
227}
228
229impl<'d> Complete<'d> {
230    pub fn fields(&self) -> Fields<'_> {
231        Fields::new(self.source.as_slice())
232    }
233
234    pub fn into_owner(self) -> Owned<resident::Budget<'d>> {
235        self.source
236    }
237}
238
239impl StoreError {
240    fn copy(target: &mut Owned<resident::Budget<'_>>, bytes: &[u8]) -> Result<(), Self> {
241        if let Some(len) = NonZero::new(target.len()) {
242            return Err(Self::Prefix(len));
243        }
244        target.try_extend(bytes).map_err(Self::Capacity)
245    }
246}
247
248/// Admitted field lines, excluding the section's terminating empty line.
249/// Each retained line has a permitted name, colon, value, and CRLF.
250pub struct Fields<'a> {
251    lines: &'a [u8],
252}
253
254impl<'a> Fields<'a> {
255    pub(super) fn new(lines: &'a [u8]) -> Self {
256        Self { lines }
257    }
258
259    /// Returns the remaining field section without the terminating empty line.
260    pub const fn section(&self) -> &'a [u8] {
261        self.lines
262    }
263}
264
265impl<'a> Iterator for Fields<'a> {
266    type Item = (&'a [u8], &'a [u8]);
267
268    fn next(&mut self) -> Option<Self::Item> {
269        let (name, value, rest) = Entry::split(self.lines)?;
270        self.lines = rest;
271        Some((name, field::Error::trim_ows(value)))
272    }
273}
274
275const _: () = assert!(mem::size_of::<Fields<'_>>() == 2 * mem::size_of::<usize>());