Add NoEscapeHTML to jwriter.Writer

This option is similar to json.Encoder.SetEscapeHTML. The default
behavior of false is to escape &, <, and > to \u0026, \u003c, and
\u003e. Setting this to true will not escape these.
This commit is contained in:
Erik Dubbelboer
2017-01-16 06:23:14 +00:00
parent db88438fca
commit daae07b7e6
+10 -5
View File
@@ -23,8 +23,9 @@ const (
type Writer struct {
Flags Flags
Error error
Buffer buffer.Buffer
Error error
Buffer buffer.Buffer
NoEscapeHTML bool
}
// Size returns the size of the data that was written out.
@@ -225,10 +226,14 @@ func (w *Writer) Bool(v bool) {
const chars = "0123456789abcdef"
func isNotEscapedSingleChar(c byte) bool {
func isNotEscapedSingleChar(c byte, escapeHTML bool) bool {
// Note: might make sense to use a table if there are more chars to escape. With 4 chars
// it benchmarks the same.
return c != '<' && c != '\\' && c != '"' && c != '>' && c >= 0x20 && c < utf8.RuneSelf
if escapeHTML {
return c != '<' && c != '>' && c != '&' && c != '\\' && c != '"' && c >= 0x20 && c < utf8.RuneSelf
} else {
return c != '\\' && c != '"' && c >= 0x20 && c < utf8.RuneSelf
}
}
func (w *Writer) String(s string) {
@@ -242,7 +247,7 @@ func (w *Writer) String(s string) {
for i := 0; i < len(s); {
c := s[i]
if isNotEscapedSingleChar(c) {
if isNotEscapedSingleChar(c, !w.NoEscapeHTML) {
// single-width character, no escaping is required
i++
continue