compio_io/util/
null.rs

1use compio_buf::{BufResult, IoBufMut};
2
3use crate::{AsyncBufRead, AsyncRead, AsyncWrite, IoResult, util::Splittable};
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
46impl Splittable for Null {
47    type ReadHalf = Null;
48    type WriteHalf = Null;
49
50    fn split(self) -> (Self::ReadHalf, Self::WriteHalf) {
51        (Null { _p: () }, Null { _p: () })
52    }
53}
54
55/// Create a new [`Null`] reader and writer which acts like a black hole.
56///
57/// All reads from and writes to this reader will return
58/// [`BufResult(Ok(0), buf)`] and leave the buffer unchanged.
59///
60/// # Examples
61///
62/// ```
63/// use compio_io::{AsyncRead, AsyncWrite, null};
64///
65/// # compio_runtime::Runtime::new().unwrap().block_on(async {
66/// let mut buf = Vec::with_capacity(10);
67/// let mut null = null();
68///
69/// let (num_read, buf) = null.read(buf).await.unwrap();
70///
71/// assert_eq!(num_read, 0);
72/// assert!(buf.is_empty());
73///
74/// let (num_written, buf) = null.write(buf).await.unwrap();
75/// assert_eq!(num_written, 0);
76/// # })
77/// ```
78///
79/// [`BufResult(Ok(0), buf)`]: compio_buf::BufResult
80#[inline(always)]
81pub fn null() -> Null {
82    Null { _p: () }
83}