Skip to main content

externally_driven_async_rt/io/
async_write_ext.rs

1use core::future::Future;
2
3use crate::Context;
4
5use super::AsyncWrite;
6
7/// Helper methods on top of [`AsyncWrite`], implemented for every [`AsyncWrite`].
8pub trait AsyncWriteExt: AsyncWrite {
9    /// Writes the whole given buffer, calling [`AsyncWrite::write`] until it's done.
10    ///
11    /// # Errors
12    ///
13    /// Returns an error if writing fails or if the stream accepts zero bytes.
14    ///
15    /// # Cancel safety
16    ///
17    /// This method is not cancel safe: an unknown number of bytes from `buf` may already be written.
18    fn write_all<
19        'a,
20        E: 'static,
21        const EVENTS: usize,
22        const TASKS: usize,
23        const TASK_SIZE: usize,
24        const ROOT_TASK_SIZE: usize,
25        const TIMERS: usize,
26        const FDS: usize,
27    >(
28        &'a mut self,
29        ctx: &'a Context<'_, E, EVENTS, TASKS, TASK_SIZE, ROOT_TASK_SIZE, TIMERS, FDS>,
30        mut buf: &'a [u8],
31    ) -> impl Future<Output = Result<(), WriteAllError<Self::Error>>> {
32        async move {
33            while !buf.is_empty() {
34                let len = match self.write(ctx, buf).await {
35                    Ok(0) => return Err(WriteAllError::WriteZero),
36                    Ok(len) => len,
37                    Err(err) => return Err(WriteAllError::Io(err)),
38                };
39                let Some(rest) = buf.get(len..) else {
40                    unreachable!("write() reported {len} written bytes out of {}", buf.len());
41                };
42                buf = rest;
43            }
44            Ok(())
45        }
46    }
47}
48
49impl<T: AsyncWrite + ?Sized> AsyncWriteExt for T {}
50
51/// An error returned from [`AsyncWriteExt::write_all`].
52#[derive(Debug, Clone, Copy, PartialEq, Eq)]
53pub enum WriteAllError<E> {
54    /// Writing failed.
55    Io(E),
56    /// The stream accepted zero bytes.
57    WriteZero,
58}
59
60impl<E: core::fmt::Display> core::fmt::Display for WriteAllError<E> {
61    fn fmt(&self, f: &mut core::fmt::Formatter<'_>) -> core::fmt::Result {
62        match self {
63            Self::Io(err) => write!(f, "write failed: {err}"),
64            Self::WriteZero => f.write_str("stream accepted zero bytes"),
65        }
66    }
67}
68
69impl<E: core::error::Error> core::error::Error for WriteAllError<E> {}
70
71#[cfg(test)]
72mod tests {
73    use core::{
74        future::{Future, ready},
75        pin::pin,
76        task::{Context, Poll, Waker},
77    };
78
79    use rustix::io::Errno;
80
81    use super::{AsyncWrite, AsyncWriteExt, WriteAllError};
82
83    use crate::{LoopStorage, Selector};
84
85    type Storage = LoopStorage<(), 1, 1, 0, 0, 1, 1>;
86
87    struct Scripted {
88        max_per_call: usize,
89        error: Option<Errno>,
90        written: [u8; 32],
91        len: usize,
92        yielding: bool,
93        calls: usize,
94    }
95
96    impl Scripted {
97        const fn new(max_per_call: usize, error: Option<Errno>) -> Self {
98            Self {
99                max_per_call,
100                error,
101                written: [0; 32],
102                len: 0,
103                yielding: false,
104                calls: 0,
105            }
106        }
107
108        const fn yielding(mut self) -> Self {
109            self.yielding = true;
110            self
111        }
112
113        fn written(&self) -> &[u8] {
114            &self.written[..self.len]
115        }
116
117        fn write_now(&mut self, buf: &[u8]) -> rustix::io::Result<usize> {
118            if let Some(errno) = self.error {
119                return Err(errno);
120            }
121            let len = buf.len().min(self.max_per_call);
122            self.written[self.len..self.len + len].copy_from_slice(&buf[..len]);
123            self.len += len;
124            Ok(len)
125        }
126    }
127
128    impl AsyncWrite for Scripted {
129        type Error = Errno;
130
131        fn write<
132            'a,
133            E: 'static,
134            const EVENTS: usize,
135            const TASKS: usize,
136            const TASK_SIZE: usize,
137            const ROOT_TASK_SIZE: usize,
138            const TIMERS: usize,
139            const FDS: usize,
140        >(
141            &'a mut self,
142            _ctx: &'a crate::Context<'_, E, EVENTS, TASKS, TASK_SIZE, ROOT_TASK_SIZE, TIMERS, FDS>,
143            buf: &'a [u8],
144        ) -> impl Future<Output = rustix::io::Result<usize>> {
145            self.calls += 1;
146            let mut pending = self.yielding;
147            core::future::poll_fn(move |cx| {
148                if pending {
149                    pending = false;
150                    cx.waker().wake_by_ref();
151                    return Poll::Pending;
152                }
153                Poll::Ready(self.write_now(buf))
154            })
155        }
156
157        fn flush<
158            'a,
159            E: 'static,
160            const EVENTS: usize,
161            const TASKS: usize,
162            const TASK_SIZE: usize,
163            const ROOT_TASK_SIZE: usize,
164            const TIMERS: usize,
165            const FDS: usize,
166        >(
167            &'a mut self,
168            _ctx: &'a crate::Context<'_, E, EVENTS, TASKS, TASK_SIZE, ROOT_TASK_SIZE, TIMERS, FDS>,
169        ) -> impl Future<Output = rustix::io::Result<()>> {
170            ready(Ok(()))
171        }
172    }
173
174    fn write_all(
175        storage: &'static Storage,
176        writer: &mut Scripted,
177        buf: &[u8],
178    ) -> Poll<Result<(), WriteAllError<Errno>>> {
179        let selector = Selector::new().unwrap();
180        let ctx = storage.claim(&selector).unwrap().0;
181        let mut cx = Context::from_waker(Waker::noop());
182        pin!(writer.write_all(&ctx, buf)).poll(&mut cx)
183    }
184
185    #[test]
186    fn write_all_retries_partial_writes() {
187        static STORAGE: Storage = Storage::new();
188        let mut writer = Scripted::new(3, None);
189        assert_eq!(
190            write_all(&STORAGE, &mut writer, b"hello world"),
191            Poll::Ready(Ok(()))
192        );
193        assert_eq!(writer.written(), b"hello world");
194        assert_eq!(writer.calls, 4);
195    }
196
197    #[test]
198    fn write_all_of_nothing_never_writes() {
199        static STORAGE: Storage = Storage::new();
200        let mut writer = Scripted::new(3, None);
201        assert_eq!(write_all(&STORAGE, &mut writer, b""), Poll::Ready(Ok(())));
202        assert_eq!(writer.calls, 0);
203    }
204
205    #[test]
206    fn write_all_fails_when_zero_bytes_are_accepted() {
207        static STORAGE: Storage = Storage::new();
208        let mut writer = Scripted::new(0, None);
209        assert_eq!(
210            write_all(&STORAGE, &mut writer, b"hello"),
211            Poll::Ready(Err(WriteAllError::WriteZero))
212        );
213        assert_eq!(writer.calls, 1);
214    }
215
216    #[test]
217    fn write_all_returns_syscall_errors() {
218        static STORAGE: Storage = Storage::new();
219        let mut writer = Scripted::new(3, Some(Errno::PIPE));
220        assert_eq!(
221            write_all(&STORAGE, &mut writer, b"hello"),
222            Poll::Ready(Err(WriteAllError::Io(Errno::PIPE)))
223        );
224        assert_eq!(writer.calls, 1);
225    }
226
227    #[test]
228    fn write_all_resumes_after_a_pending_write() {
229        static STORAGE: Storage = Storage::new();
230        let selector = Selector::new().unwrap();
231        let ctx = STORAGE.claim(&selector).unwrap().0;
232        let mut writer = Scripted::new(6, None).yielding();
233        let mut cx = Context::from_waker(Waker::noop());
234        {
235            let mut write = pin!(writer.write_all(&ctx, b"hello world"));
236            assert_eq!(write.as_mut().poll(&mut cx), Poll::Pending);
237            assert_eq!(write.as_mut().poll(&mut cx), Poll::Pending);
238            assert_eq!(write.as_mut().poll(&mut cx), Poll::Ready(Ok(())));
239        }
240        assert_eq!(writer.written(), b"hello world");
241        assert_eq!(writer.calls, 2);
242    }
243}