aboutsummaryrefslogtreecommitdiffstats
path: root/askama_shared/src/escaping.rs
diff options
context:
space:
mode:
authorLibravatar bott <mhpoin@gmail.com>2018-11-05 17:30:26 +0100
committerLibravatar Dirkjan Ochtman <dirkjan@ochtman.nl>2018-11-05 21:03:31 +0100
commit99abc3e303f7c92b1395b0cdb000ea7169963f1c (patch)
treef2cc1c0a1b3d774987d514435945c71bfaf81496 /askama_shared/src/escaping.rs
parent57dc7ef9ca6f093908ad0eabbf81476293e218ed (diff)
downloadaskama-99abc3e303f7c92b1395b0cdb000ea7169963f1c.tar.gz
askama-99abc3e303f7c92b1395b0cdb000ea7169963f1c.tar.bz2
askama-99abc3e303f7c92b1395b0cdb000ea7169963f1c.zip
Improve performance simplify
Diffstat (limited to 'askama_shared/src/escaping.rs')
-rw-r--r--askama_shared/src/escaping.rs52
1 files changed, 20 insertions, 32 deletions
diff --git a/askama_shared/src/escaping.rs b/askama_shared/src/escaping.rs
index 8bb8f0b..6390f0c 100644
--- a/askama_shared/src/escaping.rs
+++ b/askama_shared/src/escaping.rs
@@ -55,46 +55,34 @@ pub struct Escaped<'a> {
bytes: &'a [u8],
}
-enum State {
- Empty,
- Unescaped(usize),
+macro_rules! escaping_body {
+ ($state:ident, $i:ident, $fmt:ident, $_self:ident, $quote:expr) => {{
+ if $state < $i {
+ $fmt.write_str(unsafe { str::from_utf8_unchecked(&$_self.bytes[$state..$i]) })?;
+ }
+ $fmt.write_str($quote)?;
+ $state = $i + 1;
+ }};
}
impl<'a> ::std::fmt::Display for Escaped<'a> {
fn fmt(&self, fmt: &mut fmt::Formatter) -> fmt::Result {
- use self::State::*;
- let mut state = Empty;
+ let mut state = 0;
for (i, b) in self.bytes.iter().enumerate() {
- let next = if b.wrapping_sub(b'"') <= FLAG {
+ if b.wrapping_sub(b'"') <= FLAG {
match *b {
- b'<' => Some("&lt;"),
- b'>' => Some("&gt;"),
- b'&' => Some("&amp;"),
- b'"' => Some("&quot;"),
- b'\'' => Some("&#x27;"),
- b'/' => Some("&#x2f;"),
- _ => None,
- }
- } else {
- None
- };
- state = match (state, next) {
- (Empty, None) => Unescaped(i),
- (s @ Unescaped(_), None) => s,
- (Empty, Some(escaped)) => {
- fmt.write_str(escaped)?;
- Empty
- }
- (Unescaped(start), Some(escaped)) => {
- fmt.write_str(unsafe { str::from_utf8_unchecked(&self.bytes[start..i]) })?;
- fmt.write_str(escaped)?;
- Empty
+ b'<' => escaping_body!(state, i, fmt, self, "&lt;"),
+ b'>' => escaping_body!(state, i, fmt, self, "&gt;"),
+ b'&' => escaping_body!(state, i, fmt, self, "&amp;"),
+ b'"' => escaping_body!(state, i, fmt, self, "&quot;"),
+ b'\'' => escaping_body!(state, i, fmt, self, "&#x27;"),
+ b'/' => escaping_body!(state, i, fmt, self, "&#x2f;"),
+ _ => (),
}
- };
- }
- if let Unescaped(start) = state {
- fmt.write_str(unsafe { str::from_utf8_unchecked(&self.bytes[start..]) })?;
+ }
}
+
+ fmt.write_str(unsafe { str::from_utf8_unchecked(&self.bytes[state..]) })?;
Ok(())
}
}