Skip to main content

qubit_io/traits/
async_byte_output.rs

1// =============================================================================
2//    Copyright (c) 2026 Haixing Hu.
3//
4//    SPDX-License-Identifier: Apache-2.0
5//
6//    Licensed under the Apache License, Version 2.0.
7// =============================================================================
8
9use crate::AsyncOutput;
10
11/// An asynchronous output whose items are bytes.
12///
13/// This trait adds no methods. Every [`AsyncOutput<Item = u8>`](AsyncOutput),
14/// including unsized streams, implements it automatically. Implement
15/// [`AsyncOutput`] to provide the operations; no separate implementation of
16/// `AsyncByteOutput` is needed.
17///
18/// The inherited polling methods retain their pinning and readiness contracts;
19/// implementors do not need to be `Unpin`.
20///
21/// # Examples
22/// `ByteSink` is always ready and stores each written byte in memory:
23///
24/// ```
25/// use std::io;
26/// use std::pin::Pin;
27/// use std::task::Context;
28/// use std::task::Poll;
29/// use std::task::Waker;
30///
31/// use qubit_io::AsyncByteOutput;
32/// use qubit_io::AsyncOutput;
33///
34/// struct ByteSink(Vec<u8>);
35/// impl AsyncOutput for ByteSink {
36///     type Item = u8;
37///     unsafe fn poll_write_unchecked(self: Pin<&mut Self>, _cx: &mut Context<'_>, input: &[u8], index: usize, count: usize) -> Poll<io::Result<usize>> {
38///         let this = self.get_mut();
39///         this.0.extend_from_slice(&input[index..index + count]);
40///         Poll::Ready(Ok(count))
41///     }
42///     fn poll_flush(self: Pin<&mut Self>, _cx: &mut Context<'_>) -> Poll<io::Result<()>> { Poll::Ready(Ok(())) }
43/// }
44/// fn write<S: AsyncByteOutput + ?Sized>(stream: Pin<&mut S>, cx: &mut Context<'_>, input: &[u8]) -> Poll<io::Result<usize>> {
45///     stream.poll_write(cx, input)
46/// }
47/// let mut sink = ByteSink(Vec::new());
48/// let mut cx = Context::from_waker(Waker::noop());
49/// assert!(matches!(write(Pin::new(&mut sink), &mut cx, b"QBIT"), Poll::Ready(Ok(4))));
50/// assert_eq!(sink.0, b"QBIT");
51/// assert!(matches!(Pin::new(&mut sink).poll_flush(&mut cx), Poll::Ready(Ok(()))));
52/// ```
53/// Streams with a different item type do not satisfy this bound:
54///
55/// ```compile_fail
56/// use qubit_io::AsyncByteOutput;
57/// use qubit_io::AsyncOutput;
58///
59/// fn accept(stream: impl AsyncByteOutput) {}
60///
61/// fn reject(stream: impl AsyncOutput<Item = char>) {
62///     accept(stream);
63/// }
64/// ```
65pub trait AsyncByteOutput: AsyncOutput<Item = u8> {
66    // empty
67}
68
69impl<T: AsyncOutput<Item = u8> + ?Sized> AsyncByteOutput for T {}