mirror of
https://github.com/vlang/v.git
synced 2025-09-13 14:32:26 +03:00
encoding.html: optimize escape performance (#19264)
This commit is contained in:
parent
ed6626dc84
commit
61b219953a
2 changed files with 11 additions and 6 deletions
|
@ -5,15 +5,20 @@ pub struct EscapeConfig {
|
|||
quote bool = true
|
||||
}
|
||||
|
||||
const (
|
||||
html_replacement_table = ['&', '&', '<', '<', '>', '>']
|
||||
html_quote_replacement_table = ['"', '"', "'", '''] // `'"'` is shorter than `'"'`
|
||||
)
|
||||
|
||||
// escape converts special characters in the input, specifically "<", ">", and "&"
|
||||
// to HTML-safe sequences. If `quote` is set to true (which is default), quotes in
|
||||
// HTML will also be translated. Both double and single quotes will be affected.
|
||||
// **Note:** escape() supports funky accents by doing nothing about them. V's UTF-8
|
||||
// support through `string` is robust enough to deal with these cases.
|
||||
pub fn escape(input string, config EscapeConfig) string {
|
||||
tag_free_input := input.replace_each(['&', '&', '<', '<', '>', '>'])
|
||||
tag_free_input := input.replace_each(html.html_replacement_table)
|
||||
return if config.quote {
|
||||
tag_free_input.replace_each(['"', '"', "'", '''])
|
||||
tag_free_input.replace_each(html.html_quote_replacement_table)
|
||||
} else {
|
||||
tag_free_input
|
||||
}
|
||||
|
|
|
@ -5,15 +5,15 @@ fn test_escape_html() {
|
|||
assert html.escape('No change') == 'No change'
|
||||
assert html.escape('<b>Bold text</b>') == '<b>Bold text</b>'
|
||||
assert html.escape('<img />') == '<img />'
|
||||
assert html.escape("' onmouseover='alert(1)'") == '' onmouseover='alert(1)''
|
||||
assert html.escape("<a href='http://www.example.com'>link</a>") == '<a href='http://www.example.com'>link</a>'
|
||||
assert html.escape("<script>alert('hello');</script>") == '<script>alert('hello');</script>'
|
||||
assert html.escape("' onmouseover='alert(1)'") == '' onmouseover='alert(1)''
|
||||
assert html.escape("<a href='http://www.example.com'>link</a>") == '<a href='http://www.example.com'>link</a>'
|
||||
assert html.escape("<script>alert('hello');</script>") == '<script>alert('hello');</script>'
|
||||
// Cases obtained from:
|
||||
// https://github.com/apache/commons-lang/blob/master/src/test/java/org/apache/commons/lang3/StringEscapeUtilsTest.java
|
||||
assert html.escape('plain text') == 'plain text'
|
||||
assert html.escape('') == ''
|
||||
assert html.escape('bread & butter') == 'bread & butter'
|
||||
assert html.escape('"bread" & butter') == '"bread" & butter'
|
||||
assert html.escape('"bread" & butter') == '"bread" & butter'
|
||||
assert html.escape('greater than >') == 'greater than >'
|
||||
assert html.escape('< less than') == '< less than'
|
||||
// Leave accents as-is
|
||||
|
|
Loading…
Add table
Add a link
Reference in a new issue