| 1 |
package utils |
| 2 |
|
| 3 |
import ( |
| 4 |
"encoding/json" |
| 5 |
"strings" |
| 6 |
"testing" |
| 7 |
|
| 8 |
"github.com/stretchr/testify/require" |
| 9 |
) |
| 10 |
|
| 11 |
func jsonStringInputs() []string { |
| 12 |
return []string{ |
| 13 |
"", |
| 14 |
"plain ascii value", |
| 15 |
"with \"quotes\" and \\backslashes\\", |
| 16 |
"tabs\tnewlines\nreturns\r", |
| 17 |
"controls \x00\x01\x1f\x7f", |
| 18 |
"html <b>bold</b> & more", |
| 19 |
"café naïve 日本語", |
| 20 |
"line\u2028and\u2029separators", |
| 21 |
"invalid \xff\xfe utf8 \xc3(", |
| 22 |
"trailing continuation \xc3", |
| 23 |
strings.Repeat("0123456789abcdef", 8), |
| 24 |
strings.Repeat("x", 7) + "\"" + strings.Repeat("y", 9), |
| 25 |
} |
| 26 |
} |
| 27 |
|
| 28 |
func Test_AppendJSONString(t *testing.T) { |
| 29 |
t.Parallel() |
| 30 |
for _, in := range jsonStringInputs() { |
| 31 |
want, err := json.Marshal(in) |
| 32 |
require.NoError(t, err) |
| 33 |
require.Equal(t, string(want), string(AppendJSONString(nil, in)), "input %q", in) |
| 34 |
require.Equal(t, string(want), string(AppendJSONString(nil, []byte(in))), "input %q", in) |
| 35 |
} |
| 36 |
|
| 37 |
// Every single byte value agrees with encoding/json. |
| 38 |
for i := range 256 { |
| 39 |
in := string([]byte{byte(i)}) |
| 40 |
want, err := json.Marshal(in) |
| 41 |
require.NoError(t, err) |
| 42 |
require.Equal(t, string(want), string(AppendJSONString(nil, in)), "byte %#x", i) |
| 43 |
} |
| 44 |
|
| 45 |
// Appending must preserve existing dst content. |
| 46 |
got := AppendJSONString([]byte(`{"msg":`), "hi \"there\"") |
| 47 |
require.Equal(t, `{"msg":"hi \"there\""`, string(got)) //nolint:testifylint // byte-exact comparison is the contract; JSONEq would hide encoding differences |
| 48 |
} |
| 49 |
|
| 50 |
func Benchmark_AppendJSONString(b *testing.B) { |
| 51 |
inputs := []struct { |
| 52 |
name string |
| 53 |
value string |
| 54 |
}{ |
| 55 |
{"clean-16B", "GET /index.html"}, |
| 56 |
{"clean-64B", strings.Repeat("clean-log", 7) + "x"}, |
| 57 |
{"escaped-64B", strings.Repeat(`says "hi" `, 6) + "done"}, |
| 58 |
{"unicode-64B", strings.Repeat("café 日本 ", 6) + "end"}, |
| 59 |
} |
| 60 |
for _, input := range inputs { |
| 61 |
dst := make([]byte, 0, 3*len(input.value)) |
| 62 |
b.Run(input.name+"/fiber", func(b *testing.B) { |
| 63 |
b.ReportAllocs() |
| 64 |
for b.Loop() { |
| 65 |
AppendJSONString(dst, input.value) |
| 66 |
} |
| 67 |
}) |
| 68 |
b.Run(input.name+"/default", func(b *testing.B) { |
| 69 |
b.ReportAllocs() |
| 70 |
for b.Loop() { |
| 71 |
if _, err := json.Marshal(input.value); err != nil { |
| 72 |
b.Fatal(err) |
| 73 |
} |
| 74 |
} |
| 75 |
}) |
| 76 |
} |
| 77 |
} |