1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
use std::{io::Cursor, path::Path};

use color_eyre::eyre::Result;
use tokio::{
    fs::{self, File},
    io::{AsyncWriteExt, BufWriter},
};

#[must_use]
pub struct Writer {
    writer: BufWriter<File>,
}

impl Writer {
    pub async fn new<T>(path: T) -> Result<Self>
    where
        T: AsRef<Path>,
    {
        let parent = path.as_ref().parent().unwrap();
        if !fs::try_exists(parent).await? {
            fs::create_dir_all(parent).await?;
        }

        Ok(Self {
            writer: BufWriter::new(File::create(&path).await?),
        })
    }

    #[inline]
    pub async fn write<T>(&mut self, text: T) -> Result<()>
    where
        T: AsRef<str>,
    {
        let mut buffer = Cursor::new(text.as_ref());
        self.writer.write_all_buf(&mut buffer).await?;
        Ok(())
    }

    #[inline]
    pub async fn ln(&mut self) -> Result<()> {
        self.writer.write_all(b"\n").await?;
        Ok(())
    }

    #[inline]
    pub async fn writeln<T>(&mut self, text: T) -> Result<()>
    where
        T: AsRef<str>,
    {
        self.write(text).await?;
        self.ln().await?;
        Ok(())
    }

    #[inline]
    pub async fn flush(&mut self) -> Result<()> {
        self.writer.flush().await?;
        Ok(())
    }
}