Skip to main content

sark_http/request/body/
mod.rs

1use std::{iter::FusedIterator, ops::ControlFlow};
2
3use o3::buffer::{
4    bytes::scope,
5    hold::ranges,
6    segments::{self, Source}, storage,
7    write::{Sink as _, SpareExt as _},
8};
9
10use crate::{
11    owner::{handoff, handoff::stage},
12    payload::{
13        owned,
14        response,
15    },
16};
17
18pub mod iter;
19mod retained;
20mod view;
21
22#[doc(hidden)]
23pub use retained::Retained;
24pub use view::View;
25
26#[derive(Clone, Copy, Debug)]
27enum RefStorage<'req, 'd> {
28    Discarded,
29    Empty(&'req [u8]),
30    /// One nonempty slice, admitted by `Ref::from_slice`.
31    Slice(&'req [u8]),
32    Retained(Retained<'req, 'd>),
33    Ranges(&'req ranges::Set<'req, &'req [u8]>),
34}
35
36/// Borrowed logical body preserving transport segmentation.
37#[derive(Clone, Copy, Debug)]
38pub struct Ref<'req, 'd> {
39    storage: RefStorage<'req, 'd>,
40    len: usize,
41}
42
43impl<'req, 'd> Ref<'req, 'd> {
44    /// Classifies an empty view or one nonempty borrowed segment.
45    pub const fn from_slice(bytes: &'req [u8]) -> Self {
46        let storage = if bytes.is_empty() {
47            RefStorage::Empty(bytes)
48        } else {
49            RefStorage::Slice(bytes)
50        };
51        Self {
52            storage,
53            len: bytes.len(),
54        }
55    }
56
57    #[doc(hidden)]
58    pub const fn discarded(len: usize) -> Self {
59        Self {
60            storage: RefStorage::Discarded,
61            len,
62        }
63    }
64
65    #[doc(hidden)]
66    pub const fn from_ranges(ranges: &'req ranges::Set<'req, &'req [u8]>) -> Self {
67        Self {
68            storage: RefStorage::Ranges(ranges),
69            len: ranges.len(),
70        }
71    }
72
73    pub const fn len(&self) -> usize {
74        self.len
75    }
76
77    pub const fn is_empty(&self) -> bool {
78        self.len == 0
79    }
80
81    pub fn count(&self) -> segments::Count {
82        match self.storage {
83            RefStorage::Discarded | RefStorage::Empty(_) => segments::Count::EMPTY,
84            RefStorage::Slice(_) => segments::Count::ONE,
85            RefStorage::Retained(body) => body.count(),
86            RefStorage::Ranges(ranges) => ranges.count(),
87        }
88    }
89
90    pub fn segment(&self, index: usize) -> Option<&'req [u8]> {
91        match self.storage {
92            RefStorage::Discarded | RefStorage::Empty(_) => None,
93            RefStorage::Slice(bytes) => (index == 0).then_some(bytes),
94            RefStorage::Retained(body) => body.segment(index),
95            RefStorage::Ranges(ranges) => ranges.get(index).map(|view| view.as_slice()),
96        }
97    }
98
99    pub fn segments(self) -> iter::Slices<'req, 'd> {
100        iter::Slices::new(self)
101    }
102
103    pub fn as_slice(&self) -> Option<&'req [u8]> {
104        match self.storage {
105            RefStorage::Discarded => None,
106            RefStorage::Empty(bytes) => Some(bytes),
107            RefStorage::Slice(bytes) => Some(bytes),
108            RefStorage::Retained(body) => body.as_slice(),
109            RefStorage::Ranges(ranges) => ranges.contiguous(),
110        }
111    }
112
113    /// Copies the logical body into one exact shared owner.
114    pub fn try_copy(self) -> Result<storage::Shared, owned::Error> {
115        if let RefStorage::Discarded = self.storage {
116            return Err(owned::Error::Discarded);
117        }
118        let mut owner = storage::Owned::try_with(self.len())
119            .map_err(storage::BuildError::from)
120            .map_err(owned::Error::Build)?;
121        let mut out = owner.spare();
122        for part in self.segments() {
123            out.write_slice(part)
124                .map_err(storage::BuildError::Build)
125                .map_err(owned::Error::Build)?;
126        }
127        out.commit();
128        Ok(owner.freeze())
129    }
130
131    pub(crate) const fn try_retained(self) -> Result<Retained<'req, 'd>, Self> {
132        match self.storage {
133            RefStorage::Retained(body) => Ok(body),
134            _ => Err(self),
135        }
136    }
137}
138
139impl<'src, 'd> response::Body<'d> for Ref<'src, 'd> {
140    type Bound = o3::buffer::resident::bound::Unbounded;
141    type Selected<S, B> = handoff::Selection<'d, S, B>;
142
143    const INLINE: bool = true;
144
145    fn len(&self) -> usize {
146        self.len
147    }
148
149    fn as_slice(&self) -> Option<&[u8]> {
150        Self::as_slice(self)
151    }
152
153    fn segments(&self) -> impl Iterator<Item = &[u8]> + FusedIterator {
154        iter::Slices::new(*self)
155    }
156
157    fn try_resolve<'req, H: scope::Source, O: stage::Body<'req, 'd>>(
158        self,
159        slot: &handoff::Slot<'req, 'd, H, O>,
160    ) -> Result<Self::Selected<H::Selection, O>, owned::Error> {
161        handoff::Selection::try_view(slot, self)
162    }
163
164    fn try_resolve_into<
165        'req,
166        H: scope::Source,
167        O: stage::Body<'req, 'd>,
168        L: std::borrow::BorrowMut<usize>,
169    >(
170        self,
171        slot: &handoff::Slot<'req, 'd, H, O>,
172        out: &mut o3::buffer::write::Slice<'_, L>,
173    ) -> Result<ControlFlow<usize, handoff::Selection<'d, H::Selection, O>>, owned::Error> {
174        if matches!(self.storage, RefStorage::Slice(_) | RefStorage::Ranges(_))
175            && let Some(bytes) = self.as_slice()
176            && let Some(written) = handoff::copy::into(out, bytes)
177        {
178            return Ok(ControlFlow::Break(written));
179        }
180        self.try_resolve(slot).map(ControlFlow::Continue)
181    }
182}
183
184const _: () = {
185    assert!(core::mem::size_of::<Ref<'static, 'static>>() == 4 * core::mem::size_of::<usize>());
186};
187
188impl<'req, 'd> From<&'req Source<'d>> for Ref<'req, 'd> {
189    fn from(body: &'req Source<'d>) -> Self {
190        Self {
191            storage: RefStorage::Retained(Retained::Segments(body)),
192            len: body.len(),
193        }
194    }
195}