manen

Fancy Lua REPL
Log | Files | Refs | README | LICENSE

commit 5ed134beca06dea8437e6b44280a91bfbd96cc74
parent f4354cbb9f46e00ee4831657d32095d50758798f
Author: Sylvia Ivory <git@sivory.net>
Date:   Sun, 22 Jun 2025 18:19:22 -0700

Reuse AhoCorasick

Diffstat:
MCargo.lock | 1+
MCargo.toml | 1+
Msrc/inspect.rs | 63+++++++++++++++++++++++++++++++++++----------------------------
3 files changed, 37 insertions(+), 28 deletions(-)

diff --git a/Cargo.lock b/Cargo.lock @@ -492,6 +492,7 @@ dependencies = [ "clap", "color-eyre", "comfy-table", + "lazy_static", "mlua", "nu-ansi-term", "reedline", diff --git a/Cargo.toml b/Cargo.toml @@ -8,6 +8,7 @@ aho-corasick = "1.1.3" clap = { version = "4.5.40", features = ["derive"] } color-eyre = "0.6.5" comfy-table = "7.1.4" +lazy_static = "1.5.0" mlua = { version = "0.10.5", features = ["lua54", "vendored", "anyhow", "send"] } nu-ansi-term = "0.50.1" reedline = "0.40.0" diff --git a/src/inspect.rs b/src/inspect.rs @@ -1,38 +1,45 @@ use aho_corasick::AhoCorasick; +use lazy_static::lazy_static; use mlua::prelude::*; -fn escape_control(s: &str) -> String { - let mut escapes = vec![ - String::from("\x07"), - String::from("\x08"), - String::from("\x0C"), - String::from("\n"), - String::from("\r"), - String::from("\t"), - String::from("\x0B"), - String::from("\x7F"), - ]; +lazy_static! { + static ref AC_REPLACEMENTS: (AhoCorasick, Vec<String>) = { + let mut escapes = vec![ + String::from("\x07"), + String::from("\x08"), + String::from("\x0C"), + String::from("\n"), + String::from("\r"), + String::from("\t"), + String::from("\x0B"), + String::from("\x7F"), + ]; - let mut replacements = vec![ - String::from("\\a"), - String::from("\\b"), - String::from("\\f"), - String::from("\\n"), - String::from("\\r"), - String::from("\\t"), - String::from("\\v"), - String::from("\\127"), - ]; + let mut replacements = vec![ + String::from("\\a"), + String::from("\\b"), + String::from("\\f"), + String::from("\\n"), + String::from("\\r"), + String::from("\\t"), + String::from("\\v"), + String::from("\\127"), + ]; - for i in 0..=31 { - escapes.push(String::from_utf8_lossy(&[i]).to_string()); - replacements.push(format!("\\{i}")); - } + for i in 0..=31 { + escapes.push(String::from_utf8_lossy(&[i]).to_string()); + replacements.push(format!("\\{i}")); + } - // TODO; reuse - let ac = AhoCorasick::new(escapes).unwrap(); + (AhoCorasick::new(escapes).unwrap(), replacements) + }; + static ref ESCAPER: &'static AhoCorasick = &AC_REPLACEMENTS.0; +} - ac.replace_all(s, &replacements).replace("\\\\x", "\\x") +fn escape_control(s: &str) -> String { + ESCAPER + .replace_all(s, &AC_REPLACEMENTS.1) + .replace("\\\\x", "\\x") } fn remove_invalid(mut bytes: &[u8]) -> String {