anstyle_stream/
buffer.rs

1/// In-memory [`RawStream`][crate::RawStream]
2#[derive(Clone, Default, Debug, PartialEq, Eq)]
3pub struct Buffer(Vec<u8>);
4
5impl Buffer {
6    #[inline]
7    pub fn new() -> Self {
8        Default::default()
9    }
10
11    #[inline]
12    pub fn with_capacity(capacity: usize) -> Self {
13        Self(Vec::with_capacity(capacity))
14    }
15
16    #[inline]
17    pub fn as_bytes(&self) -> &[u8] {
18        &self.0
19    }
20}
21
22impl AsRef<[u8]> for Buffer {
23    #[inline]
24    fn as_ref(&self) -> &[u8] {
25        self.as_bytes()
26    }
27}
28
29#[cfg(feature = "auto")]
30impl is_terminal::IsTerminal for Buffer {
31    #[inline]
32    fn is_terminal(&self) -> bool {
33        false
34    }
35}
36
37impl std::io::Write for Buffer {
38    #[inline]
39    fn write(&mut self, buf: &[u8]) -> std::io::Result<usize> {
40        self.0.extend(buf);
41        Ok(buf.len())
42    }
43
44    #[inline]
45    fn flush(&mut self) -> std::io::Result<()> {
46        Ok(())
47    }
48}
49
50#[cfg(all(windows, feature = "wincon"))]
51impl anstyle_wincon::WinconStream for Buffer {
52    fn set_colors(
53        &mut self,
54        fg: Option<anstyle::AnsiColor>,
55        bg: Option<anstyle::AnsiColor>,
56    ) -> std::io::Result<()> {
57        use std::io::Write as _;
58
59        if let Some(fg) = fg {
60            write!(self, "{}", fg.render_fg())?;
61        }
62        if let Some(bg) = bg {
63            write!(self, "{}", bg.render_bg())?;
64        }
65        if fg.is_none() && bg.is_none() {
66            write!(self, "{}", anstyle::Reset.render())?;
67        }
68        Ok(())
69    }
70
71    fn get_colors(
72        &self,
73    ) -> std::io::Result<(Option<anstyle::AnsiColor>, Option<anstyle::AnsiColor>)> {
74        Ok((None, None))
75    }
76}