|
3 | 3 | package service |
4 | 4 |
|
5 | 5 | import ( |
| 6 | + "strings" |
6 | 7 | "testing" |
7 | 8 |
|
8 | 9 | "github.com/stretchr/testify/require" |
@@ -36,3 +37,45 @@ func TestJSONMayEscapePlainASCII(t *testing.T) { |
36 | 37 | }) |
37 | 38 | } |
38 | 39 | } |
| 40 | + |
| 41 | +func TestJSONMayEscapePlainASCIIBackslashRuns(t *testing.T) { |
| 42 | + for count := 0; count <= 9; count++ { |
| 43 | + run := strings.Repeat("\\", count) |
| 44 | + odd := count%2 != 0 |
| 45 | + for _, prefix := range []string{"", "\\u003c", "\\n" + strings.Repeat("x", 15), "\\n" + strings.Repeat("x", 16), strings.Repeat("code\\n", 100)} { |
| 46 | + require.Equal(t, odd, JSONMayEscapePlainASCII([]byte(prefix+run)), "trailing run %d", count) |
| 47 | + require.Equal(t, odd, JSONMayEscapePlainASCII([]byte(prefix+run+"u0061")), "keyword run %d", count) |
| 48 | + require.Equal(t, odd, JSONMayEscapePlainASCII([]byte(prefix+run+"u0x")), "malformed run %d", count) |
| 49 | + } |
| 50 | + } |
| 51 | +} |
| 52 | + |
| 53 | +func BenchmarkJSONMayEscapePlainASCII(b *testing.B) { |
| 54 | + code := strings.Repeat("func f() { return \\\"sample\\\" }\\n", 1<<15) |
| 55 | + for _, tc := range []struct { |
| 56 | + name string |
| 57 | + body string |
| 58 | + want bool |
| 59 | + }{ |
| 60 | + {"short", "{\"input\":\"ok\"}", false}, |
| 61 | + {"short-newline", "{\"input\":\"a\\nb\"}", false}, |
| 62 | + {"plain", strings.Repeat("function sample ", 1<<16), false}, |
| 63 | + {"quoted-code", code, false}, |
| 64 | + {"source-file", strings.Repeat("package app\\nfunc sample() string { return \\\"Example 测试\\\" }\\n", 1<<14), false}, |
| 65 | + {"sparse-newlines", strings.Repeat(strings.Repeat("x", 126)+"\\n", 1<<13), false}, |
| 66 | + {"late-keyword-escape", code + "\\u0061", true}, |
| 67 | + {"html-escapes", strings.Repeat("\\u003c\\u003e", 1<<16), false}, |
| 68 | + {"escaped-backslashes", strings.Repeat("\\\\", 1<<19), false}, |
| 69 | + } { |
| 70 | + b.Run(tc.name, func(b *testing.B) { |
| 71 | + body := []byte(tc.body) |
| 72 | + b.ReportAllocs() |
| 73 | + b.SetBytes(int64(len(body))) |
| 74 | + for b.Loop() { |
| 75 | + if JSONMayEscapePlainASCII(body) != tc.want { |
| 76 | + b.Fatal("unexpected escape classification") |
| 77 | + } |
| 78 | + } |
| 79 | + }) |
| 80 | + } |
| 81 | +} |
0 commit comments