Skip to main content

sark_http/payload/response/body/
mod.rs

1use std::{
2    borrow::BorrowMut,
3    iter::FusedIterator,
4    ops::{ControlFlow, Range},
5};
6
7use crate::{
8    payload::{owned, response::Destination},
9    request::Id,
10};
11use o3::buffer::{
12    self, hold,
13    resident::{self, bound},
14    segments, storage,
15    write::{self, Sink as _},
16};
17
18mod sources;
19mod store;
20use sources::{Admit, Sealed};
21pub(super) use store::Store;
22
23/// Statically dispatched response payload.
24pub trait Body<'d, Ranges: Copy + 'd = ()>: Sized + Sealed {
25    type Bound: bound::Bound + 'd;
26    type Storage: Store<'d, Ranges, Self>;
27    type Prepared: Into<Option<Self::Storage>>;
28
29    #[doc(hidden)]
30    const INLINE: bool = false;
31
32    fn len(&self) -> usize;
33
34    fn is_empty(&self) -> bool {
35        self.len() == 0
36    }
37
38    fn as_slice(&self) -> Option<&[u8]>;
39
40    fn segments(&self) -> impl FusedIterator<Item: AsRef<[u8]>> {
41        self.as_slice()
42            .filter(|body| !<[u8]>::is_empty(body))
43            .into_iter()
44    }
45
46    #[doc(hidden)]
47    fn try_prepare(self) -> Result<Self::Prepared, owned::Error>;
48
49    #[doc(hidden)]
50    fn try_inline<L: BorrowMut<usize>>(
51        self,
52        _: &mut write::raw::Slice<'_, L>,
53    ) -> Result<ControlFlow<usize, Self::Prepared>, owned::Error> {
54        <Self as Body<'d, Ranges>>::try_prepare(self).map(ControlFlow::Continue)
55    }
56
57    #[doc(hidden)]
58    fn store<'place, const DEFERRED_FIXED: bool, S, D: Destination<'place, 'd, S, Ranges>>(
59        body: Self::Prepared,
60        place: D::Place,
61        current: Option<Id<'d>>,
62    ) -> D::Stored {
63        match body.into() {
64            Some(owner) => {
65                <Self::Storage as Store<'d, Ranges, Self>>::place::<DEFERRED_FIXED, S, D>(
66                    owner, place, current,
67                )
68            }
69            None => D::empty(place),
70        }
71    }
72}
73
74impl<'d, Ranges: Copy + 'd> Body<'d, Ranges> for [u8; 0] {
75    type Bound = bound::AtMost<0>;
76    type Storage = Self;
77    type Prepared = Self;
78
79    const INLINE: bool = true;
80
81    fn len(&self) -> usize {
82        0
83    }
84    fn as_slice(&self) -> Option<&[u8]> {
85        Some(self)
86    }
87    fn try_prepare(self) -> Result<Self, owned::Error> {
88        Ok(self)
89    }
90}
91
92impl<'d, Ranges: Copy + 'd, T> Body<'d, Ranges> for T
93where
94    T: buffer::raw::Source,
95    storage::NonEmpty<T>: Admit + Store<'d, Ranges, T>,
96{
97    type Bound = bound::Unbounded;
98    type Storage = storage::NonEmpty<T>;
99    type Prepared = Option<Self::Storage>;
100
101    const INLINE: bool = <Self::Storage as Admit>::CAN_INLINE;
102
103    fn len(&self) -> usize {
104        self.as_ref().len()
105    }
106
107    fn as_slice(&self) -> Option<&[u8]> {
108        Some(self.as_ref())
109    }
110
111    fn try_prepare(self) -> Result<Self::Prepared, owned::Error> {
112        Ok(storage::NonEmpty::try_new(self).ok())
113    }
114}
115
116impl<'d, Ranges: Copy + 'd> Body<'d, Ranges> for storage::NonEmpty<Vec<u8>> {
117    type Bound = bound::Unbounded;
118    type Storage = Self;
119    type Prepared = Self;
120
121    const INLINE: bool = true;
122
123    fn len(&self) -> usize {
124        self.as_ref().len()
125    }
126    fn is_empty(&self) -> bool {
127        false
128    }
129    fn as_slice(&self) -> Option<&[u8]> {
130        Some(self.as_ref())
131    }
132    fn try_prepare(self) -> Result<Self, owned::Error> {
133        Ok(self)
134    }
135}
136
137impl<'d, Ranges: Copy + 'd> Body<'d, Ranges> for String {
138    type Bound = bound::Unbounded;
139    type Storage = storage::NonEmpty<Vec<u8>>;
140    type Prepared = Option<Self::Storage>;
141
142    const INLINE: bool = true;
143
144    fn len(&self) -> usize {
145        String::len(self)
146    }
147    fn as_slice(&self) -> Option<&[u8]> {
148        Some(self.as_bytes())
149    }
150
151    fn try_prepare(self) -> Result<Self::Prepared, owned::Error> {
152        <Vec<u8> as Body<'d, Ranges>>::try_prepare(self.into_bytes())
153    }
154}
155
156fn copy(bytes: &[u8]) -> Result<Option<storage::NonEmpty<storage::Shared>>, storage::AllocError> {
157    storage::NonEmpty::try_new(bytes)
158        .ok()
159        .map(storage::NonEmpty::<storage::Shared>::try_from)
160        .transpose()
161}
162
163impl<'d, Ranges: Copy + 'd, T: AsRef<[u8]> + ?Sized> Body<'d, Ranges> for &T
164where
165    Self: Sealed,
166{
167    type Bound = bound::Unbounded;
168    type Storage = storage::NonEmpty<storage::Shared>;
169    type Prepared = Option<Self::Storage>;
170
171    const INLINE: bool = true;
172
173    fn len(&self) -> usize {
174        self.as_ref().len()
175    }
176    fn as_slice(&self) -> Option<&[u8]> {
177        Some(self.as_ref())
178    }
179
180    fn try_prepare(self) -> Result<Self::Prepared, owned::Error> {
181        copy(self.as_ref()).map_err(owned::Error::Storage)
182    }
183
184    fn try_inline<L: BorrowMut<usize>>(
185        self,
186        out: &mut write::raw::Slice<'_, L>,
187    ) -> Result<ControlFlow<usize, Self::Prepared>, owned::Error> {
188        let bytes = match storage::NonEmpty::try_new(self.as_ref()) {
189            Ok(bytes) => bytes,
190            Err(_) => return Ok(ControlFlow::Continue(None)),
191        };
192        if out.write_slice(bytes.as_ref()).is_ok() {
193            return Ok(ControlFlow::Break(bytes.len().get()));
194        }
195        storage::NonEmpty::<storage::Shared>::try_from(bytes)
196            .map(|body| ControlFlow::Continue(Some(body)))
197            .map_err(owned::Error::Storage)
198    }
199}
200
201impl<'d, Ranges: Copy + 'd> Body<'d, Ranges> for &mut &[u8] {
202    type Bound = bound::Unbounded;
203    type Storage = storage::NonEmpty<storage::Shared>;
204    type Prepared = Option<Self::Storage>;
205
206    const INLINE: bool = true;
207
208    fn len(&self) -> usize {
209        (**self).len()
210    }
211
212    fn as_slice(&self) -> Option<&[u8]> {
213        Some(**self)
214    }
215
216    fn try_prepare(self) -> Result<Self::Prepared, owned::Error> {
217        copy(self)
218            .map_err(storage::BuildError::from)
219            .map_err(owned::Error::Build)
220    }
221
222    fn try_inline<L: BorrowMut<usize>>(
223        self,
224        out: &mut write::raw::Slice<'_, L>,
225    ) -> Result<ControlFlow<usize, Self::Prepared>, owned::Error> {
226        let bytes = *self;
227        if out.write_slice(bytes).is_ok() {
228            return Ok(ControlFlow::Break(bytes.len()));
229        }
230        <Self as Body<'d, Ranges>>::try_prepare(self).map(ControlFlow::Continue)
231    }
232}
233
234impl<'d, 'input, 'ranges, 'bytes, Ranges: Copy + 'd, N: buffer::raw::Length> Body<'d, Ranges>
235    for &'input mut hold::raw::Set<'ranges, &'bytes [u8], N>
236{
237    type Bound = bound::Unbounded;
238    type Storage = storage::NonEmpty<storage::Shared>;
239    type Prepared = Option<Self::Storage>;
240
241    const INLINE: bool = true;
242
243    fn len(&self) -> usize {
244        hold::raw::Set::len(&**self)
245    }
246
247    fn as_slice(&self) -> Option<&[u8]> {
248        self.contiguous()
249    }
250
251    fn segments(&self) -> impl FusedIterator<Item: AsRef<[u8]>> {
252        hold::raw::Set::iter(&**self)
253    }
254
255    fn try_prepare(self) -> Result<Self::Prepared, owned::Error> {
256        hold::raw::Set::try_copy(self)
257            .map_err(storage::BuildError::from)
258            .map_err(owned::Error::Build)
259    }
260
261    fn try_inline<L: BorrowMut<usize>>(
262        self,
263        out: &mut write::raw::Slice<'_, L>,
264    ) -> Result<ControlFlow<usize, Self::Prepared>, owned::Error> {
265        if let Some(bytes) = self.contiguous()
266            && out.write_slice(bytes).is_ok()
267        {
268            return Ok(ControlFlow::Break(bytes.len()));
269        }
270        <Self as Body<'d, Ranges>>::try_prepare(self).map(ControlFlow::Continue)
271    }
272}
273
274impl<'d, Ranges: Copy + 'd> Body<'d, Ranges> for segments::raw::Data<'d, (), Ranges> {
275    type Bound = bound::Unbounded;
276    type Storage = Self;
277    type Prepared = Self;
278
279    fn len(&self) -> usize {
280        segments::raw::Data::len(self).get()
281    }
282    fn is_empty(&self) -> bool {
283        false
284    }
285    fn as_slice(&self) -> Option<&[u8]> {
286        segments::raw::Data::contiguous(self)
287    }
288
289    fn segments(&self) -> impl FusedIterator<Item: AsRef<[u8]>> {
290        segments::raw::Iter::from(self)
291    }
292
293    fn try_prepare(self) -> Result<Self::Prepared, owned::Error> {
294        Ok(self)
295    }
296}
297
298impl<'d, Inline: Copy, Ranges: Copy + 'd> Body<'d, Ranges>
299    for &mut Option<segments::raw::Data<'d, Inline, Ranges>>
300{
301    type Bound = bound::Unbounded;
302    type Storage = Self;
303    type Prepared = Self;
304
305    const INLINE: bool = true;
306
307    fn len(&self) -> usize {
308        self.as_ref().map_or(0, |body| body.len().get())
309    }
310    fn is_empty(&self) -> bool {
311        self.is_none()
312    }
313    fn as_slice(&self) -> Option<&[u8]> {
314        match self {
315            Some(body) => body.contiguous(),
316            None => Some(&[]),
317        }
318    }
319
320    fn segments(&self) -> impl FusedIterator<Item: AsRef<[u8]>> {
321        self.iter().flat_map(IntoIterator::into_iter)
322    }
323
324    fn try_prepare(self) -> Result<Self::Prepared, owned::Error> {
325        Ok(self)
326    }
327}
328
329impl<'input, 'd, Ranges: Copy + 'd> Body<'d, Ranges> for segments::raw::View<'input, 'd, Ranges> {
330    type Bound = bound::Unbounded;
331    type Storage = segments::raw::Part<'d, Ranges>;
332    type Prepared = Option<Self::Storage>;
333
334    const INLINE: bool = true;
335
336    fn len(&self) -> usize {
337        segments::raw::View::len(self)
338    }
339    fn as_slice(&self) -> Option<&[u8]> {
340        Some(self.as_ref())
341    }
342
343    fn try_prepare(self) -> Result<Self::Prepared, owned::Error> {
344        self.try_project().map_err(owned::Error::Retain)
345    }
346}
347
348impl<'d, Ranges: Copy + 'd> Body<'d, Ranges>
349    for buffer::raw::Input<&mut storage::Shared<resident::State<'d>>, Range<usize>>
350{
351    type Bound = bound::Unbounded;
352    type Storage = storage::NonEmpty<storage::Shared<resident::State<'d>>>;
353    type Prepared = Option<Self::Storage>;
354
355    const INLINE: bool = true;
356
357    fn len(&self) -> usize {
358        let bounds = self.as_parts().1;
359        bounds.end - bounds.start
360    }
361    fn as_slice(&self) -> Option<&[u8]> {
362        Some(self.as_ref())
363    }
364
365    fn try_prepare(self) -> Result<Self::Prepared, owned::Error> {
366        self.try_project().map_err(owned::Error::Retain)
367    }
368}