diff --git a/esc.go b/esc.go new file mode 100644 index 00000000..8fa5a79e --- /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 00000000..b1aca633 --- /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