vow/async/
async_std.rs

1use async_std::{
2    fs::{File, OpenOptions},
3    io::{ReadExt, SeekExt, SeekFrom, WriteExt},
4};
5use std::path::Path;
6
7use crate::VowFileAsync;
8
9impl VowFileAsync for File {
10    fn open(path: &Path) -> impl super::IoFut<Self>
11    where
12        Self: Sized,
13    {
14        OpenOptions::new()
15            .write(true)
16            .create(true)
17            .truncate(false)
18            .open(path)
19    }
20
21    fn read(&mut self, mut buf: Vec<u8>) -> impl super::BufFut {
22        async move {
23            let res = self.read_to_end(&mut buf).await.map(|_| ());
24            (res, buf)
25        }
26    }
27
28    fn write(&mut self, buf: Vec<u8>) -> impl super::BufFut {
29        async move {
30            let res = self.write_all(&buf).await;
31            (res, buf)
32        }
33    }
34
35    fn flush(&mut self) -> impl super::IoFut<()> {
36        async move {
37            <Self as WriteExt>::flush(self).await?;
38            Ok(())
39        }
40    }
41
42    fn set_len(&mut self, len: u64) -> impl super::IoFut<()> {
43        async move {
44            self.seek(SeekFrom::Start(len)).await?;
45            Self::set_len(self, len).await?;
46            Ok(())
47        }
48    }
49}
50
51#[cfg(test)]
52mod test {
53    use crate::VowFileAsync;
54    use async_std::io::ReadExt;
55
56    #[async_std::test]
57    async fn test_write() {
58        let mut file = async_std::fs::File::create("/tmp/async-std").await.unwrap();
59        let (res, _) =
60            VowFileAsync::write(&mut file, b"{\"a\":43,\"b\":\"async std!\"}".to_vec()).await;
61
62        res.unwrap();
63
64        let mut buf = vec![];
65        file.read_to_end(&mut buf).await.unwrap();
66
67        assert_eq!(buf, b"{\"a\":43,\"b\":\"async std!\"}");
68    }
69}