1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
#![feature(specialization)]
#[cfg(feature = "iron")] extern crate iron;
use std::fmt::{self, Write};
pub trait Render {
fn render(&self, &mut fmt::Write) -> fmt::Result;
}
impl<T: fmt::Display + ?Sized> Render for T {
default fn render(&self, w: &mut fmt::Write) -> fmt::Result {
write!(Escaper::new(w), "{}", self)
}
}
impl Render for String {
fn render(&self, w: &mut fmt::Write) -> fmt::Result {
Escaper::new(w).write_str(self)
}
}
impl Render for str {
fn render(&self, w: &mut fmt::Write) -> fmt::Result {
Escaper::new(w).write_str(self)
}
}
pub trait RenderOnce {
fn render_once(self, &mut fmt::Write) -> fmt::Result;
}
impl<'a, T: Render + ?Sized> RenderOnce for &'a T {
fn render_once(self, w: &mut fmt::Write) -> fmt::Result {
Render::render(self, w)
}
}
#[derive(Debug)]
pub struct PreEscaped<T>(pub T);
impl<T: fmt::Display> Render for PreEscaped<T> {
default fn render(&self, w: &mut fmt::Write) -> fmt::Result {
write!(w, "{}", self.0)
}
}
impl Render for PreEscaped<String> {
fn render(&self, w: &mut fmt::Write) -> fmt::Result {
w.write_str(&self.0)
}
}
impl<'a> Render for PreEscaped<&'a str> {
fn render(&self, w: &mut fmt::Write) -> fmt::Result {
w.write_str(self.0)
}
}
pub type Markup = PreEscaped<String>;
impl Markup {
pub fn into_string(self) -> String {
self.0
}
}
pub struct Escaper<W: fmt::Write> {
inner: W,
}
impl<W: fmt::Write> Escaper<W> {
pub fn new(inner: W) -> Escaper<W> {
Escaper { inner: inner }
}
pub fn into_inner(self) -> W {
self.inner
}
}
impl<W: fmt::Write> fmt::Write for Escaper<W> {
fn write_str(&mut self, s: &str) -> fmt::Result {
for c in s.chars() {
try!(match c {
'&' => self.inner.write_str("&"),
'<' => self.inner.write_str("<"),
'>' => self.inner.write_str(">"),
'"' => self.inner.write_str("""),
'\'' => self.inner.write_str("'"),
_ => self.inner.write_char(c),
});
}
Ok(())
}
}
#[cfg(feature = "iron")]
mod iron_support {
use std::io;
use iron::headers::ContentType;
use iron::modifier::{Modifier, Set};
use iron::modifiers::Header;
use iron::response::{Response, ResponseBody, WriteBody};
use Markup;
impl Modifier<Response> for Markup {
fn modify(self, response: &mut Response) {
response
.set_mut(Header(ContentType::html()))
.set_mut(Box::new(self) as Box<WriteBody>);
}
}
impl WriteBody for Markup {
fn write_body(&mut self, body: &mut ResponseBody) -> io::Result<()> {
self.0.write_body(body)
}
}
}