Skip to main content

dope_core/io/socket/msg/
raw.rs

1use core::{mem, num::NonZero};
2
3use dope_sys::io::socket::{self, msg, msg::Header};
4use o3::{
5    buffer,
6    depot::array::{self, copy},
7};
8
9use crate::io::transfer;
10
11pub trait Iovec {
12    /// Constructs a retained iovec.
13    /// # Safety
14    /// The bytes stay fixed through terminal completion or quiescence.
15    unsafe fn retain(self) -> msg::Iovec;
16}
17
18impl Iovec for &[u8] {
19    unsafe fn retain(self) -> msg::Iovec {
20        msg::Iovec::from_slice(self)
21    }
22}
23
24pub trait Vectored<'a, const N: usize = { super::MAX_IOVECS }> {
25    /// Constructs a retained descriptor graph.
26    /// # Safety
27    /// The initialized prefix stays fixed, fits `N`/`MAX_IOVECS`, and sums to `bytes`.
28    unsafe fn retain(self) -> super::Vectored<'a, N>;
29}
30
31impl<'a, const N: usize> Vectored<'a, N>
32    for (
33        &'a mut mem::MaybeUninit<Header>,
34        &'a copy::Vec<msg::Iovec, N>,
35        transfer::Len,
36    )
37{
38    unsafe fn retain(self) -> super::Vectored<'a, N> {
39        const { assert!(N <= super::MAX_IOVECS) };
40        let (header, iovecs, bytes) = self;
41        super::Vectored::from_parts(header, iovecs, bytes)
42    }
43}
44
45impl<'a, const N: usize> Vectored<'a, N>
46    for (
47        &'a mut mem::MaybeUninit<Header>,
48        &'a [mem::MaybeUninit<msg::Iovec>; N],
49        array::Len<N>,
50        transfer::Len,
51    )
52{
53    unsafe fn retain(self) -> super::Vectored<'a, N> {
54        const { assert!(N <= super::MAX_IOVECS) };
55        let (header, iovecs, count, bytes) = self;
56        // SAFETY: the caller retains this exact initialized prefix through completion.
57        let iovecs = unsafe { count.prefix(iovecs).assume_init_ref() };
58        super::Vectored::from_parts(header, iovecs, bytes)
59    }
60}
61
62/// Compact exact cursor over one retained iovec graph.
63#[derive(Clone, Copy)]
64pub struct Cursor<'a> {
65    iovecs: &'a [msg::Iovec],
66    index: u32,
67    local: u32,
68    remaining: transfer::Len,
69}
70
71impl<'a> Cursor<'a> {
72    pub const fn bytes(&self) -> transfer::Len {
73        self.remaining
74    }
75
76    fn start<const N: usize>(source: &super::Vectored<'a, N>) -> Self {
77        Self {
78            iovecs: source.iovs,
79            index: 0,
80            local: 0,
81            remaining: source.bytes(),
82        }
83    }
84
85    fn new<const N: usize>(source: &super::Vectored<'a, N>, mut offset: usize) -> Option<Self> {
86        let len = source.bytes().into_raw();
87        if offset > len {
88            return None;
89        }
90        let left = transfer::Len::prefix(len - offset, source.bytes());
91        let iovecs: &'a [msg::Iovec] = source.iovs;
92        let mut index = 0;
93        let mut local = 0_usize;
94        while let Some(iovec) = iovecs.get(index as usize) {
95            if offset < iovec.len() {
96                local = offset;
97                break;
98            }
99            offset -= iovec.len();
100            index += 1;
101        }
102        Some(Self {
103            iovecs,
104            index,
105            local: local as u32,
106            remaining: left,
107        })
108    }
109}
110
111// SAFETY: retained construction proves the iovec graph's exact byte sum and
112// stable backing for 'a; cursor transitions emit each capped prefix once.
113unsafe impl<'a: 'b, 'b> buffer::raw::Scatter<'b> for Cursor<'a> {
114    fn remaining(&self) -> usize {
115        self.remaining.into_raw()
116    }
117
118    unsafe fn advance<const MAX: usize>(
119        &mut self,
120        cap: NonZero<usize>,
121    ) -> buffer::raw::Chunk<'b, MAX> {
122        loop {
123            // SAFETY: admitted nonzero cap proves remaining bytes in this retained graph.
124            let iovec = unsafe { self.iovecs.get_unchecked(self.index as usize) };
125            if iovec.len() == self.local as usize {
126                self.index += 1;
127                self.local = 0;
128                continue;
129            }
130            // SAFETY: the graph retains these bytes for 'a; cursor construction
131            // and transitions keep `local` within this nonempty descriptor.
132            let bytes =
133                unsafe { socket::raw::Iovec::as_slice(iovec).get_unchecked(self.local as usize..) };
134            let len = bytes.len().min(cap.get());
135            self.local += len as u32;
136            let consumed = transfer::Len::prefix(len, self.remaining);
137            self.remaining = self.remaining.abs_diff(consumed);
138            if self.local as usize == iovec.len() {
139                self.index += 1;
140                self.local = 0;
141            }
142            // SAFETY: retained graph construction proves exact length and
143            // stable bytes; the cursor emits one non-empty capped prefix.
144            return unsafe { buffer::raw::Chunk::new(&bytes[..len]) };
145        }
146    }
147}
148
149// SAFETY: Vectored retains its complete descriptor graph for 'a, and each cursor
150// derives its position and remaining length from that same proved graph.
151unsafe impl<'a, const N: usize> buffer::raw::Chunks for super::Vectored<'a, N> {
152    type Cursor<'data>
153        = Cursor<'a>
154    where
155        Self: 'data;
156
157    fn len(&self) -> usize {
158        self.bytes().into_raw()
159    }
160
161    fn chunks(&self) -> Self::Cursor<'_> {
162        Cursor::start(self)
163    }
164
165    fn cursor(&self, offset: usize) -> Option<Self::Cursor<'_>> {
166        Cursor::new(self, offset)
167    }
168}
169
170const _: () = {
171    let state = mem::size_of::<&[msg::Iovec]>() + 3 * mem::size_of::<u32>();
172    let align = mem::align_of::<Cursor<'_>>();
173    let exact = state.div_ceil(align) * align;
174    assert!(mem::size_of::<Cursor<'_>>() == exact);
175};