diff options
Diffstat (limited to '')
-rw-r--r-- | askama_shared/src/escaping.rs | 43 |
1 files changed, 43 insertions, 0 deletions
diff --git a/askama_shared/src/escaping.rs b/askama_shared/src/escaping.rs index 54f58e4..ed4b3d7 100644 --- a/askama_shared/src/escaping.rs +++ b/askama_shared/src/escaping.rs @@ -1,3 +1,46 @@ +use std::fmt::{self, Display, Formatter}; + + +#[derive(Debug, PartialEq)] +pub enum MarkupDisplay<T> where T: Display { + Safe(T), + Unsafe(T), +} + +impl<T> MarkupDisplay<T> where T: Display { + pub fn mark_safe(self) -> MarkupDisplay<T> { + match self { + MarkupDisplay::Unsafe(t) => MarkupDisplay::Safe(t), + _ => { self }, + } + } + pub fn unsafe_string(&self) -> String { + match *self { + MarkupDisplay::Safe(ref t) | MarkupDisplay::Unsafe(ref t) => format!("{}", t) + } + } +} + +impl<T> From<T> for MarkupDisplay<T> where T: Display { + fn from(t: T) -> MarkupDisplay<T> { + MarkupDisplay::Unsafe(t) + } +} + +impl<T> Display for MarkupDisplay<T> where T: Display { + fn fmt(&self, f: &mut Formatter) -> fmt::Result { + match *self { + MarkupDisplay::Unsafe(_) => { + write!(f, "{}", escape(self.unsafe_string())) + }, + MarkupDisplay::Safe(ref t) => { + t.fmt(f) + }, + } + } +} + + fn escapable(b: &u8) -> bool { *b == b'<' || *b == b'>' || *b == b'&' } |