From c61ebb37d153d3090e768b975524bd8c4f9258de Mon Sep 17 00:00:00 2001 From: Toby Vincent Date: Fri, 2 Dec 2022 23:55:46 -0600 Subject: refactor: simplify nonprintable parsing --- src/lib.rs | 40 ++++++++++++++++------------------------ 1 file changed, 16 insertions(+), 24 deletions(-) diff --git a/src/lib.rs b/src/lib.rs index 0d45606..c3665da 100644 --- a/src/lib.rs +++ b/src/lib.rs @@ -28,6 +28,8 @@ Examples: cat f - g Output f's contents, then standard input, then g's contents. cat Copy standard input to standard output."#; +const UNKNOWN_CHAR: &[u8; 2] = b"^?"; + pub fn run(cli: Cli) -> Result<()> { use std::io::{BufReader, Read, Write}; @@ -49,10 +51,10 @@ pub fn run(cli: Cli) -> Result<()> { let mut line = Vec::new(); for c in arr { let parsed = match *c { - b'\t' if cli.opts.show_tabs => vec![b'^', b'I'], - b'\t' => vec![b'\t'], + b'\t' if cli.opts.show_tabs => b"^I".to_vec(), + b'\t' => b"\t".to_vec(), c if cli.opts.show_nonprinting => parse_nonprinting_char(c), - c => vec![c], + c => [c].to_vec(), }; line.extend(parsed) } @@ -79,29 +81,19 @@ pub fn run(cli: Cli) -> Result<()> { Ok(()) } -fn parse_nonprinting_char(c: u8) -> Vec { - match c { - c @ 0..=31 => into_ctrl_char(c), - c @ 32..=126 => vec![c], - 127 => into_unknown_char(), - c @ 128.. => into_meta_char(c), - } -} +fn parse_nonprinting_char(mut c: u8) -> Vec { + let mut buf = Vec::new(); -fn into_ctrl_char(c: u8) -> Vec { - vec![b'^', c + 64] -} + if c >= 128 { + c -= 128; + buf.extend(b"M-"); + } -fn into_meta_char(c: u8) -> Vec { - let mut buf = "M-^".as_bytes().to_vec(); - match c - 128 { - c @ 0..=31 => buf.extend(vec![b'^', c + 64]), - c @ 32..=127 => buf.push(c), - 128.. => buf.extend(into_unknown_char()), + match c { + c @ 0..=31 => buf.extend([b'^', c + 64]), + c @ 32..=126 => buf.push(c), + 127.. => buf.extend(UNKNOWN_CHAR), }; - buf -} -fn into_unknown_char() -> Vec { - vec![b'^', b'?'] + buf } -- cgit v1.2.3-70-g09d2