From fbab5e1bd9528fd1cf3a7d8906167c887b240d7a Mon Sep 17 00:00:00 2001 From: Martin von Zweigbergk Date: Sat, 7 Jan 2023 09:36:19 -0800 Subject: [PATCH] formatter: extract repeated code for writing new color code The implementations of `add_label()` and `remove_label()` had a lot of duplicated code, and we would soon have more duplication if we didn't extract it to shared function. --- src/formatter.rs | 25 ++++++++++++------------- 1 file changed, 12 insertions(+), 13 deletions(-) diff --git a/src/formatter.rs b/src/formatter.rs index 410e0b523..d6e35c8d3 100644 --- a/src/formatter.rs +++ b/src/formatter.rs @@ -164,7 +164,7 @@ fn config_colors(config: &config::Config) -> HashMap { result } -impl ColorFormatter { +impl ColorFormatter { pub fn new(output: W, colors: Arc>) -> ColorFormatter { ColorFormatter { output, @@ -214,6 +214,15 @@ impl ColorFormatter { color } } + + fn write_new_color(&mut self) -> io::Result<()> { + let new_color = self.current_color(); + if new_color != self.current_color { + self.output.write_all(&new_color)?; + self.current_color = new_color; + } + Ok(()) + } } fn color_for_name(color_name: &str) -> Vec { @@ -251,22 +260,12 @@ impl Write for ColorFormatter { impl Formatter for ColorFormatter { fn add_label(&mut self, label: &str) -> io::Result<()> { self.labels.push(label.to_owned()); - let new_color = self.current_color(); - if new_color != self.current_color { - self.output.write_all(&new_color)?; - self.current_color = new_color; - } - Ok(()) + self.write_new_color() } fn remove_label(&mut self) -> io::Result<()> { self.labels.pop(); - let new_color = self.current_color(); - if new_color != self.current_color { - self.output.write_all(&new_color)?; - self.current_color = new_color; - } - Ok(()) + self.write_new_color() } }