summaryrefslogtreecommitdiffstats
diff options
context:
space:
mode:
authorToby Vincent <tobyv13@gmail.com>2022-12-02 23:55:46 -0600
committerToby Vincent <tobyv13@gmail.com>2022-12-02 23:55:46 -0600
commitc61ebb37d153d3090e768b975524bd8c4f9258de (patch)
tree71539a1aeeeda76c493568974716deaff7db4e49
parent81516ffa14bc06f91b7e51cafe175cb620dc1be5 (diff)
refactor: simplify nonprintable parsing
-rw-r--r--src/lib.rs40
1 files 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<u8> {
- 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<u8> {
+ let mut buf = Vec::new();
-fn into_ctrl_char(c: u8) -> Vec<u8> {
- vec![b'^', c + 64]
-}
+ if c >= 128 {
+ c -= 128;
+ buf.extend(b"M-");
+ }
-fn into_meta_char(c: u8) -> Vec<u8> {
- 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<u8> {
- vec![b'^', b'?']
+ buf
}