Skip to content

Commit 31646cc

Browse files
committed
Fix: Improve markdown_v2_escape
Signed-off-by: Muhammad Amin Boubaker <muhammadaminboubaker@gmail.com>
1 parent d706cc5 commit 31646cc

1 file changed

Lines changed: 27 additions & 24 deletions

File tree

src/main.rs

Lines changed: 27 additions & 24 deletions
Original file line numberDiff line numberDiff line change
@@ -641,31 +641,34 @@ async fn handle_gemini(bot: Bot, msg: Message, prompt: String, model: &str) -> R
641641
Ok(())
642642
}
643643

644+
/// Escapes **any** text for safe use with Telegram `MarkdownV2`.
644645
fn markdown_v2_escape(text: &str) -> String {
645-
text.chars()
646-
.map(|c| match c {
647-
'\\' => "\\\\".to_string(),
648-
'[' => "\\[".to_string(),
649-
']' => "\\]".to_string(),
650-
'(' => "\\(".to_string(),
651-
')' => "\\)".to_string(),
652-
'~' => "\\~".to_string(),
653-
'>' => "\\>".to_string(),
654-
'#' => "\\#".to_string(),
655-
'+' => "\\+".to_string(),
656-
'-' => "\\-".to_string(),
657-
'|' => "\\|".to_string(),
658-
'{' => "\\{".to_string(),
659-
'}' => "\\}".to_string(),
660-
'.' => "\\.".to_string(),
661-
'=' => "\\=".to_string(),
662-
'!' => "\\!".to_string(),
663-
'*' => "\\*".to_string(),
664-
'_' => "\\_".to_string(),
665-
'`' => "\\`".to_string(),
666-
_ => c.to_string(),
667-
})
668-
.collect()
646+
let mut escaped = String::with_capacity(text.len() * 2);
647+
for c in text.chars() {
648+
match c {
649+
'\\' => escaped.push_str("\\\\"),
650+
'[' => escaped.push_str("\\["),
651+
']' => escaped.push_str("\\]"),
652+
'(' => escaped.push_str("\\("),
653+
')' => escaped.push_str("\\)"),
654+
'~' => escaped.push_str("\\~"),
655+
'>' => escaped.push_str("\\>"),
656+
'#' => escaped.push_str("\\#"),
657+
'+' => escaped.push_str("\\+"),
658+
'-' => escaped.push_str("\\-"),
659+
'=' => escaped.push_str("\\="),
660+
'|' => escaped.push_str("\\|"),
661+
'{' => escaped.push_str("\\{"),
662+
'}' => escaped.push_str("\\}"),
663+
'.' => escaped.push_str("\\."),
664+
'!' => escaped.push_str("\\!"),
665+
'`' => escaped.push_str("\\`"),
666+
'*' => escaped.push_str("\\*"),
667+
'_' => escaped.push_str("\\_"),
668+
_ => escaped.push(c),
669+
}
670+
}
671+
escaped
669672
}
670673

671674
const MAX_MESSAGE_LENGTH: usize = 4096;

0 commit comments

Comments
 (0)