maybe_fut/api/io/
empty.rs

1use std::io::SeekFrom;
2
3use super::{Read, Seek, Write};
4
5/// Empty ignores any data written via [`Write`], and will always be empty (returning zero bytes) when read via [`Read`].
6///
7/// This struct is generally created by calling [`empty`]. Please see the documentation of [`empty`] for more details.
8#[derive(Debug, Clone, Copy, Default)]
9pub struct Empty;
10
11impl Write for Empty {
12    async fn write(&mut self, buf: &[u8]) -> std::io::Result<usize> {
13        // This is a no-op, so we just return the length of the buffer.
14        Ok(buf.len())
15    }
16
17    async fn flush(&mut self) -> std::io::Result<()> {
18        // This is a no-op, so we just return Ok.
19        Ok(())
20    }
21}
22
23impl Seek for Empty {
24    async fn seek(&mut self, _pos: SeekFrom) -> std::io::Result<u64> {
25        // This is a no-op, so we just return Ok(0).
26        Ok(0)
27    }
28}
29
30impl Read for Empty {
31    async fn read(&mut self, _buf: &mut [u8]) -> std::io::Result<usize> {
32        // This is a no-op, so we just return Ok(0).
33        Ok(0)
34    }
35}
36
37/// Creates a new [`Empty`] instance.
38pub fn empty() -> Empty {
39    Empty
40}
41
42#[cfg(test)]
43mod test {
44    use super::*;
45    use crate::api::io::{Read, Write};
46
47    #[tokio::test]
48    async fn test_empty() {
49        let mut empty = empty();
50        let buf = b"Hello, world!";
51        let n = empty.write(buf).await.unwrap();
52        assert_eq!(n, buf.len());
53        assert!(empty.flush().await.is_ok());
54
55        let mut read_buf = [0; 13];
56        let n = empty.read(&mut read_buf).await.unwrap();
57        assert_eq!(n, 0);
58    }
59}