externally_driven_async_rt/io/
frame_writer.rs1use crate::Context;
2
3use super::AsyncWrite;
4
5#[must_use]
14pub struct FrameWriter<W, const N: usize> {
15 inner: W,
16 buf: [u8; N],
17 written: usize,
18}
19
20impl<W: AsyncWrite, const N: usize> FrameWriter<W, N> {
21 pub const fn new(inner: W) -> Self {
23 Self {
24 inner,
25 buf: [0; N],
26 written: N,
27 }
28 }
29
30 pub async fn write_all<
43 E: 'static,
44 const EVENTS: usize,
45 const TASKS: usize,
46 const TASK_SIZE: usize,
47 const ROOT_TASK_SIZE: usize,
48 const TIMERS: usize,
49 const FDS: usize,
50 >(
51 &mut self,
52 ctx: &Context<'_, E, EVENTS, TASKS, TASK_SIZE, ROOT_TASK_SIZE, TIMERS, FDS>,
53 frame: &[u8; N],
54 ) -> Result<(), FrameWriterError<W::Error>> {
55 self.flush(ctx).await?;
56 self.buf = *frame;
57 self.written = 0;
58 Ok(())
59 }
60
61 pub async fn flush<
71 E: 'static,
72 const EVENTS: usize,
73 const TASKS: usize,
74 const TASK_SIZE: usize,
75 const ROOT_TASK_SIZE: usize,
76 const TIMERS: usize,
77 const FDS: usize,
78 >(
79 &mut self,
80 ctx: &Context<'_, E, EVENTS, TASKS, TASK_SIZE, ROOT_TASK_SIZE, TIMERS, FDS>,
81 ) -> Result<(), FrameWriterError<W::Error>> {
82 while self.written < N {
83 let Some(rest) = self.buf.get(self.written..) else {
84 unreachable!("written is below N");
85 };
86 let len = match self.inner.write(ctx, rest).await {
87 Ok(0) => return Err(FrameWriterError::WriteZero),
88 Ok(len) => len,
89 Err(err) => return Err(FrameWriterError::Io(err)),
90 };
91 let Some(written) = self
92 .written
93 .checked_add(len)
94 .filter(|&written| written <= N)
95 else {
96 unreachable!("write() reported more written bytes than the buffer has");
97 };
98 self.written = written;
99 }
100 self.inner.flush(ctx).await.map_err(FrameWriterError::Io)
101 }
102}
103
104#[derive(Debug, Clone, Copy, PartialEq, Eq)]
106pub enum FrameWriterError<E> {
107 Io(E),
109 WriteZero,
111}
112
113impl<E: core::fmt::Display> core::fmt::Display for FrameWriterError<E> {
114 fn fmt(&self, f: &mut core::fmt::Formatter<'_>) -> core::fmt::Result {
115 match self {
116 Self::Io(err) => write!(f, "write failed: {err}"),
117 Self::WriteZero => f.write_str("stream accepted zero bytes"),
118 }
119 }
120}
121
122impl<E: core::error::Error> core::error::Error for FrameWriterError<E> {}
123
124#[cfg(test)]
125mod tests {
126 use core::{
127 future::{Future, poll_fn},
128 pin::pin,
129 task::{Context, Poll, Waker},
130 };
131
132 use rustix::io::Errno;
133
134 use super::{AsyncWrite, FrameWriter, FrameWriterError};
135
136 use crate::{LoopStorage, Selector};
137
138 type Storage = LoopStorage<(), 1, 1, 0, 0, 1, 1>;
139
140 struct Sink {
141 max_per_call: usize,
142 room: usize,
143 error: Option<Errno>,
144 written: [u8; 16],
145 len: usize,
146 flushed: usize,
147 }
148
149 impl Sink {
150 const fn new(max_per_call: usize, room: usize, error: Option<Errno>) -> Self {
151 Self {
152 max_per_call,
153 room,
154 error,
155 written: [0; 16],
156 len: 0,
157 flushed: 0,
158 }
159 }
160
161 fn written(&self) -> &[u8] {
162 &self.written[..self.len]
163 }
164 }
165
166 impl AsyncWrite for Sink {
167 type Error = Errno;
168
169 fn write<
170 'a,
171 E: 'static,
172 const EVENTS: usize,
173 const TASKS: usize,
174 const TASK_SIZE: usize,
175 const ROOT_TASK_SIZE: usize,
176 const TIMERS: usize,
177 const FDS: usize,
178 >(
179 &'a mut self,
180 _ctx: &'a crate::Context<'_, E, EVENTS, TASKS, TASK_SIZE, ROOT_TASK_SIZE, TIMERS, FDS>,
181 buf: &'a [u8],
182 ) -> impl Future<Output = rustix::io::Result<usize>> {
183 poll_fn(move |_| {
184 if let Some(errno) = self.error {
185 return Poll::Ready(Err(errno));
186 }
187 if self.room == 0 {
188 return Poll::Pending;
189 }
190 let len = buf.len().min(self.max_per_call).min(self.room);
191 self.written[self.len..self.len + len].copy_from_slice(&buf[..len]);
192 self.len += len;
193 self.room -= len;
194 Poll::Ready(Ok(len))
195 })
196 }
197
198 fn flush<
199 'a,
200 E: 'static,
201 const EVENTS: usize,
202 const TASKS: usize,
203 const TASK_SIZE: usize,
204 const ROOT_TASK_SIZE: usize,
205 const TIMERS: usize,
206 const FDS: usize,
207 >(
208 &'a mut self,
209 _ctx: &'a crate::Context<'_, E, EVENTS, TASKS, TASK_SIZE, ROOT_TASK_SIZE, TIMERS, FDS>,
210 ) -> impl Future<Output = rustix::io::Result<()>> {
211 self.flushed = self.len;
212 core::future::ready(Ok(()))
213 }
214 }
215
216 fn poll_once<F: Future>(future: F) -> Poll<F::Output> {
217 pin!(future).poll(&mut Context::from_waker(Waker::noop()))
218 }
219
220 #[test]
221 fn writes_frames_on_the_next_write_and_flush() {
222 static STORAGE: Storage = Storage::new();
223 let selector = Selector::new().unwrap();
224 let ctx = STORAGE.claim(&selector).unwrap().0;
225 let mut writer = FrameWriter::<_, 5>::new(Sink::new(2, 16, None));
226
227 assert_eq!(
228 poll_once(writer.write_all(&ctx, b"hello")),
229 Poll::Ready(Ok(()))
230 );
231 assert_eq!(writer.inner.written(), b"");
232 assert_eq!(
233 poll_once(writer.write_all(&ctx, b"world")),
234 Poll::Ready(Ok(()))
235 );
236 assert_eq!(writer.inner.written(), b"hello");
237 assert_eq!(writer.inner.flushed, 5);
238 assert_eq!(poll_once(writer.flush(&ctx)), Poll::Ready(Ok(())));
239 assert_eq!(writer.inner.written(), b"helloworld");
240 assert_eq!(writer.inner.flushed, 10);
241 }
242
243 #[test]
244 fn resumes_a_cancelled_write() {
245 static STORAGE: Storage = Storage::new();
246 let selector = Selector::new().unwrap();
247 let ctx = STORAGE.claim(&selector).unwrap().0;
248 let mut writer = FrameWriter::<_, 5>::new(Sink::new(2, 3, None));
249
250 assert_eq!(
251 poll_once(writer.write_all(&ctx, b"hello")),
252 Poll::Ready(Ok(()))
253 );
254 assert_eq!(poll_once(writer.write_all(&ctx, b"world")), Poll::Pending);
255 assert_eq!(writer.inner.written(), b"hel");
256
257 writer.inner.room = 16;
258 assert_eq!(poll_once(writer.flush(&ctx)), Poll::Ready(Ok(())));
259 assert_eq!(writer.inner.written(), b"hello");
260 assert_eq!(
261 poll_once(writer.write_all(&ctx, b"world")),
262 Poll::Ready(Ok(()))
263 );
264 assert_eq!(poll_once(writer.flush(&ctx)), Poll::Ready(Ok(())));
265 assert_eq!(writer.inner.written(), b"helloworld");
266 }
267
268 #[test]
269 fn fails_when_zero_bytes_are_accepted() {
270 static STORAGE: Storage = Storage::new();
271 let selector = Selector::new().unwrap();
272 let ctx = STORAGE.claim(&selector).unwrap().0;
273 let mut writer = FrameWriter::<_, 5>::new(Sink::new(0, 16, None));
274
275 assert_eq!(
276 poll_once(writer.write_all(&ctx, b"hello")),
277 Poll::Ready(Ok(()))
278 );
279 assert_eq!(
280 poll_once(writer.flush(&ctx)),
281 Poll::Ready(Err(FrameWriterError::WriteZero))
282 );
283 }
284
285 #[test]
286 fn returns_syscall_errors() {
287 static STORAGE: Storage = Storage::new();
288 let selector = Selector::new().unwrap();
289 let ctx = STORAGE.claim(&selector).unwrap().0;
290 let mut writer = FrameWriter::<_, 5>::new(Sink::new(2, 16, Some(Errno::PIPE)));
291
292 assert_eq!(
293 poll_once(writer.write_all(&ctx, b"hello")),
294 Poll::Ready(Ok(()))
295 );
296 assert_eq!(
297 poll_once(writer.flush(&ctx)),
298 Poll::Ready(Err(FrameWriterError::Io(Errno::PIPE)))
299 );
300 }
301}