Skip to main content

buffa/types/
field_payload.rs

1// Modified by ReallyMe Technologies Limited.
2use crate::bytes::{buf::Take, Buf, Bytes};
3
4/// A read-only window over exactly one validated length-delimited field.
5///
6/// Buffa constructs this buffer after checking the field's length against the
7/// input. Overrides of [`super::ProtoBytes::decode_length_delimited`] and
8/// [`super::ProtoString::decode_length_delimited`] can use every [`Buf`] reader,
9/// but cannot widen the window or access the following field. Unread bytes are
10/// skipped by the caller when an override returns successfully.
11///
12/// The underlying buffer and limit are deliberately private. A `Take` would
13/// expose both controls, making the field boundary depend on each override.
14///
15/// ```compile_fail
16/// use buffa::{bytes::Buf, FieldPayload};
17/// fn widen(payload: &mut FieldPayload<impl Buf>) {
18///     payload.set_limit(usize::MAX);
19/// }
20/// ```
21///
22/// ```compile_fail
23/// use buffa::{bytes::Buf, FieldPayload};
24/// fn escape(payload: &mut FieldPayload<impl Buf>) {
25///     payload.get_mut().advance(1);
26/// }
27/// ```
28pub struct FieldPayload<B> {
29    pub(super) inner: Take<B>,
30}
31
32impl<B: Buf> FieldPayload<B> {
33    // The caller has already validated this length against buf.remaining().
34    pub(super) fn new(buf: B, length: usize) -> Self {
35        Self {
36            inner: buf.take(length),
37        }
38    }
39}
40
41impl<B: Buf> Buf for FieldPayload<B> {
42    fn remaining(&self) -> usize {
43        self.inner.remaining()
44    }
45
46    fn chunk(&self) -> &[u8] {
47        self.inner.chunk()
48    }
49
50    #[cfg(feature = "std")]
51    fn chunks_vectored<'a>(&'a self, destination: &mut [std::io::IoSlice<'a>]) -> usize {
52        self.inner.chunks_vectored(destination)
53    }
54
55    fn advance(&mut self, count: usize) {
56        self.inner.advance(count);
57    }
58
59    fn copy_to_bytes(&mut self, length: usize) -> Bytes {
60        // Preserve Bytes' shared-allocation path, with Take enforcing the
61        // boundary before forwarding to the underlying buffer.
62        self.inner.copy_to_bytes(length)
63    }
64}
65
66#[cfg(all(test, feature = "std"))]
67mod tests {
68    use super::*;
69    #[test]
70    fn vectored_chunks_remain_inside_the_validated_window() {
71        let input = b"abc".as_slice().chain(b"def".as_slice());
72        let payload = FieldPayload::new(input, 4);
73        let mut chunks = [std::io::IoSlice::new(&[]), std::io::IoSlice::new(&[])];
74        assert_eq!(payload.chunks_vectored(&mut chunks), 2);
75        assert_eq!(&*chunks[0], b"abc");
76        assert_eq!(&*chunks[1], b"d");
77        assert_eq!(payload.remaining(), 4);
78    }
79}
80
81impl<B> core::fmt::Debug for FieldPayload<B> {
82    fn fmt(&self, formatter: &mut core::fmt::Formatter<'_>) -> core::fmt::Result {
83        formatter.write_str("FieldPayload([REDACTED])")
84    }
85}