summaryrefslogtreecommitdiff
path: root/misc.go
diff options
context:
space:
mode:
Diffstat (limited to 'misc.go')
-rw-r--r--misc.go55
1 files changed, 34 insertions, 21 deletions
diff --git a/misc.go b/misc.go
index 4d8b136..ad69d91 100644
--- a/misc.go
+++ b/misc.go
@@ -107,6 +107,10 @@ func EscapeDefault(c rune, wasEscaped BackslashEscapeMode) BackslashEscapeMode {
}
}
+func EscapePreserve(_ rune, wasEscaped BackslashEscapeMode) BackslashEscapeMode {
+ return wasEscaped
+}
+
func writeStringUnicodeEscape(w io.Writer, c rune) (int, error) {
buf := [6]byte{
'\\',
@@ -118,8 +122,25 @@ func writeStringUnicodeEscape(w io.Writer, c rune) (int, error) {
}
return w.Write(buf[:])
}
-func writeStringShortEscape(w io.Writer, c byte) (int, error) {
- buf := [2]byte{'\\', c}
+func writeStringShortEscape(w io.Writer, c rune) (int, error) {
+ var b byte
+ switch c {
+ case '"', '\\', '/':
+ b = byte(c)
+ case '\b':
+ b = 'b'
+ case '\f':
+ b = 'f'
+ case '\n':
+ b = 'n'
+ case '\r':
+ b = 'r'
+ case '\t':
+ b = 't'
+ default:
+ panic("should not happen")
+ }
+ buf := [2]byte{'\\', b}
return w.Write(buf[:])
}
func writeStringChar(w io.Writer, c rune, wasEscaped BackslashEscapeMode, escaper func(rune, BackslashEscapeMode) BackslashEscapeMode) (int, error) {
@@ -129,38 +150,30 @@ func writeStringChar(w io.Writer, c rune, wasEscaped BackslashEscapeMode, escape
switch escaper(c, wasEscaped) {
case BackslashEscapeNone:
switch {
- case c < 0x0020:
+ case c < 0x0020: // override, gotta escape these
switch c {
- case '\b':
- return writeStringShortEscape(w, 'b')
- case '\f':
- return writeStringShortEscape(w, 'f')
- case '\n':
- return writeStringShortEscape(w, 'n')
- case '\r':
- return writeStringShortEscape(w, 'r')
- case '\t':
- return writeStringShortEscape(w, 't')
+ case '\b', '\f', '\n', '\r', '\t': // short-escape if possible
+ return writeStringShortEscape(w, c)
default:
return writeStringUnicodeEscape(w, c)
}
- case c == '"' || c == '\\':
- return writeStringShortEscape(w, byte(c))
- default:
+ case c == '"' || c == '\\': // override, gotta escape these
+ return writeStringShortEscape(w, c)
+ default: // obey
return writeRune(w, c)
}
case BackslashEscapeShort:
switch c {
- case '"', '\\', '/', '\b', '\f', '\n', '\r', '\t':
- return writeStringShortEscape(w, byte(c))
- default:
+ case '"', '\\', '/', '\b', '\f', '\n', '\r', '\t': // obey
+ return writeStringShortEscape(w, c)
+ default: // override, can't short-escape these
return writeRune(w, c)
}
case BackslashEscapeUnicode:
switch {
- case c > 0xFFFF:
+ case c > 0xFFFF: // override, can't escape these (TODO: unless we use UTF-16 surrogates?)
return writeRune(w, c)
- default:
+ default: // obey
return writeStringUnicodeEscape(w, c)
}
default: