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