From cb7cdbf52ee34fedb1dbf16eac9a1084641932ed Mon Sep 17 00:00:00 2001 From: Haydon Ryan Date: Wed, 12 Aug 2026 16:36:52 -0500 Subject: [PATCH] Refactor to avoid multiple string heap allocations --- src/uu/ptx/src/ptx.rs | 28 +++++++++++++++++----------- 1 file changed, 17 insertions(+), 11 deletions(-) diff --git a/src/uu/ptx/src/ptx.rs b/src/uu/ptx/src/ptx.rs index e72c713a081..e8d089b06a0 100644 --- a/src/uu/ptx/src/ptx.rs +++ b/src/uu/ptx/src/ptx.rs @@ -578,19 +578,25 @@ fn get_output_chunks( (tail, before, after, head) } -fn tex_mapper(x: char) -> String { - match x { - '\\' => "\\backslash{}".to_owned(), - '$' | '%' | '#' | '&' | '_' => format!("\\{x}"), - '}' | '{' => format!("$\\{x}$"), - _ => x.to_string(), - } -} - /// Escape special characters for TeX. fn format_tex_field(s: &str) -> String { - let mapped_chunks: Vec = s.chars().map(tex_mapper).collect(); - mapped_chunks.join("") + let mut out = String::with_capacity(s.len()); + for c in s.chars() { + match c { + '\\' => out.push_str("\\backslash{}"), + '$' | '%' | '#' | '&' | '_' => { + out.push('\\'); + out.push(c); + } + '}' | '{' => { + out.push_str("$\\"); + out.push(c); + out.push('$'); + } + _ => out.push(c), + } + } + out } fn format_tex_line(