From 993325d13f751e2c5995fe98e3f8573ea446b23c Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Vytautas=20=C5=A0altenis?= Date: Sat, 10 Sep 2016 14:33:37 +0300 Subject: [PATCH] Roll our own implementation of HTML escaper --- esc.go | 45 +++++++++++++++++++++++++++++++++++++++ esc_test.go | 50 +++++++++++++++++++++++++++++++++++++++++++ html.go | 57 ++++++++++++++++++++++++++------------------------ smartypants.go | 11 +++++----- 4 files changed, 130 insertions(+), 33 deletions(-) create mode 100644 esc.go create mode 100644 esc_test.go diff --git a/esc.go b/esc.go new file mode 100644 index 0000000..8fa5a79 --- /dev/null +++ b/esc.go @@ -0,0 +1,45 @@ +package blackfriday + +import ( + "html" + "io" +) + +type escMap struct { + char byte + seq []byte +} + +var htmlEscaper = []escMap{ + {'&', []byte("&")}, + {'<', []byte("<")}, + {'>', []byte(">")}, + {'"', []byte(""")}, +} + +func escapeHTML(w io.Writer, s []byte) { + var start, end int + var sEnd byte + for end < len(s) { + sEnd = s[end] + if sEnd == '&' || sEnd == '<' || sEnd == '>' || sEnd == '"' { + for i := 0; i < len(htmlEscaper); i++ { + if sEnd == htmlEscaper[i].char { + w.Write(s[start:end]) + w.Write(htmlEscaper[i].seq) + start = end + 1 + break + } + } + } + end++ + } + if start < len(s) && end <= len(s) { + w.Write(s[start:end]) + } +} + +func escLink(w io.Writer, text []byte) { + unesc := html.UnescapeString(string(text)) + escapeHTML(w, []byte(unesc)) +} diff --git a/esc_test.go b/esc_test.go new file mode 100644 index 0000000..b1aca63 --- /dev/null +++ b/esc_test.go @@ -0,0 +1,50 @@ +package blackfriday + +import ( + "bytes" + "testing" +) + +func TestEsc(t *testing.T) { + tests := []string{ + "abc", "abc", + "a&c", "a&c", + "<", "<", + "[]:<", "[]:<", + "Hello