use log::*;
use std::io;
use std::io::prelude::*;
use termcolor::ColorSpec;
use termcolor::WriteColor;
pub struct ColorAccumulator {
buf: Vec<u8>,
color: ColorSpec,
}
impl ColorAccumulator {
pub fn new() -> ColorAccumulator {
ColorAccumulator {
buf: Vec::new(),
color: ColorSpec::new(),
}
}
pub fn to_string(self) -> String {
String::from_utf8(self.buf).unwrap()
}
}
impl io::Write for ColorAccumulator {
fn write(&mut self, buf: &[u8]) -> io::Result<usize> {
self.buf.extend(buf);
Ok(buf.len())
}
fn flush(&mut self) -> io::Result<()> {
Ok(())
}
}
impl WriteColor for ColorAccumulator {
fn supports_color(&self) -> bool {
true
}
fn set_color(&mut self, spec: &ColorSpec) -> io::Result<()> {
#![allow(unused_assignments)]
if self.color == *spec {
return Ok(());
} else {
trace!(
"eq={:?} spec={:?} current={:?}",
self.color == *spec,
spec,
self.color
);
self.color = spec.clone();
}
if spec.is_none() {
write!(self, "{{/}}")?;
return Ok(());
} else {
write!(self, "{{")?;
}
let mut first = true;
fn write_first(first: bool, write: &mut ColorAccumulator) -> io::Result<bool> {
if !first {
write!(write, " ")?;
}
Ok(false)
};
if let Some(fg) = spec.fg() {
first = write_first(first, self)?;
write!(self, "fg:{:?}", fg)?;
}
if let Some(bg) = spec.bg() {
first = write_first(first, self)?;
write!(self, "bg:{:?}", bg)?;
}
if spec.bold() {
first = write_first(first, self)?;
write!(self, "bold")?;
}
if spec.underline() {
first = write_first(first, self)?;
write!(self, "underline")?;
}
if spec.intense() {
first = write_first(first, self)?;
write!(self, "bright")?;
}
write!(self, "}}")?;
Ok(())
}
fn reset(&mut self) -> io::Result<()> {
let color = self.color.clone();
if color != ColorSpec::new() {
write!(self, "{{/}}")?;
self.color = ColorSpec::new();
}
Ok(())
}
}