Skip to main content

externally_driven_async_rt/io/
async_write_ext.rs

1use core::future::Future;
2
3use crate::{Context, State, io::AsyncWrite};
4
5/// Helper methods on top of [`AsyncWrite`], implemented for every [`AsyncWrite`].
6pub trait AsyncWriteExt: AsyncWrite {
7    /// Writes the whole given buffer, calling [`AsyncWrite::write`] until it's done.
8    ///
9    /// # Errors
10    ///
11    /// Returns an error if writing fails or if the stream accepts zero bytes.
12    ///
13    /// # Cancel safety
14    ///
15    /// This method is not cancel safe: an unknown number of bytes from `buf` may already be written.
16    fn write_all<
17        'a,
18        S: State,
19        const TASKS: usize,
20        const TASK_SIZE: usize,
21        const ROOT_TASK_SIZE: usize,
22        const TIMERS: usize,
23        const FDS: usize,
24    >(
25        &'a mut self,
26        ctx: &'a Context<'_, S, TASKS, TASK_SIZE, ROOT_TASK_SIZE, TIMERS, FDS>,
27        mut buf: &'a [u8],
28    ) -> impl Future<Output = Result<(), WriteAllError<Self::Error>>> {
29        async move {
30            while !buf.is_empty() {
31                let len = match self.write(ctx, buf).await {
32                    Ok(0) => return Err(WriteAllError::WriteZero),
33                    Ok(len) => len,
34                    Err(err) => return Err(WriteAllError::Io(err)),
35                };
36                let Some(rest) = buf.get(len..) else {
37                    unreachable!("write() reported {len} written bytes out of {}", buf.len());
38                };
39                buf = rest;
40            }
41            Ok(())
42        }
43    }
44}
45
46impl<T: AsyncWrite + ?Sized> AsyncWriteExt for T {}
47
48/// An error returned from [`AsyncWriteExt::write_all`].
49#[derive(Debug, Clone, Copy, PartialEq, Eq)]
50pub enum WriteAllError<E> {
51    /// Writing failed.
52    Io(E),
53    /// The stream accepted zero bytes.
54    WriteZero,
55}
56
57impl<E: core::fmt::Display> core::fmt::Display for WriteAllError<E> {
58    fn fmt(&self, f: &mut core::fmt::Formatter<'_>) -> core::fmt::Result {
59        match self {
60            Self::Io(err) => write!(f, "write failed: {err}"),
61            Self::WriteZero => f.write_str("stream accepted zero bytes"),
62        }
63    }
64}
65
66impl<E: core::error::Error> core::error::Error for WriteAllError<E> {}
67
68#[cfg(test)]
69mod tests {
70    use core::{
71        cell::RefCell,
72        future::{Future, pending, ready},
73        net::SocketAddr,
74        pin::pin,
75        task::{Context, Poll, Waker},
76    };
77
78    use rustix::{
79        io::Errno,
80        net::{AddressFamily, SocketType},
81    };
82
83    use crate::{
84        Selector, State,
85        io::{AsyncWrite, AsyncWriteExt, WriteAllError},
86        net::TcpStream,
87        testing::{EventLoopTestingExt, Log, TestContext, TestLoop, TestStorage, raw_accept},
88    };
89
90    struct Scripted {
91        max_per_call: usize,
92        error: Option<Errno>,
93        written: [u8; 32],
94        len: usize,
95        calls: usize,
96    }
97
98    impl Scripted {
99        const fn new(max_per_call: usize, error: Option<Errno>) -> Self {
100            Self {
101                max_per_call,
102                error,
103                written: [0; 32],
104                len: 0,
105                calls: 0,
106            }
107        }
108
109        fn written(&self) -> &[u8] {
110            &self.written[..self.len]
111        }
112    }
113
114    impl AsyncWrite for Scripted {
115        type Error = Errno;
116
117        fn write<
118            'a,
119            S: State,
120            const TASKS: usize,
121            const TASK_SIZE: usize,
122            const ROOT_TASK_SIZE: usize,
123            const TIMERS: usize,
124            const FDS: usize,
125        >(
126            &'a mut self,
127            _ctx: &'a crate::Context<'_, S, TASKS, TASK_SIZE, ROOT_TASK_SIZE, TIMERS, FDS>,
128            buf: &'a [u8],
129        ) -> impl Future<Output = rustix::io::Result<usize>> {
130            self.calls += 1;
131            if let Some(errno) = self.error {
132                return ready(Err(errno));
133            }
134            let len = buf.len().min(self.max_per_call);
135            self.written[self.len..self.len + len].copy_from_slice(&buf[..len]);
136            self.len += len;
137            ready(Ok(len))
138        }
139
140        fn flush<
141            'a,
142            S: State,
143            const TASKS: usize,
144            const TASK_SIZE: usize,
145            const ROOT_TASK_SIZE: usize,
146            const TIMERS: usize,
147            const FDS: usize,
148        >(
149            &'a mut self,
150            _ctx: &'a crate::Context<'_, S, TASKS, TASK_SIZE, ROOT_TASK_SIZE, TIMERS, FDS>,
151        ) -> impl Future<Output = rustix::io::Result<()>> {
152            ready(Ok(()))
153        }
154    }
155
156    fn write_all(
157        storage: &'static TestStorage,
158        writer: &mut Scripted,
159        buf: &[u8],
160    ) -> Poll<Result<(), WriteAllError<Errno>>> {
161        let selector = Selector::new().unwrap();
162        let state = RefCell::new(Log::default());
163        let ctx: TestContext<'_> = storage.claim(&selector, &state);
164        let mut cx = Context::from_waker(Waker::noop());
165        pin!(writer.write_all(&ctx, buf)).poll(&mut cx)
166    }
167
168    #[test]
169    fn write_all_retries_partial_writes() {
170        let mut writer = Scripted::new(3, None);
171        assert_eq!(
172            write_all(
173                {
174                    static STORAGE: TestStorage = TestStorage::new();
175                    &STORAGE
176                },
177                &mut writer,
178                b"hello world"
179            ),
180            Poll::Ready(Ok(()))
181        );
182        assert_eq!(writer.written(), b"hello world");
183        assert_eq!(writer.calls, 4);
184    }
185
186    #[test]
187    fn write_all_of_nothing_never_writes() {
188        let mut writer = Scripted::new(3, None);
189        assert_eq!(
190            write_all(
191                {
192                    static STORAGE: TestStorage = TestStorage::new();
193                    &STORAGE
194                },
195                &mut writer,
196                b""
197            ),
198            Poll::Ready(Ok(()))
199        );
200        assert_eq!(writer.calls, 0);
201    }
202
203    #[test]
204    fn write_all_fails_when_zero_bytes_are_accepted() {
205        let mut writer = Scripted::new(0, None);
206        assert_eq!(
207            write_all(
208                {
209                    static STORAGE: TestStorage = TestStorage::new();
210                    &STORAGE
211                },
212                &mut writer,
213                b"hello"
214            ),
215            Poll::Ready(Err(WriteAllError::WriteZero))
216        );
217        assert_eq!(writer.calls, 1);
218    }
219
220    #[test]
221    fn write_all_returns_syscall_errors() {
222        let mut writer = Scripted::new(3, Some(Errno::PIPE));
223        assert_eq!(
224            write_all(
225                {
226                    static STORAGE: TestStorage = TestStorage::new();
227                    &STORAGE
228                },
229                &mut writer,
230                b"hello"
231            ),
232            Poll::Ready(Err(WriteAllError::Io(Errno::PIPE)))
233        );
234        assert_eq!(writer.calls, 1);
235    }
236
237    #[test]
238    #[cfg_attr(miri, ignore)]
239    fn write_all_fills_a_socket_beyond_its_buffer() {
240        const LEN: usize = 1 << 20;
241        static DATA: [u8; LEN] = {
242            let mut data = [0; LEN];
243            let mut i = 0;
244            let mut byte = 0;
245            while i < LEN {
246                data[i] = byte;
247                byte = if byte == 250 { 0 } else { byte + 1 };
248                i += 1;
249            }
250            data
251        };
252
253        let listener = crate::testing::raw_socket(AddressFamily::INET, SocketType::STREAM);
254        let localhost = SocketAddr::from(([127, 0, 0, 1], 0));
255        rustix::net::bind(&listener, &localhost).unwrap();
256        rustix::net::listen(&listener, 1).unwrap();
257        let addr: SocketAddr = rustix::net::getsockname(&listener)
258            .unwrap()
259            .try_into()
260            .unwrap();
261
262        let mut selector = Selector::new().unwrap();
263        let mut state = RefCell::new(Log::default());
264        let mut event_loop = TestLoop::new(
265            {
266                static STORAGE: TestStorage = TestStorage::new();
267                &STORAGE
268            },
269            &mut selector,
270            &mut state,
271            async move |ctx| {
272                let mut stream = TcpStream::connect(&ctx, addr).await.unwrap();
273                stream.write_all(&ctx, &DATA).await.unwrap();
274                ctx.dispatch(1);
275                pending::<()>().await;
276            },
277        )
278        .unwrap();
279
280        let peer = raw_accept(&listener);
281        let mut received = [0; 4096];
282        for chunk in DATA.chunks(received.len()) {
283            let received = &mut received[..chunk.len()];
284            event_loop.peer_read_exact(&peer, received);
285            assert_eq!(received, chunk);
286        }
287        event_loop.run_until_events(1);
288        assert_eq!(event_loop.state_mut().events(), [1]);
289    }
290}