From 3b830b0fee51306f0100bb27292fd8dd09bf08f3 Mon Sep 17 00:00:00 2001 From: René Kijewski Date: Thu, 30 Mar 2023 14:12:15 +0200 Subject: Use lookup table --- askama_escape/src/lib.rs | 18 +++++++++++++----- 1 file changed, 13 insertions(+), 5 deletions(-) (limited to 'askama_escape/src') diff --git a/askama_escape/src/lib.rs b/askama_escape/src/lib.rs index ef6c1f9..e09a32d 100644 --- a/askama_escape/src/lib.rs +++ b/askama_escape/src/lib.rs @@ -113,12 +113,20 @@ impl Escaper for Html { { let mut last = 0; for (index, byte) in string.bytes().enumerate() { + const MIN_CHAR: u8 = b'"'; + const MAX_CHAR: u8 = b'>'; + const TABLE: [Option<&&str>; (MAX_CHAR - MIN_CHAR + 1) as usize] = { + let mut table = [None; (MAX_CHAR - MIN_CHAR + 1) as usize]; + table[(b'<' - MIN_CHAR) as usize] = Some(&"<"); + table[(b'>' - MIN_CHAR) as usize] = Some(&">"); + table[(b'&' - MIN_CHAR) as usize] = Some(&"&"); + table[(b'"' - MIN_CHAR) as usize] = Some(&"""); + table[(b'\'' - MIN_CHAR) as usize] = Some(&"'"); + table + }; + let escaped = match byte { - b'<' => Some(&"<"), - b'>' => Some(&">"), - b'&' => Some(&"&"), - b'"' => Some(&"""), - b'\'' => Some(&"'"), + MIN_CHAR..=MAX_CHAR => TABLE[(byte - MIN_CHAR) as usize], _ => None, }; if let Some(escaped) = escaped { -- cgit