Debian Codegraph @

internal/encoder/string_fast_path_test.go

raw
1 package encoder
2
3 import (
4 "fmt"
5 "math/rand"
6 "strings"
7 "testing"
8 "unicode/utf8"
9 )
10
11 // AppendString handles a string which has nothing to escape by itself: by bytes under a half word, by a word
12 // made of two overlapping halves under a word, by words with the last one overlapping, and with a copy which
13 // depends on the length. Every length and every position of a byte is compared with the function for the
14 // options, which is the one used for a string to escape.
15 func TestAppendStringFastPath(t *testing.T) {
16 special := []string{
17 "\x00", "\x1f", " ", "!", `"`, "#", "&", "'", "/", "<", "=", ">", "?", "[", `\`, "]", "\x7f",
18 "\x80", "\xe3", "\xff", "あ", "
", "
", "\n", "\t",
19 }
20 var inputs []string
21 for length := 0; length <= 72; length++ {
22 base := strings.Repeat("a", length)
23 inputs = append(inputs, base)
24 for pos := 0; pos <= length; pos++ {
25 for _, c := range special {
26 inputs = append(inputs, base[:pos]+c+base[pos:])
27 }
28 }
29 }
30 for index := range stringEscapes {
31 escape := &stringEscapes[index]
32 var flag OptionFlag
33 if index&stringEscapeHTML != 0 {
34 flag |= HTMLEscapeOption
35 }
36 if index&stringEscapeNormalize != 0 {
37 flag |= NormalizeUTF8Option
38 }
39 ctx := &RuntimeContext{Option: &Option{Flag: flag}}
40 t.Run(fmt.Sprintf("html=%v,normalize=%v", index&stringEscapeHTML != 0, index&stringEscapeNormalize != 0), func(t *testing.T) {
41 for _, s := range inputs {
42 expected := string(escape.appendEscaped([]byte("x"), s))
43 // without and with the capacity.
44 for _, buf := range [][]byte{[]byte("x"), append(make([]byte, 0, 256), 'x')} {
45 if got := string(AppendString(ctx, buf, s)); got != expected {
46 t.Fatalf("AppendString(%q): expected %s but got %s", s, expected, got)
47 }
48 }
49 }
50 })
51 }
52 }
53
54 // The string must not be read out of its memory: the strings here end at the end of their memory.
55 func TestAppendStringAtEndOfMemory(t *testing.T) {
56 ctx := &RuntimeContext{Option: &Option{Flag: HTMLEscapeOption | NormalizeUTF8Option}}
57 for length := 1; length <= 24; length++ {
58 mem := []byte(strings.Repeat("a", length))
59 for start := 0; start < length; start++ {
60 s := string(mem[start:])
61 if got := string(AppendString(ctx, nil, s)); got != `"`+s+`"` {
62 t.Fatalf("AppendString(%q): got %s", s, got)
63 }
64 }
65 }
66 }
67
68 // The buffer grows as append does: the capacity must at least double, or appending many strings is quadratic.
69 func TestAppendStringGrowth(t *testing.T) {
70 ctx := &RuntimeContext{Option: &Option{Flag: HTMLEscapeOption | NormalizeUTF8Option}}
71 var buf []byte
72 grown := 0
73 for i := 0; i < 10000; i++ {
74 before := cap(buf)
75 buf = AppendString(ctx, buf, "0123456789")
76 if cap(buf) != before {
77 grown++
78 }
79 }
80 if grown > 32 {
81 t.Fatalf("the buffer grew %d times", grown)
82 }
83 if len(buf) != 10000*12 {
84 t.Fatalf("unexpected length %d", len(buf))
85 }
86 }
87
88 func BenchmarkAppendString(b *testing.B) {
89 options := []struct {
90 name string
91 flag OptionFlag
92 }{
93 {"std", HTMLEscapeOption | NormalizeUTF8Option},
94 {"fastest", 0},
95 }
96 text := strings.Repeat("abcdefghij", 1000)
97 for _, o := range options {
98 ctx := &RuntimeContext{Option: &Option{Flag: o.flag}}
99 for _, n := range []int{0, 3, 6, 8, 9, 12, 15, 16, 17, 20, 24, 28, 31, 32, 36, 50, 64, 100, 300, 1000, 10000} {
100 s := text[:n]
101 b.Run(fmt.Sprintf("%s/%d", o.name, n), func(b *testing.B) {
102 buf := make([]byte, 0, 16384)
103 for i := 0; i < b.N; i++ {
104 buf = AppendString(ctx, buf[:0], s)
105 }
106 })
107 }
108 }
109 }
110
111 // commonRuneSize takes a character for valid and not escaped only if decodeRuneInString does, for every first
112 // byte which is not ASCII and every two bytes after it, and at the end of the string.
113 func TestCommonRuneSize(t *testing.T) {
114 var accepted [3]int
115 for c := 0x80; c <= 0xff; c++ {
116 for s1 := 0; s1 <= 0xff; s1++ {
117 for s2 := 0; s2 <= 0xff; s2++ {
118 s := string([]byte{byte(c), byte(s1), byte(s2)})
119 for n := 1; n <= 3; n++ {
120 size := commonRuneSize(s[:n], 0)
121 if size == 0 {
122 continue
123 }
124 accepted[size-1]++
125 if state, want := decodeRuneInString(s[:n]); state != validUTF8State || want != size {
126 t.Fatalf("% x: commonRuneSize %d, decodeRuneInString %d %d", s[:n], size, state, want)
127 }
128 }
129 }
130 }
131 }
132 // the characters of two bytes and the ones of three bytes of 0xE3 to 0xEC, 0xEE and 0xEF are taken.
133 if want := 30 * 64 * 256 * 2; accepted[1] != want {
134 t.Errorf("characters of two bytes: %d, want %d", accepted[1], want)
135 }
136 if want := 12 * 64 * 64; accepted[2] != want {
137 t.Errorf("characters of three bytes: %d, want %d", accepted[2], want)
138 }
139 }
140
141 // BenchmarkAppendStringNotASCII measures strings of Japanese, and of Japanese and ASCII, by the options of the
142 // std configuration, of the fast one, which normalizes UTF-8 without escaping HTML, and of the fastest one.
143 func BenchmarkAppendStringNotASCII(b *testing.B) {
144 options := []struct {
145 name string
146 flag OptionFlag
147 }{
148 {"std", HTMLEscapeOption | NormalizeUTF8Option},
149 {"fast", NormalizeUTF8Option},
150 {"fastest", 0},
151 }
152 ja := []rune(strings.Repeat("日本語の文章を書き出します。", 100))
153 mixed := []rune(strings.Repeat("東京 Tokyo 2026年9月30日, weather: 晴れ; ", 40))
154 texts := []struct {
155 name string
156 s string
157 }{
158 {"ja3", string(ja[:3])}, {"ja10", string(ja[:10])}, {"ja30", string(ja[:30])}, {"ja100", string(ja[:100])},
159 {"ja1000", string(ja[:1000])}, {"mixed40", string(mixed[:40])}, {"mixed400", string(mixed[:400])},
160 }
161 for _, o := range options {
162 ctx := &RuntimeContext{Option: &Option{Flag: o.flag}}
163 for _, text := range texts {
164 s := text.s
165 b.Run(o.name+"/"+text.name, func(b *testing.B) {
166 buf := make([]byte, 0, 16384)
167 b.SetBytes(int64(len(s)))
168 for i := 0; i < b.N; i++ {
169 buf = AppendString(ctx, buf[:0], s)
170 }
171 })
172 }
173 }
174 }
175
176 // referenceNormalizedString is what appendNormalizedString and appendNormalizedHTMLString append, written by
177 // decoding every character with unicode/utf8.
178 func referenceNormalizedString(s string, html bool) string {
179 b := []byte{'"'}
180 for i := 0; i < len(s); {
181 c := s[i]
182 if c < utf8.RuneSelf {
183 if seq := escapeSequences[c]; seq != 0 && (html || (c != '<' && c != '>' && c != '&')) {
184 for k := uint64(0); k < seq>>56; k++ {
185 b = append(b, byte(seq>>(8*k)))
186 }
187 } else {
188 b = append(b, c)
189 }
190 i++
191 continue
192 }
193 r, size := utf8.DecodeRuneInString(s[i:])
194 switch {
195 case r == utf8.RuneError && size == 1:
196 b = append(b, invalidUTF8...)
197 case r == '\u2028':
198 b = append(b, `\u2028`...)
199 case r == '\u2029':
200 b = append(b, `\u2029`...)
201 default:
202 b = append(b, s[i:i+size]...)
203 }
204 i += size
205 }
206 return string(append(b, '"'))
207 }
208
209 // The strings of every length, mostly of characters which are not ASCII, with bytes to escape, invalid UTF-8,
210 // U+2028 and U+2029 anywhere, are appended by the functions which normalize UTF-8 as they are when every
211 // character is decoded ( with the loop of the escapes by SIMD if the CPU has it; see also
212 // TestAppendNormalizedStringsWithoutEscapeLoop ).
213 func TestAppendNormalizedStrings(t *testing.T) {
214 checkAppendNormalizedStrings(t)
215 }
216
217 func checkAppendNormalizedStrings(t *testing.T) {
218 t.Helper()
219 r := rand.New(rand.NewSource(1))
220 pieces := []string{"a", " ", "\"", "\\", "\n", "\x00", "\x1f", "\x7f", "<", ">", "&", "é", "ß", "あ", "語", "。", "A",
221 "\u0800", "\uffff", "\ue000", "\ufffd", "😀", "\u2027", "\u2028", "\u2029", "\u202a", "\xff", "\x80", "\xc3",
222 "\xe3\x81", "\xe3", "\xf0\x9f\x98", "\xc0\x80", "\xe0\x80\x80", "\xed\xa0\x80", "\xf4\x90\x80\x80"}
223 common := []string{"あ", "い", "語", "。", "A", "é", "ß"}
224 for n := 0; n < 4000; n++ {
225 var b strings.Builder
226 for k := r.Intn(n%200 + 1); k > 0; k-- {
227 if r.Intn(8) == 0 {
228 b.WriteString(pieces[r.Intn(len(pieces))])
229 } else {
230 b.WriteString(common[r.Intn(len(common))])
231 }
232 }
233 s := b.String()
234 if got, want := string(appendNormalizedString(nil, s)), referenceNormalizedString(s, false); got != want {
235 t.Fatalf("%q:\n got %q\nwant %q", s, got, want)
236 }
237 if got, want := string(appendNormalizedHTMLString(nil, s)), referenceNormalizedString(s, true); got != want {
238 t.Fatalf("HTML, %q:\n got %q\nwant %q", s, got, want)
239 }
240 }
241 }