From afb6669477b5ac3432532e9eb9b7d3ca6d51198e Mon Sep 17 00:00:00 2001 From: Lily Ballard Date: Wed, 9 Jan 2019 21:53:57 -0800 Subject: [PATCH] Replace all uses of format!() Previously we were allocating 2 strings per byte, plus another for the offset. Instead we can just write all this directly to stdout. Also replace the calculation of the ANSI escape code for every single byte. This produces a significant speedup. --- src/main.rs | 31 ++++++++++++++++++++++++------- 1 file changed, 24 insertions(+), 7 deletions(-) diff --git a/src/main.rs b/src/main.rs index 0a240fc..be4642a 100644 --- a/src/main.rs +++ b/src/main.rs @@ -78,6 +78,8 @@ struct Printer<'a> { idx: usize, line: Vec, stdout: StdoutLock<'a>, + byte_hex_table: Vec, + byte_char_table: Vec, } impl<'a> Printer<'a> { @@ -86,6 +88,17 @@ impl<'a> Printer<'a> { idx: 1, line: vec![], stdout, + byte_hex_table: (0u8..=u8::max_value()) + .map(|i| format!("{}", Byte(i).color().paint(format!("{:02x} ", i)))) + .collect(), + byte_char_table: (0u8..=u8::max_value()) + .map(|i| { + format!( + "{}", + Byte(i).color().paint(format!("{}", Byte(i).as_char())) + ) + }) + .collect(), } } @@ -109,12 +122,17 @@ impl<'a> Printer<'a> { fn print_byte(&mut self, b: u8) -> io::Result<()> { if self.idx % 16 == 1 { - let offset_str = format!("{:08x}", self.idx - 1); - write!(self.stdout, "│{}│ ", COLOR_OFFSET.paint(offset_str))?; + let style = COLOR_OFFSET.normal(); + write!( + self.stdout, + "│{}{:08x}{}│ ", + style.prefix(), + self.idx - 1, + style.suffix() + )?; } - let byte_str = format!("{:02x} ", b); - write!(self.stdout, "{}", Byte(b).color().paint(byte_str))?; + write!(self.stdout, "{}", self.byte_hex_table[b as usize])?; self.line.push(b); match self.idx % 16 { @@ -150,9 +168,8 @@ impl<'a> Printer<'a> { } let mut idx = 1; - for b in self.line.iter().map(|b| Byte(*b)) { - let chr = format!("{}", b.as_char()); - write!(self.stdout, "{}", b.color().paint(chr)).ok(); + for &b in self.line.iter() { + write!(self.stdout, "{}", self.byte_char_table[b as usize])?; if idx == 8 { write!(self.stdout, "┊").ok();