use crate::buffer::Rgb;
use std::io::Write;
pub struct OutputBuffer {
data: Vec<u8>,
}
impl OutputBuffer {
pub fn with_capacity(capacity: usize) -> Self {
Self {
data: Vec::with_capacity(capacity),
}
}
pub fn new() -> Self {
Self::with_capacity(4096)
}
#[inline]
pub fn clear(&mut self) {
self.data.clear();
}
#[inline]
pub fn as_bytes(&self) -> &[u8] {
&self.data
}
#[inline]
pub const fn len(&self) -> usize {
self.data.len()
}
#[inline]
pub const fn is_empty(&self) -> bool {
self.data.is_empty()
}
#[inline]
pub fn write_raw(&mut self, bytes: &[u8]) {
self.data.extend_from_slice(bytes);
}
#[inline]
pub fn write_str(&mut self, s: &str) {
self.data.extend_from_slice(s.as_bytes());
}
#[inline]
pub fn cursor_move(&mut self, x: u16, y: u16) {
write!(self.data, "\x1b[{};{}H", y + 1, x + 1).unwrap();
}
#[inline]
pub fn cursor_hide(&mut self) {
self.data.extend_from_slice(b"\x1b[?25l");
}
#[inline]
pub fn cursor_show(&mut self) {
self.data.extend_from_slice(b"\x1b[?25h");
}
#[inline]
pub fn set_fg(&mut self, color: Rgb) {
write!(self.data, "\x1b[38;2;{};{};{}m", color.r, color.g, color.b).unwrap();
}
#[inline]
pub fn set_bg(&mut self, color: Rgb) {
write!(self.data, "\x1b[48;2;{};{};{}m", color.r, color.g, color.b).unwrap();
}
#[inline]
pub fn reset_attrs(&mut self) {
self.data.extend_from_slice(b"\x1b[0m");
}
#[inline]
pub fn clear_screen(&mut self) {
self.data.extend_from_slice(b"\x1b[2J");
}
pub fn flush_to<W: Write>(&self, writer: &mut W) -> std::io::Result<()> {
writer.write_all(&self.data)?;
writer.flush()
}
}
impl Default for OutputBuffer {
fn default() -> Self {
Self::new()
}
}