compio_io/util/
null.rs

1use compio_buf::{BufResult, IoBufMut};
2
3use crate::{AsyncBufRead, AsyncRead, AsyncWrite, IoResult};
4
5/// An empty reader and writer constructed via [`null`].
6#[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Hash)]
7pub struct Null {
8    _p: (),
9}
10
11impl AsyncRead for Null {
12    async fn read<B: IoBufMut>(&mut self, buf: B) -> compio_buf::BufResult<usize, B> {
13        BufResult(Ok(0), buf)
14    }
15}
16
17impl AsyncBufRead for Null {
18    async fn fill_buf(&mut self) -> IoResult<&'_ [u8]> {
19        Ok(&[])
20    }
21
22    fn consume(&mut self, _: usize) {}
23}
24
25impl AsyncWrite for Null {
26    async fn write<T: compio_buf::IoBuf>(&mut self, buf: T) -> BufResult<usize, T> {
27        BufResult(Ok(0), buf)
28    }
29
30    async fn write_vectored<T: compio_buf::IoVectoredBuf>(
31        &mut self,
32        buf: T,
33    ) -> BufResult<usize, T> {
34        BufResult(Ok(0), buf)
35    }
36
37    async fn flush(&mut self) -> IoResult<()> {
38        Ok(())
39    }
40
41    async fn shutdown(&mut self) -> IoResult<()> {
42        Ok(())
43    }
44}
45
46/// Create a new [`Null`] reader and writer which acts like a black hole.
47///
48/// All reads from and writes to this reader will return
49/// [`BufResult(Ok(0), buf)`] and leave the buffer unchanged.
50///
51/// # Examples
52///
53/// ```
54/// use compio_io::{AsyncRead, AsyncWrite, null};
55///
56/// # compio_runtime::Runtime::new().unwrap().block_on(async {
57/// let mut buf = Vec::with_capacity(10);
58/// let mut null = null();
59///
60/// let (num_read, buf) = null.read(buf).await.unwrap();
61///
62/// assert_eq!(num_read, 0);
63/// assert!(buf.is_empty());
64///
65/// let (num_written, buf) = null.write(buf).await.unwrap();
66/// assert_eq!(num_written, 0);
67/// # })
68/// ```
69///
70/// [`BufResult(Ok(0), buf)`]: compio_buf::BufResult
71#[inline(always)]
72pub fn null() -> Null {
73    Null { _p: () }
74}