Skip to main content

externally_driven_async_rt/io/
frame_writer.rs

1use crate::{Context, State, io::AsyncWrite};
2
3/// Writes frames of exactly `N` bytes to an [`AsyncWrite`].
4///
5/// A frame is accepted as a whole and a partially written frame is kept inside, so unlike
6/// [`AsyncWriteExt::write_all`](crate::io::AsyncWriteExt::write_all) writing a frame can be
7/// cancelled and resumed.
8///
9/// A frame that is not fully written yet is lost when this value is dropped, call
10/// [`flush`](Self::flush) to avoid it.
11#[must_use]
12pub struct FrameWriter<W, const N: usize> {
13    inner: W,
14    buf: [u8; N],
15    written: usize,
16}
17
18impl<W: AsyncWrite, const N: usize> FrameWriter<W, N> {
19    /// Wraps a given writer.
20    pub const fn new(inner: W) -> Self {
21        Self {
22            inner,
23            buf: [0; N],
24            written: N,
25        }
26    }
27
28    /// Finishes writing the previous frame and accepts `frame` as the next one.
29    ///
30    /// `frame` is written by the next call to [`write_all`](Self::write_all) or
31    /// [`flush`](Self::flush).
32    ///
33    /// # Errors
34    ///
35    /// Returns an error if writing fails or if the stream accepts zero bytes.
36    ///
37    /// # Cancel safety
38    ///
39    /// This method is cancel safe.
40    pub async fn write_all<
41        S: State,
42        const TASKS: usize,
43        const TASK_SIZE: usize,
44        const ROOT_TASK_SIZE: usize,
45        const TIMERS: usize,
46        const FDS: usize,
47    >(
48        &mut self,
49        ctx: &Context<'_, S, TASKS, TASK_SIZE, ROOT_TASK_SIZE, TIMERS, FDS>,
50        frame: &[u8; N],
51    ) -> Result<(), FrameWriterError<W::Error>> {
52        self.flush(ctx).await?;
53        self.buf = *frame;
54        self.written = 0;
55        Ok(())
56    }
57
58    /// Finishes writing the last accepted frame and flushes the wrapped writer.
59    ///
60    /// # Errors
61    ///
62    /// Returns an error if writing fails or if the stream accepts zero bytes.
63    ///
64    /// # Cancel safety
65    ///
66    /// This method is cancel safe.
67    pub async fn flush<
68        S: State,
69        const TASKS: usize,
70        const TASK_SIZE: usize,
71        const ROOT_TASK_SIZE: usize,
72        const TIMERS: usize,
73        const FDS: usize,
74    >(
75        &mut self,
76        ctx: &Context<'_, S, TASKS, TASK_SIZE, ROOT_TASK_SIZE, TIMERS, FDS>,
77    ) -> Result<(), FrameWriterError<W::Error>> {
78        while self.written < N {
79            let Some(rest) = self.buf.get(self.written..) else {
80                unreachable!("written is below N");
81            };
82            let len = match self.inner.write(ctx, rest).await {
83                Ok(0) => return Err(FrameWriterError::WriteZero),
84                Ok(len) => len,
85                Err(err) => return Err(FrameWriterError::Io(err)),
86            };
87            let Some(written) = self
88                .written
89                .checked_add(len)
90                .filter(|&written| written <= N)
91            else {
92                unreachable!("write() reported more written bytes than the buffer has");
93            };
94            self.written = written;
95        }
96        self.inner.flush(ctx).await.map_err(FrameWriterError::Io)
97    }
98}
99
100impl<W, const N: usize> core::fmt::Debug for FrameWriter<W, N> {
101    fn fmt(&self, f: &mut core::fmt::Formatter<'_>) -> core::fmt::Result {
102        f.write_str("FrameWriter")
103    }
104}
105
106/// An error returned from [`FrameWriter::write_all`] and [`FrameWriter::flush`].
107#[derive(Debug, Clone, Copy, PartialEq, Eq)]
108pub enum FrameWriterError<E> {
109    /// Writing failed.
110    Io(E),
111    /// The stream accepted zero bytes.
112    WriteZero,
113}
114
115impl<E: core::fmt::Display> core::fmt::Display for FrameWriterError<E> {
116    fn fmt(&self, f: &mut core::fmt::Formatter<'_>) -> core::fmt::Result {
117        match self {
118            Self::Io(err) => write!(f, "write failed: {err}"),
119            Self::WriteZero => f.write_str("stream accepted zero bytes"),
120        }
121    }
122}
123
124impl<E: core::error::Error> core::error::Error for FrameWriterError<E> {}
125
126#[cfg(test)]
127mod tests {
128    use core::{
129        cell::RefCell,
130        future::{Future, poll_fn},
131        pin::pin,
132        task::{Context, Poll, Waker},
133    };
134
135    use rustix::io::Errno;
136
137    use crate::{
138        Selector, State,
139        io::{AsyncWrite, FrameWriter, FrameWriterError},
140        testing::{Log, TestContext, TestStorage},
141    };
142
143    struct Sink {
144        max_per_call: usize,
145        room: usize,
146        error: Option<Errno>,
147        written: [u8; 16],
148        len: usize,
149        flushed: usize,
150    }
151
152    impl Sink {
153        const fn new(max_per_call: usize, room: usize, error: Option<Errno>) -> Self {
154            Self {
155                max_per_call,
156                room,
157                error,
158                written: [0; 16],
159                len: 0,
160                flushed: 0,
161            }
162        }
163
164        fn written(&self) -> &[u8] {
165            &self.written[..self.len]
166        }
167    }
168
169    impl AsyncWrite for Sink {
170        type Error = Errno;
171
172        fn write<
173            'a,
174            S: State,
175            const TASKS: usize,
176            const TASK_SIZE: usize,
177            const ROOT_TASK_SIZE: usize,
178            const TIMERS: usize,
179            const FDS: usize,
180        >(
181            &'a mut self,
182            _ctx: &'a crate::Context<'_, S, TASKS, TASK_SIZE, ROOT_TASK_SIZE, TIMERS, FDS>,
183            buf: &'a [u8],
184        ) -> impl Future<Output = rustix::io::Result<usize>> {
185            poll_fn(move |_| {
186                if let Some(errno) = self.error {
187                    return Poll::Ready(Err(errno));
188                }
189                if self.room == 0 {
190                    return Poll::Pending;
191                }
192                let len = buf.len().min(self.max_per_call).min(self.room);
193                self.written[self.len..self.len + len].copy_from_slice(&buf[..len]);
194                self.len += len;
195                self.room -= len;
196                Poll::Ready(Ok(len))
197            })
198        }
199
200        fn flush<
201            'a,
202            S: State,
203            const TASKS: usize,
204            const TASK_SIZE: usize,
205            const ROOT_TASK_SIZE: usize,
206            const TIMERS: usize,
207            const FDS: usize,
208        >(
209            &'a mut self,
210            _ctx: &'a crate::Context<'_, S, TASKS, TASK_SIZE, ROOT_TASK_SIZE, TIMERS, FDS>,
211        ) -> impl Future<Output = rustix::io::Result<()>> {
212            self.flushed = self.len;
213            core::future::ready(Ok(()))
214        }
215    }
216
217    fn poll_once<F: Future>(future: F) -> Poll<F::Output> {
218        pin!(future).poll(&mut Context::from_waker(Waker::noop()))
219    }
220
221    #[test]
222    fn writes_frames_on_the_next_write_and_flush() {
223        static STORAGE: TestStorage = TestStorage::new();
224        let selector = Selector::new().unwrap();
225        let state = RefCell::new(Log::default());
226        let ctx: TestContext<'_> = STORAGE.claim(&selector, &state);
227        let mut writer = FrameWriter::<_, 5>::new(Sink::new(2, 16, None));
228
229        assert_eq!(
230            poll_once(writer.write_all(&ctx, b"hello")),
231            Poll::Ready(Ok(()))
232        );
233        assert_eq!(writer.inner.written(), b"");
234        assert_eq!(
235            poll_once(writer.write_all(&ctx, b"world")),
236            Poll::Ready(Ok(()))
237        );
238        assert_eq!(writer.inner.written(), b"hello");
239        assert_eq!(writer.inner.flushed, 5);
240        assert_eq!(poll_once(writer.flush(&ctx)), Poll::Ready(Ok(())));
241        assert_eq!(writer.inner.written(), b"helloworld");
242        assert_eq!(writer.inner.flushed, 10);
243    }
244
245    #[test]
246    fn resumes_a_cancelled_write() {
247        static STORAGE: TestStorage = TestStorage::new();
248        let selector = Selector::new().unwrap();
249        let state = RefCell::new(Log::default());
250        let ctx: TestContext<'_> = STORAGE.claim(&selector, &state);
251        let mut writer = FrameWriter::<_, 5>::new(Sink::new(2, 3, None));
252
253        assert_eq!(
254            poll_once(writer.write_all(&ctx, b"hello")),
255            Poll::Ready(Ok(()))
256        );
257        assert_eq!(poll_once(writer.write_all(&ctx, b"world")), Poll::Pending);
258        assert_eq!(writer.inner.written(), b"hel");
259
260        writer.inner.room = 16;
261        assert_eq!(poll_once(writer.flush(&ctx)), Poll::Ready(Ok(())));
262        assert_eq!(writer.inner.written(), b"hello");
263        assert_eq!(
264            poll_once(writer.write_all(&ctx, b"world")),
265            Poll::Ready(Ok(()))
266        );
267        assert_eq!(poll_once(writer.flush(&ctx)), Poll::Ready(Ok(())));
268        assert_eq!(writer.inner.written(), b"helloworld");
269    }
270
271    #[test]
272    fn fails_when_zero_bytes_are_accepted() {
273        static STORAGE: TestStorage = TestStorage::new();
274        let selector = Selector::new().unwrap();
275        let state = RefCell::new(Log::default());
276        let ctx: TestContext<'_> = STORAGE.claim(&selector, &state);
277        let mut writer = FrameWriter::<_, 5>::new(Sink::new(0, 16, None));
278
279        assert_eq!(
280            poll_once(writer.write_all(&ctx, b"hello")),
281            Poll::Ready(Ok(()))
282        );
283        assert_eq!(
284            poll_once(writer.flush(&ctx)),
285            Poll::Ready(Err(FrameWriterError::WriteZero))
286        );
287    }
288
289    #[test]
290    fn returns_syscall_errors() {
291        static STORAGE: TestStorage = TestStorage::new();
292        let selector = Selector::new().unwrap();
293        let state = RefCell::new(Log::default());
294        let ctx: TestContext<'_> = STORAGE.claim(&selector, &state);
295        let mut writer = FrameWriter::<_, 5>::new(Sink::new(2, 16, Some(Errno::PIPE)));
296
297        assert_eq!(
298            poll_once(writer.write_all(&ctx, b"hello")),
299            Poll::Ready(Ok(()))
300        );
301        assert_eq!(
302            poll_once(writer.flush(&ctx)),
303            Poll::Ready(Err(FrameWriterError::Io(Errno::PIPE)))
304        );
305    }
306}