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
61
62
63
64
use crate::io::{AsyncCacheRead, PipeError, PipeRead, PipeReadExt};
use crossterm::Command;
use std::time::Duration;
use tokio::io::{AsyncRead, AsyncWrite, AsyncWriteExt};

pub trait PipeWrite: AsyncWrite {}

impl<W: PipeWrite> PipeWriteExt for W {}

pub trait PipeWriteExt: AsyncWrite {
    async fn write_line<T: AsRef<[u8]>>(&mut self, text: T) -> Result<usize, PipeError>
    where
        Self: Unpin,
    {
        // to_vec is used so we dont accidentally trigger
        // flush if user did not wrap writer into BufWriter
        let mut res = text.as_ref().to_vec();
        res.push(b'\n');
        let size = self.write(&res).await?;
        self.flush().await?;
        Ok(size)
    }

    async fn write_line_crlf<T: AsRef<[u8]>>(&mut self, text: T) -> Result<usize, PipeError>
    where
        Self: Unpin,
    {
        let mut res = text.as_ref().to_vec();
        res.push(b'\r');
        res.push(b'\n');
        let size = self.write(&res).await?;
        self.flush().await?;
        Ok(size)
    }

    async fn write_flush<T: AsRef<[u8]>>(&mut self, data: T) -> Result<usize, PipeError>
    where
        Self: Unpin,
    {
        let size = self.write(data.as_ref()).await?;
        self.flush().await?;
        Ok(size)
    }

    async fn write_all_flush<T: AsRef<[u8]>>(&mut self, data: T) -> Result<(), PipeError>
    where
        Self: Unpin,
    {
        self.write_all(data.as_ref()).await?;
        self.flush().await?;
        Ok(())
    }

    async fn write_ansi_command<T: Command>(&mut self, command: T) -> Result<usize, PipeError>
    where
        Self: Unpin,
    {
        let mut ansi_command = String::new();
        command.write_ansi(&mut ansi_command)?;
        let size = self.write(ansi_command.as_bytes()).await?;
        self.flush().await?;
        Ok(size)
    }
}