From d34e9963b79d70a7f15026bf561726f0b55da93e Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Mateusz=20Czapli=C5=84ski?= Date: Thu, 6 Dec 2018 23:58:42 +0100 Subject: [PATCH] simplify quoteString Benchmark results comparison: benchmark old ns/op new ns/op delta BenchmarkValidIdentifier-4 250 241 -3.60% BenchmarkValidIdentifierUnquoted-4 423 418 -1.18% BenchmarkValidIdentifierReserved-4 22.0 26.9 +22.27% BenchmarkBigJSON-4 84351117 83896179 -0.54% BenchmarkStatementsLess-4 91.9 90.7 -1.31% BenchmarkFill-4 10096 9877 -2.17% BenchmarkValueTokenFromInterface-4 2274 1977 -13.06% --- token.go | 64 +++++++++++++++++++++----------------------------------- 1 file changed, 24 insertions(+), 40 deletions(-) diff --git a/token.go b/token.go index 6a8c77e..0bc5865 100644 --- a/token.go +++ b/token.go @@ -148,53 +148,37 @@ func quoteString(s string) string { _ = out.WriteByte('"') for _, r := range s { - - if r == '\\' || r == '"' { - _ = out.WriteByte('\\') - _, _ = out.WriteRune(r) - continue - } - + switch r { + case '\\': + _, _ = out.WriteString(`\\`) + case '"': + _, _ = out.WriteString(`\"`) + case '\b': + _, _ = out.WriteString(`\b`) + case '\f': + _, _ = out.WriteString(`\f`) + case '\n': + _, _ = out.WriteString(`\n`) + case '\r': + _, _ = out.WriteString(`\r`) + case '\t': + _, _ = out.WriteString(`\t`) // \u2028 and \u2029 are separator runes that are not valid // in javascript strings so they must be escaped. // See http://timelessrepo.com/json-isnt-a-javascript-subset - if r == '\u2028' { + case '\u2028': _, _ = out.WriteString(`\u2028`) - continue - } - if r == '\u2029' { + case '\u2029': _, _ = out.WriteString(`\u2029`) - continue - } - - // Any other control runes must be escaped - if unicode.IsControl(r) { - - switch r { - case '\b': - _ = out.WriteByte('\\') - _ = out.WriteByte('b') - case '\f': - _ = out.WriteByte('\\') - _ = out.WriteByte('f') - case '\n': - _ = out.WriteByte('\\') - _ = out.WriteByte('n') - case '\r': - _ = out.WriteByte('\\') - _ = out.WriteByte('r') - case '\t': - _ = out.WriteByte('\\') - _ = out.WriteByte('t') - default: - _, _ = out.WriteString(fmt.Sprintf(`\u%04X`, r)) + default: + // Any other control runes must be escaped + if unicode.IsControl(r) { + _, _ = fmt.Fprintf(out, `\u%04X`, r) + } else { + // Unescaped rune + _, _ = out.WriteRune(r) } - - continue } - - // Unescaped rune - _, _ = out.WriteRune(r) } _ = out.WriteByte('"')