forked from Mirrors/gomuks
hicli/html: deduplicate html escaping code
This commit is contained in:
parent
249dffaa2d
commit
44dee015d4
1 changed files with 23 additions and 40 deletions
|
@ -281,31 +281,33 @@ func linkifyAndWriteBytes(w *strings.Builder, s []byte) {
|
|||
|
||||
const escapedChars = "&'<>\"\r"
|
||||
|
||||
func getEscapeCharacter(b byte) string {
|
||||
switch b {
|
||||
case '&':
|
||||
return "&"
|
||||
case '\'':
|
||||
// "'" is shorter than "'" and apos was not in HTML until HTML5.
|
||||
return "'"
|
||||
case '<':
|
||||
return "<"
|
||||
case '>':
|
||||
return ">"
|
||||
case '"':
|
||||
// """ is shorter than """.
|
||||
return """
|
||||
case '\r':
|
||||
return " "
|
||||
default:
|
||||
panic("unrecognized escape character")
|
||||
}
|
||||
}
|
||||
|
||||
func writeEscapedBytes(w *strings.Builder, s []byte) {
|
||||
i := bytes.IndexAny(s, escapedChars)
|
||||
for i != -1 {
|
||||
w.Write(s[:i])
|
||||
var esc string
|
||||
switch s[i] {
|
||||
case '&':
|
||||
esc = "&"
|
||||
case '\'':
|
||||
// "'" is shorter than "'" and apos was not in HTML until HTML5.
|
||||
esc = "'"
|
||||
case '<':
|
||||
esc = "<"
|
||||
case '>':
|
||||
esc = ">"
|
||||
case '"':
|
||||
// """ is shorter than """.
|
||||
esc = """
|
||||
case '\r':
|
||||
esc = " "
|
||||
default:
|
||||
panic("unrecognized escape character")
|
||||
}
|
||||
w.WriteString(getEscapeCharacter(s[i]))
|
||||
s = s[i+1:]
|
||||
w.WriteString(esc)
|
||||
i = bytes.IndexAny(s, escapedChars)
|
||||
}
|
||||
w.Write(s)
|
||||
|
@ -315,27 +317,8 @@ func writeEscapedString(w *strings.Builder, s string) {
|
|||
i := strings.IndexAny(s, escapedChars)
|
||||
for i != -1 {
|
||||
w.WriteString(s[:i])
|
||||
var esc string
|
||||
switch s[i] {
|
||||
case '&':
|
||||
esc = "&"
|
||||
case '\'':
|
||||
// "'" is shorter than "'" and apos was not in HTML until HTML5.
|
||||
esc = "'"
|
||||
case '<':
|
||||
esc = "<"
|
||||
case '>':
|
||||
esc = ">"
|
||||
case '"':
|
||||
// """ is shorter than """.
|
||||
esc = """
|
||||
case '\r':
|
||||
esc = " "
|
||||
default:
|
||||
panic("unrecognized escape character")
|
||||
}
|
||||
w.WriteString(getEscapeCharacter(s[i]))
|
||||
s = s[i+1:]
|
||||
w.WriteString(esc)
|
||||
i = strings.IndexAny(s, escapedChars)
|
||||
}
|
||||
w.WriteString(s)
|
||||
|
|
Loading…
Add table
Reference in a new issue