Debian Codegraph @

strcase_test.go

raw
1 // Copyright 2023 Charlie Vieth. All rights reserved.
2 // Use of this source code is governed by the MIT license.
3
4 package strcase
5
6 import (
7 "flag"
8 "fmt"
9 "math/rand"
10 "sort"
11 "strconv"
12 "strings"
13 "testing"
14 "unicode"
15 "unicode/utf8"
16 "unsafe"
17
18 "github.com/charlievieth/strcase/internal/tables"
19 "github.com/charlievieth/strcase/internal/test"
20 )
21
22 func TestUnicodeVersion(t *testing.T) {
23 test.UnicodeVersion(t, UnicodeVersion)
24 }
25
26 func TestCompare(t *testing.T) {
27 test.Compare(t, Compare)
28 }
29
30 func TestEqualFold(t *testing.T) {
31 test.EqualFold(t, EqualFold)
32 }
33
34 func TestIndex(t *testing.T) {
35 test.Index(t, Index)
36 }
37
38 func TestIndexUnicode(t *testing.T) {
39 test.IndexUnicode(t, Index)
40 }
41
42 func TestIndexInvalid(t *testing.T) {
43 test.IndexInvalid(t, Index)
44 }
45
46 func TestIndexRuneIndexParity(t *testing.T) {
47 test.IndexRuneIndexParity(t, Index, IndexRune)
48 }
49
50 func TestIndexAllAssigned(t *testing.T) {
51 test.IndexAllAssigned(t,
52 test.TestFunc{Name: "Compare", Index: Compare},
53 test.TestFunc{Name: "Contains", Contains: Contains},
54 test.TestFunc{Name: "EqualFold", Contains: EqualFold},
55 test.TestFunc{Name: "HasPrefix", Contains: HasPrefix},
56 test.TestFunc{Name: "HasSuffix", Contains: HasSuffix},
57 test.TestFunc{Name: "Index", Index: Index},
58 test.TestFunc{Name: "LastIndex", Index: LastIndex},
59 )
60 }
61
62 // Test our use of bytealg.IndexString
63 func TestIndexNumeric(t *testing.T) {
64 test.IndexNumeric(t, Index)
65 }
66
67 // Extensively test the handling of Kelvin K since it is three times the size
68 // of ASCII [Kk] it requires special handling.
69 func TestIndexKelvin(t *testing.T) {
70 test.IndexKelvin(t, Index)
71 }
72
73 // Test the Rabin-Karp fallback logic directly since not all test cases will
74 // trigger it.
75 func TestRabinKarp(t *testing.T) {
76 test.Index(t, test.WrapRabinKarp(indexRabinKarpUnicode))
77 }
78
79 // Test the Rabin-Karp fallback logic directly since not all test cases will
80 // trigger it.
81 func TestRabinKarpUnicode(t *testing.T) {
82 test.IndexUnicode(t, test.WrapRabinKarp(indexRabinKarpUnicode))
83 }
84
85 func TestBruteForceIndexUnicode(t *testing.T) {
86 test.IndexUnicode(t, func(s, substr string) int {
87 n := len(substr)
88 var size int
89 if n > 0 {
90 if substr[0] < utf8.RuneSelf {
91 size = 1
92 } else {
93 _, size = utf8.DecodeRuneInString(substr)
94 }
95 }
96 if len(s) == 0 || len(substr) == 0 || n == size {
97 // Can't use brute-force here
98 return Index(s, substr)
99 }
100 return bruteForceIndexUnicode(s, substr)
101 })
102 }
103
104 func TestIndexAllocs(t *testing.T) {
105 haystack := "test世界İ"
106 allocs := testing.AllocsPerRun(1000, func() {
107 if i := Index(haystack, "世界İ"); i != 4 {
108 t.Fatalf("'s' at %d; want 4", i)
109 }
110 if i := Index(haystack, "t世"); i != 3 {
111 t.Fatalf("'世' at %d; want 3", i)
112 }
113 if i := Index(haystack, "test世界İ"); i != 0 {
114 t.Fatalf("'İ' at %d; want 0", i)
115 }
116 })
117 if allocs != 0 {
118 t.Errorf("expected no allocations, got %f", allocs)
119 }
120 }
121
122 func TestContains(t *testing.T) {
123 test.Contains(t, Contains)
124 }
125
126 func TestContainsAny(t *testing.T) {
127 test.ContainsAny(t, ContainsAny)
128 }
129
130 func TestLastIndex(t *testing.T) {
131 test.LastIndex(t, LastIndex)
132 }
133
134 func TestLastIndexInvalid(t *testing.T) {
135 test.LastIndexInvalid(t, LastIndex)
136 }
137
138 func TestIndexRune(t *testing.T) {
139 test.IndexRune(t, IndexRune)
140 }
141
142 func TestIndexRuneAllocs(t *testing.T) {
143 haystack := "test世界İ"
144 allocs := testing.AllocsPerRun(1000, func() {
145 if i := IndexRune(haystack, 's'); i != 2 {
146 t.Fatalf("'s' at %d; want 2", i)
147 }
148 if i := IndexRune(haystack, '世'); i != 4 {
149 t.Fatalf("'世' at %d; want 4", i)
150 }
151 if i := IndexRune(haystack, 'İ'); i != 10 {
152 t.Fatalf("'İ' at %d; want 10", i)
153 }
154 })
155 if allocs != 0 {
156 t.Errorf("expected no allocations, got %f", allocs)
157 }
158 }
159
160 func TestIndexRuneCase(t *testing.T) {
161 test.IndexRuneCase(t, indexRuneCase)
162 }
163
164 func TestContainsRune(t *testing.T) {
165 test.ContainsRune(t, ContainsRune)
166 }
167
168 func TestLastIndexRune(t *testing.T) {
169 test.LastIndexRune(t, lastIndexRune)
170 }
171
172 func TestIndexByte(t *testing.T) {
173 test.IndexByte(t, IndexByte)
174 }
175
176 func TestLastIndexByte(t *testing.T) {
177 test.LastIndexByte(t, LastIndexByte)
178 }
179
180 func TestIndexNonASCII(t *testing.T) {
181 test.IndexNonASCII(t, IndexNonASCII)
182 }
183
184 func TestContainsNonASCII(t *testing.T) {
185 test.ContainsNonASCII(t, ContainsNonASCII)
186 }
187
188 func TestHasPrefix(t *testing.T) {
189 test.HasPrefix(t, hasPrefixUnicode)
190 }
191
192 func TestTrimPrefix(t *testing.T) {
193 test.TrimPrefix(t, TrimPrefix)
194 }
195
196 func TestHasSuffix(t *testing.T) {
197 test.HasSuffix(t, HasSuffix)
198 }
199
200 func TestTrimSuffix(t *testing.T) {
201 test.TrimSuffix(t, TrimSuffix)
202 }
203
204 func TestCount(t *testing.T) {
205 test.Count(t, Count)
206 }
207
208 func TestTestIndexAny(t *testing.T) {
209 test.IndexAny(t, IndexAny)
210 }
211
212 func TestTestLastIndexAny(t *testing.T) {
213 test.LastIndexAny(t, LastIndexAny)
214 }
215
216 func TestCut(t *testing.T) {
217 test.Cut(t, Cut)
218 }
219
220 func TestCutPrefix(t *testing.T) {
221 test.CutPrefix(t, CutPrefix)
222 }
223
224 func TestCutSuffix(t *testing.T) {
225 test.CutSuffix(t, CutSuffix)
226 }
227
228 // Ensure that strings.EqualFold does not match 'İ' (U+0130) and ASCII 'i' or 'I'.
229 // This is mostly a sanity check.
230 func TestLatinCapitalLetterIWithDotAbove(t *testing.T) {
231 test.LatinCapitalLetterIWithDotAbove(t, Compare)
232 }
233
234 func TestNonLetterASCII(t *testing.T) {
235 test.NonLetterASCII(t, nonLetterASCII)
236 }
237
238 ////////////////////////////////////////////////////////////
239 // Fuzz tests
240
241 func TestIndexFuzz(t *testing.T) {
242 test.IndexFuzz(t, Index)
243 }
244
245 func TestLastIndexFuzz(t *testing.T) {
246 test.LastIndexFuzz(t, LastIndex)
247 }
248
249 func TestHasPrefixFuzz(t *testing.T) {
250 test.HasPrefixFuzz(t, hasPrefixUnicode)
251 }
252
253 func TestHasSuffixFuzz(t *testing.T) {
254 test.HasSuffixFuzz(t, HasSuffix)
255 }
256
257 func TestCompareFuzz(t *testing.T) {
258 test.CompareFuzz(t, Compare)
259 }
260
261 func TestEqualFoldFuzz(t *testing.T) {
262 test.EqualFoldFuzz(t,
263 test.TestFunc{Name: "Contains", Contains: Contains},
264 test.TestFunc{Name: "EqualFold", Contains: EqualFold},
265 test.TestFunc{Name: "HasPrefix", Contains: HasPrefix},
266 test.TestFunc{Name: "HasSuffix", Contains: HasSuffix},
267 )
268 }
269
270 ////////////////////////////////////////////////////////////
271 // Benchmarks
272
273 // TODO: update benchmarks to match my Go PR and see if my approach
274 // there is faster than ours (use last byte)
275
276 func BenchmarkCompare(b *testing.B) {
277 bench := func(b *testing.B, s, t string) {
278 b.Helper()
279 n := len(s)
280 if len(t) < n {
281 n = len(t)
282 }
283 b.SetBytes(int64(n))
284 for i := 0; i < b.N; i++ {
285 Compare(s, t)
286 }
287 }
288
289 const s1 = "abcdefghijKz"
290 const s2 = "abcDefGhijKz"
291
292 b.Run("ASCII", func(b *testing.B) {
293 bench(b, s1, s2)
294 })
295
296 b.Run("ASCII_Long", func(b *testing.B) {
297 const s = s1 + s1 + s1 + s1 + s1
298 const t = s2 + s2 + s2 + s2 + s2
299 bench(b, s, t)
300 })
301
302 b.Run("UnicodePrefix", func(b *testing.B) {
303 // WARN
304 const s1 = "AbCdCfghIjKz"
305 const s2 = "abcDeFGhijKz"
306 bench(b, "αβδ"+s1, "ΑΒΔ"+s2)
307 })
308
309 b.Run("UnicodeSuffix", func(b *testing.B) {
310 bench(b, s1+"αβδ", s2+"ΑΒΔ")
311 })
312
313 b.Run("Russian", func(b *testing.B) {
314 b.SetBytes(int64(len(russianText)))
315 bench(b, russianText, russianText)
316 })
317 }
318
319 const benchmarkString = "some_text=some☺value"
320
321 // WARN: dev only
322 func BenchmarkIndexRuneRussian(b *testing.B) {
323 want := strings.IndexRune(russianText, 'ж')
324 if got := IndexRune(russianText, 'ж'); got != want {
325 b.Fatalf("got: %d want: %d", got, want)
326 }
327 b.SetBytes(int64(len(russianText)))
328 for i := 0; i < b.N; i++ {
329 IndexRune(russianText, 'ж')
330 }
331 }
332
333 func BenchmarkIndexRune(b *testing.B) {
334 // const str = benchmarkString + "\u212a"
335 const str = benchmarkString + "k"
336 // const str = benchmarkString + string(rune(0x212A))
337 // if got := IndexRune(benchmarkString, '☺'); got != 14 {
338 if got := IndexRune(str, rune(0x212A)); got != 22 {
339 b.Fatalf("wrong index: expected 14, got=%d", got)
340 }
341 for i := 0; i < b.N; i++ {
342 IndexRune(benchmarkString, '☺')
343 }
344 }
345
346 // TODO: remove this benchmark
347 func BenchmarkIndexRuneFastPath(b *testing.B) {
348 if got := IndexRune(benchmarkString, 'v'); got != 17 {
349 b.Fatalf("wrong index: expected 17, got=%d", got)
350 }
351 for i := 0; i < b.N; i++ {
352 IndexRune(benchmarkString, 'v')
353 }
354 }
355
356 // Benchmark buffer
357 var bmbuf []byte
358
359 func valName(x int) string {
360 if s := x >> 20; s<<20 == x {
361 return fmt.Sprintf("%dM", s)
362 }
363 if s := x >> 10; s<<10 == x {
364 return fmt.Sprintf("%dK", s)
365 }
366 return fmt.Sprint(x)
367 }
368
369 var indexSizes = []int{10, 32, 4 << 10, 4 << 20, 64 << 20}
370
371 func benchBytesUnicode(b *testing.B, sizes []int, f func(b *testing.B, n int, s string)) {
372 // WARN: change this to runes with the same last byte
373 // These character all have the same second byte (0x90)
374 const _s = "𐀀𐀁𐀂𐀃𐀄𐀅𐀆𐀇𐀈𐀉𐀊𐀋𐀍𐀎𐀏𐀐𐀑𐀒𐀓𐀔𐀕𐀖𐀗𐀘𐀙𐀚𐀛𐀜𐀝𐀞𐀟𐀠"
375 const s = _s + _s + _s + _s + _s + _s + _s + _s + _s + _s + _s + _s + _s + _s + _s + _s // 2048
376 for _, n := range sizes {
377 b.Run(valName(n), func(b *testing.B) {
378 if len(bmbuf) < n {
379 bmbuf = make([]byte, n)
380 }
381 for i := 0; i < n; {
382 i += copy(bmbuf[i:], s)
383 }
384 copy(bmbuf[n-len("𐀤"):], "𐀤")
385 b.SetBytes(int64(n))
386 f(b, n, string(bmbuf))
387 })
388 }
389 }
390
391 func bmIndexRune(index func(string, rune) int) func(b *testing.B, n int, s string) {
392 return func(b *testing.B, n int, s string) {
393 // Sanity check since I got this wrong in the past
394 want := strings.IndexRune(s, '𐀤')
395 got := index(s, '𐀤')
396 if want != got {
397 b.Fatalf("bad index %d want: %d", got, want)
398 }
399 if got != n-4 {
400 b.Fatalf("bad index %d want: %d", got, n-4)
401 }
402 for i := 0; i < b.N; i++ {
403 _ = index(s, '𐀤')
404 }
405 }
406 }
407
408 func benchBytes(b *testing.B, sizes []int, f func(b *testing.B, n int)) {
409 for _, n := range sizes {
410 b.Run(valName(n), func(b *testing.B) {
411 if len(bmbuf) < n {
412 bmbuf = make([]byte, n)
413 }
414 b.SetBytes(int64(n))
415 f(b, n)
416 })
417 }
418 }
419
420 func bmIndexRuneCaseUnicode(rt *unicode.RangeTable, needle rune) func(b *testing.B, n int) {
421 n := 0
422 visitTable(rt, func(_ rune) {
423 n++
424 })
425 rs := make([]rune, 0, n)
426 visitTable(rt, func(r rune) {
427 if r != needle {
428 rs = append(rs, r)
429 }
430 })
431 // Shuffle the runes so that they are not in descending order.
432 // The sort is deterministic since this is used for benchmarks,
433 // which need to be repeatable.
434 rr := rand.New(rand.NewSource(1))
435 rr.Shuffle(len(rs), func(i, j int) {
436 rs[i], rs[j] = rs[j], rs[i]
437 })
438 uchars := string(rs)
439
440 return func(b *testing.B, n int) {
441 buf := bmbuf[0:n]
442 o := copy(buf, uchars)
443 for o < len(buf) {
444 o += copy(buf[o:], uchars)
445 }
446
447 // Make space for the needle rune at the end of buf.
448 m := utf8.RuneLen(needle)
449 for o := m; o > 0; {
450 _, sz := utf8.DecodeLastRune(buf)
451 copy(buf[len(buf)-sz:], "\x00\x00\x00\x00")
452 buf = buf[:len(buf)-sz]
453 o -= sz
454 }
455 buf = utf8.AppendRune(buf[:n-m], needle)
456 s := *(*string)(unsafe.Pointer(&buf))
457
458 n -= m // adjust for rune len
459 for i := 0; i < b.N; i++ {
460 j := indexRuneCase(s, needle)
461 if j != n {
462 b.Fatal("bad index", j)
463 }
464 }
465 for i := range buf {
466 buf[i] = 0
467 }
468 }
469 }
470
471 func BenchmarkIndexRuneCaseUnicode(b *testing.B) {
472 b.Run("Latin", func(b *testing.B) {
473 // Latin is mostly 1, 2, 3 byte runes.
474 benchBytes(b, indexSizes, bmIndexRuneCaseUnicode(unicode.Latin, 'é'))
475 })
476 b.Run("Cyrillic", func(b *testing.B) {
477 // Cyrillic is mostly 2 and 3 byte runes.
478 benchBytes(b, indexSizes, bmIndexRuneCaseUnicode(unicode.Cyrillic, 'Ꙁ'))
479 })
480 b.Run("Han", func(b *testing.B) {
481 // Han consists only of 3 and 4 byte runes.
482 benchBytes(b, indexSizes, bmIndexRuneCaseUnicode(unicode.Han, '𠀿'))
483 })
484 }
485
486 // Torture test IndexRune. This is useful for calculating the cutover
487 // for when we should switch to strings.Index in indexRuneCase.
488 func BenchmarkIndexRuneTorture_Bytes(b *testing.B) {
489 b.Log("WARN: this only tests runes that are 4 bytes!")
490 if *benchStdLib {
491 benchBytesUnicode(b, indexSizes, bmIndexRune(strings.IndexRune))
492 } else {
493 benchBytesUnicode(b, indexSizes, bmIndexRune(IndexRune))
494 }
495 }
496
497 func BenchmarkIndexByte(b *testing.B) {
498 const ch = 'V'
499 if got := IndexByte(benchmarkString, ch); got != 17 {
500 b.Fatalf("wrong index: expected 17, got=%d", got)
501 }
502 b.SetBytes(int64(len(benchmarkString)))
503 for i := 0; i < b.N; i++ {
504 IndexByte(benchmarkString, ch)
505 }
506 }
507
508 func BenchmarkIndexByteEmpty(b *testing.B) {
509 const ch = 'V'
510 for i := 0; i < b.N; i++ {
511 IndexByte("", ch)
512 }
513 }
514
515 // Benchmark the handling of [KkSs] which require a check for their
516 // equivalent Unicode folds.
517 func BenchmarkIndexByteLongSpecial(b *testing.B) {
518 for i := range bmbuf {
519 bmbuf[i] = 0
520 }
521
522 bmIndexByte := func(index func(string, byte) int) func(b *testing.B, n int) {
523 return func(b *testing.B, n int) {
524 buf := bmbuf[0:n]
525 buf[n/2] = 's'
526 copy(buf[n-2:], "ſ")
527 s := string(buf)
528 // We scan the first half of the string twice but the match occurs
529 // in the first half so using that index here seems more fair than
530 // using the full length of the string as number of bytes processed.
531 b.SetBytes(int64(index(s, 's')))
532 for i := 0; i < b.N; i++ {
533 j := index(s, 's')
534 if j != n/2 {
535 b.Fatal("bad index", j)
536 }
537 }
538 buf[n/2] = '\x00'
539 buf[n-2] = '\x00'
540 buf[n-1] = '\x00'
541 }
542 }
543
544 benchBytes := func(b *testing.B, sizes []int, f func(b *testing.B, n int)) {
545 for _, n := range sizes {
546 b.Run(valName(n), func(b *testing.B) {
547 if len(bmbuf) < n {
548 bmbuf = make([]byte, n)
549 }
550 f(b, n)
551 })
552 }
553 }
554
555 benchBytes(b, indexSizes, bmIndexByte(IndexByte))
556 }
557
558 func BenchmarkLastIndexByte(b *testing.B) {
559 if testing.Short() {
560 b.Skip("short test")
561 }
562 s := "b" + strings.Repeat("a", 128)
563 c := byte('B')
564 if i := LastIndexByte(s, c); i != 0 {
565 b.Fatal("invalid index:", i)
566 }
567 b.SetBytes(int64(len(s)))
568 for i := 0; i < b.N; i++ {
569 LastIndexByte(s, c)
570 }
571 }
572
573 // WARN
574 var benchStdLib = flag.Bool("stdlib", false, "Use strings.Index in benchmarks (for comparison)")
575
576 // WARN: this is not really fair because of strings.ToLower
577 func benchmarkIndex(b *testing.B, s, substr string) {
578 if *benchStdLib {
579 n := strings.Index(strings.ToLower(s), strings.ToLower(substr))
580 if o := Index(s, substr); n != o {
581 b.Errorf("strings.Index(%q, %q) = %d; want: %d", s, substr, n, o)
582 }
583 if n >= 0 {
584 b.SetBytes(int64(len(s) + len(substr)))
585 } else {
586 b.SetBytes(int64(len(s)))
587 }
588 for i := 0; i < b.N; i++ {
589 strings.Index(strings.ToLower(s), strings.ToLower(substr))
590 }
591 } else {
592 if n := Index(s, substr); n >= 0 {
593 b.SetBytes(int64(len(s) + len(substr)))
594 } else {
595 b.SetBytes(int64(len(s)))
596 }
597 for i := 0; i < b.N; i++ {
598 Index(s, substr)
599 }
600 }
601 }
602
603 func BenchmarkIndex(b *testing.B) {
604 if got := Index(benchmarkString, "v"); got != 17 {
605 b.Fatalf("wrong index: expected 17, got=%d", got)
606 }
607 benchmarkIndex(b, benchmarkString, "v")
608 }
609
610 func BenchmarkLastIndex(b *testing.B) {
611 if got := LastIndex(benchmarkString, "v"); got != 17 {
612 b.Fatalf("wrong index: expected 17, got=%d", got)
613 }
614 for i := 0; i < b.N; i++ {
615 LastIndex(benchmarkString, "v")
616 }
617 }
618
619 // Thanks to variable length encoding it's possible the needle
620 // to be larger than the haystack.
621 func BenchmarkLastIndexNeedleExceedsHaystack(b *testing.B) {
622 s := strings.Repeat("ab", 1024)
623 substr := "z" + s
624 i1 := strings.LastIndex(s, substr)
625 i2 := LastIndex(s, substr)
626 if i1 != i2 {
627 b.Fatalf("wrong index: expected: %d, got: %d", i1, i2)
628 }
629 // Can't compare perf to the stdlib because we have to scan
630 // the whole string and not just bail at the length mismatch.
631 b.SetBytes(int64(len(s)))
632 for i := 0; i < b.N; i++ {
633 LastIndex(s, substr)
634 }
635 }
636
637 func BenchmarkIndexNeedleLongerThanSubject(b *testing.B) {
638 const s = benchmarkString
639 b.Run("FirstRuneEqual", func(b *testing.B) {
640 substr := s + "-"
641 benchmarkIndex(b, s, substr)
642 })
643 b.Run("FirstRuneNotEqual", func(b *testing.B) {
644 substr := "-" + s
645 benchmarkIndex(b, s, substr)
646 })
647 }
648
649 const russianText = `Владимир Маяковский родился в селе Багдади[10] Кутаисской
650 губернии Российской империи, в обедневшей дворянской семье[11] Владимира
651 Константиновича Маяковского (1857—1906), служившего лесничим третьего
652 разряда в Эриванской губернии, а с 1889 г. — в Багдатском лесничестве.
653 Маяковский вёл род от запорожских казаков, прадед отца поэта Кирилл
654 Маяковский был полковым есаулом Черноморских войск, что дало ему право
655 получить звание дворянина[12]. Мать поэта, Александра Алексеевна Павленко
656 (1867−1954), из рода кубанских казаков, родилась на Кубани, в станице
657 Терновской. В поэме «Владикавказ — Тифлис» 1924 года Маяковский называет
658 себя «грузином». О себе Маяковский сказал в 1927 году: «Родился я в
659 1894[13] году на Кавказе. Отец был казак, мать — украинка. Первый язык —
660 грузинский. Так сказать, между тремя культурами» (из интервью пражской
661 газете «Prager Presse»)[14]. Бабушка по отцовской линии, Ефросинья Осиповна
662 Данилевская, — двоюродная сестра автора исторических романов Г. П.
663 Данилевского, родом из запорожских казаков. У Маяковского было две сестры:
664 Людмила (1884—1972) и Ольга (1890—1949) и два брата: Константин (умер в
665 трёхлетнем возрасте от скарлатины) и Александр (умер во младенчестве).`
666
667 var (
668 russianUpper = strings.ToUpper(russianText)
669 russianLower = strings.ToLower(russianText)
670 )
671
672 func BenchmarkIndexRussian(b *testing.B) {
673 benchmarkIndex(b, russianText, "младенчестве")
674 }
675
676 // Pathological worst-case.
677 func BenchmarkIndexLateMatchLargeNeedle(b *testing.B) {
678 bench := func(b *testing.B, s1, s2, s3 string) {
679 m := strings.Repeat(s1, 100/len(s1))
680 haystack := strings.Repeat(m+s2, 300) + m + s3
681 needle := m + s3
682 benchmarkIndex(b, haystack, needle)
683 }
684 b.Run("Latin", func(b *testing.B) {
685 bench(b, "AB", "C", "D")
686 })
687 b.Run("Cyrillic", func(b *testing.B) {
688 bench(b, "А̀ВЄ", "Ж", "Њ")
689 })
690 b.Run("Han", func(b *testing.B) {
691 bench(b, "遠方", "來", "矣")
692 })
693 }
694
695 // Pathological worst-case. Consistency here is a good thing.
696 func BenchmarkIndexLateMatchSmallNeedle(b *testing.B) {
697 bench := func(b *testing.B, s1, s2 string) {
698 s := strings.Repeat(s1, 1_000/len(s1)) + s2
699 rs := []rune(s)
700 for i := 2; i <= 64; i *= 2 {
701 b.Run(strconv.Itoa(i), func(b *testing.B) {
702 benchmarkIndex(b, s, string(rs[len(rs)-i:]))
703 })
704 }
705 }
706 b.Run("Numeric", func(b *testing.B) {
707 bench(b, "123", "4")
708 })
709 b.Run("Latin", func(b *testing.B) {
710 bench(b, "abc", "d")
711 })
712 b.Run("Cyrillic", func(b *testing.B) {
713 bench(b, "А̀ВЄ", "Њ")
714 })
715 b.Run("Han", func(b *testing.B) {
716 bench(b, "遠方", "來")
717 })
718 }
719
720 // Pathological worst-case. Consistency here is a good thing.
721 func BenchmarkIndexEarlyMatchSmallNeedle(b *testing.B) {
722 bench := func(b *testing.B, s1, s2 string) {
723 for i := 2; i <= 32; i += 2 {
724 s := strings.Repeat(s1, i) + s2
725 substr := s1 + s2
726 b.Run(strconv.Itoa(i), func(b *testing.B) {
727 benchmarkIndex(b, s, substr)
728 })
729 }
730 }
731 b.Run("Latin", func(b *testing.B) {
732 bench(b, "AB", "C")
733 })
734 b.Run("Cyrillic", func(b *testing.B) {
735 bench(b, "А̀В", "Њ")
736 })
737 b.Run("Han", func(b *testing.B) {
738 bench(b, "遠方", "來")
739 })
740 }
741
742 // Thanks to variable length encoding it's possible the needle
743 // to be larger than the haystack.
744 func BenchmarkIndexNeedleExceedsHaystack(b *testing.B) {
745 s := strings.Repeat("А̀В", 32*1024)
746 substr := s + s[:len(s)/2] + "z"
747 i1 := strings.Index(s, substr)
748 i2 := Index(s, substr)
749 if i1 != i2 {
750 b.Fatalf("wrong index: expected: %d, got: %d", i1, i2)
751 }
752 // Can't compare perf to the stdlib because we have to scan
753 // the whole string and not just bail at the length mismatch.
754 b.SetBytes(int64(len(s)))
755 for i := 0; i < b.N; i++ {
756 Index(s, substr)
757 }
758 }
759
760 // Pathological worst-case. Consistency here is a good thing.
761 func BenchmarkLastIndexLateMatchSmallNeedle(b *testing.B) {
762 bench := func(b *testing.B, s1, s2 string) {
763 s := s2 + strings.Repeat(s1, 1_000/len(s1))
764 rs := []rune(s)
765 for _, i := range []int{2, 16, 32} {
766 b.Run(strconv.Itoa(i), func(b *testing.B) {
767 b.SetBytes(int64(len(s)))
768 substr := string(rs[:i])
769 for i := 0; i < b.N; i++ {
770 if j := LastIndex(s, substr); j != 0 {
771 b.Fatalf("LastIndex(%q, %q) = %d; want: %d", s, substr, j, 0)
772 }
773 }
774 })
775 }
776 }
777 b.Run("Cyrillic", func(b *testing.B) {
778 bench(b, "А̀ВЄ", "Њ")
779 })
780 b.Run("Han", func(b *testing.B) {
781 bench(b, "遠方", "來")
782 })
783 }
784
785 func makeBenchInputHard() string {
786 tokens := [...]string{
787 "<a>", "<p>", "<b>", "<strong>",
788 "</a>", "</p>", "</b>", "</strong>",
789 "hello", "world",
790 }
791 x := make([]byte, 0, 1<<20)
792 for {
793 i := rand.Intn(len(tokens))
794 if len(x)+len(tokens[i]) >= 1<<20 {
795 break
796 }
797 x = append(x, tokens[i]...)
798 }
799 return string(x)
800 }
801
802 var benchInputHard = makeBenchInputHard()
803
804 func benchmarkIndexHard(b *testing.B, sep string) {
805 benchmarkIndex(b, benchInputHard, sep)
806 }
807
808 func benchmarkLastIndexHard(b *testing.B, sep string) {
809 i := LastIndex(benchInputHard, sep)
810 if i < 0 {
811 b.SetBytes(int64(len(benchInputHard)))
812 } else {
813 b.SetBytes(int64(i + len(sep)))
814 }
815 for i := 0; i < b.N; i++ {
816 LastIndex(benchInputHard, sep)
817 }
818 }
819
820 func BenchmarkIndexHard1(b *testing.B) { benchmarkIndexHard(b, "<>") }
821 func BenchmarkIndexHard2(b *testing.B) { benchmarkIndexHard(b, "</pre>") }
822 func BenchmarkIndexHard3(b *testing.B) { benchmarkIndexHard(b, "<b>hello world</b>") }
823 func BenchmarkIndexHard4(b *testing.B) {
824 benchmarkIndexHard(b, "<pre><b>hello</b><strong>world</strong></pre>")
825 }
826
827 // TODO: these benchmarks are not very useful
828 func BenchmarkLastIndexHard1(b *testing.B) { benchmarkLastIndexHard(b, "<>") }
829 func BenchmarkLastIndexHard2(b *testing.B) { benchmarkLastIndexHard(b, "</pre>") }
830 func BenchmarkLastIndexHard3(b *testing.B) { benchmarkLastIndexHard(b, "<b>hello world</b>") }
831
832 // visitTable visits all runes in the given RangeTable in order, calling fn for each.
833 func visitTable(rt *unicode.RangeTable, fn func(rune)) {
834 for _, r16 := range rt.R16 {
835 for r := rune(r16.Lo); r <= rune(r16.Hi); r += rune(r16.Stride) {
836 fn(r)
837 }
838 }
839 for _, r32 := range rt.R32 {
840 for r := rune(r32.Lo); r <= rune(r32.Hi); r += rune(r32.Stride) {
841 fn(r)
842 }
843 }
844 }
845
846 func BenchmarkLastIndexRuneUnicode(b *testing.B) {
847 bench := func(b *testing.B, name string, rt *unicode.RangeTable) {
848 b.Run(name, func(b *testing.B) {
849 var rs []rune
850 visitTable(rt, func(r rune) {
851 if len(rs) < 1024 {
852 rs = append(rs, r)
853 }
854 })
855 s := string(rs)
856 r := rs[0]
857 b.SetBytes(int64(len(s)))
858 for i := 0; i < b.N; i++ {
859 lastIndexRune(s, r)
860 }
861 })
862 }
863 bench(b, "Han", unicode.Han) // no folds
864 bench(b, "Cyrillic", unicode.Cyrillic) // folds
865 }
866
867 var (
868 benchInputTorture = strings.Repeat("ABC", 1<<10) + "123" + strings.Repeat("ABC", 1<<10)
869 benchNeedleTorture = strings.Repeat("ABC", 1<<10+1)
870
871 benchInputTortureUnicode = strings.Repeat("ΑΒΔ", 1<<10) + "123" + strings.Repeat("ΑΒΔ", 1<<10)
872 benchNeedleTortureUnicode = strings.Repeat("ΑΒΔ", 1<<10+1)
873 )
874
875 func BenchmarkIndexTorture(b *testing.B) {
876 benchmarkIndex(b, benchInputTorture, benchNeedleTorture)
877 }
878
879 func BenchmarkIndexTortureUnicode(b *testing.B) {
880 benchmarkIndex(b, benchInputTortureUnicode, benchNeedleTortureUnicode)
881 }
882
883 func BenchmarkIndexPeriodic(b *testing.B) {
884 key := "aa"
885 for _, skip := range [...]int{2, 4, 8, 16, 32, 64} {
886 b.Run(fmt.Sprintf("IndexPeriodic%d", skip), func(b *testing.B) {
887 s := strings.Repeat("a"+strings.Repeat(" ", skip-1), 1<<16/skip)
888 benchmarkIndex(b, s, key)
889 })
890 }
891 }
892
893 func BenchmarkIndexPeriodicUnicode(b *testing.B) {
894 key := "αa"
895 for _, skip := range [...]int{2, 4, 8, 16, 32, 64} {
896 b.Run(fmt.Sprintf("IndexPeriodic%d", skip), func(b *testing.B) {
897 s := strings.Repeat("α"+strings.Repeat(" ", skip-1), 1<<16/skip)
898 benchmarkIndex(b, s, key)
899 })
900 }
901 }
902
903 func BenchmarkIndexNonASCII(b *testing.B) {
904 for _, size := range indexSizes {
905 b.Run(valName(size), func(b *testing.B) {
906 s := strings.Repeat("a", size-1) + string(rune(utf8.RuneSelf))
907 if i := IndexNonASCII(s); i < 0 {
908 b.Fatalf("IndexNonASCII(%q) = -1", s)
909 return
910 }
911 b.SetBytes(int64(len(s)))
912 for i := 0; i < b.N; i++ {
913 IndexNonASCII(s)
914 }
915 })
916 }
917 }
918
919 func BenchmarkHasPrefixASCII(b *testing.B) {
920 s0 := strings.Repeat("a", 64)
921 s1 := strings.Repeat("A", 64)
922 if !HasPrefix(s0, s1) {
923 b.Fatalf("HasPrefix(%[1]q, %[1]q) = false; want: true", s0, s1)
924 }
925 b.SetBytes(int64(len(s0)))
926 for i := 0; i < b.N; i++ {
927 HasPrefix(s0, s1)
928 }
929 }
930
931 func BenchmarkHasPrefix(b *testing.B) {
932 if !HasPrefix(benchmarkString, benchmarkString) {
933 b.Fatalf("HasPrefix(%[1]q, %[1]q) = false; want: true", benchmarkString)
934 }
935 b.SetBytes(int64(len(benchmarkString)))
936 for i := 0; i < b.N; i++ {
937 HasPrefix(benchmarkString, benchmarkString)
938 }
939 }
940
941 func BenchmarkHasPrefixUnicode(b *testing.B) {
942 const prefix = "Владимир Маяковский родился"
943 b.SetBytes(int64(len(prefix)))
944 for i := 0; i < b.N; i++ {
945 HasPrefix(prefix, "Владимир МАЯКОВСКИЙ родился")
946 }
947 }
948
949 func BenchmarkHasPrefixHard(b *testing.B) {
950 if !HasPrefix(benchInputHard, benchInputHard) {
951 b.Fatalf("HasPrefix(%[1]q, %[1]q) = false; want: true", benchInputHard)
952 }
953 b.SetBytes(int64(len(benchInputHard)))
954 for i := 0; i < b.N; i++ {
955 HasPrefix(benchInputHard, benchInputHard)
956 }
957 }
958
959 func BenchmarkHasPrefixRussian(b *testing.B) {
960 if !HasPrefix(russianLower, russianUpper) {
961 b.Fatalf("HasPrefix(%[1]q, %[1]q) = false; want: true", russianText)
962 }
963 b.SetBytes(int64(len(russianLower)))
964 for i := 0; i < b.N; i++ {
965 HasPrefix(russianLower, russianUpper)
966 }
967 }
968
969 func BenchmarkHasPrefixLonger(b *testing.B) {
970 prefix := strings.Repeat("\u212a", 32)
971 s := strings.Repeat("k", 32)
972 if !HasPrefix(s, prefix) {
973 b.Fatalf("HasPrefix(%q, %q) = false; want: true", s, prefix)
974 }
975
976 b.Run("Equal", func(b *testing.B) {
977 b.SetBytes(int64(len(prefix)))
978 for i := 0; i < b.N; i++ {
979 HasPrefix(s, prefix)
980 }
981 })
982
983 b.Run("ShortCircuitSize", func(b *testing.B) {
984 kprefix := prefix + "\u212a"
985 b.SetBytes(int64(len(kprefix)))
986 for i := 0; i < b.N; i++ {
987 HasPrefix(s, kprefix)
988 }
989 })
990
991 // Benchmark the overhead of checking for Kelvin
992 b.Run("KelvinCheck", func(b *testing.B) {
993 ks := s + "\u212a"
994 b.SetBytes(int64(len(ks)))
995 for i := 0; i < b.N; i++ {
996 containsKelvin(ks)
997 }
998 })
999 }
1000
1001 // TODO: need to compare against the stdlib
1002 func BenchmarkHasSuffix(b *testing.B) {
1003 if !HasSuffix(benchmarkString, benchmarkString) {
1004 b.Fatalf("HasSuffix(%[1]q, %[1]q) = false; want: true", benchmarkString)
1005 }
1006 for i := 0; i < b.N; i++ {
1007 HasSuffix(benchmarkString, benchmarkString)
1008 }
1009 }
1010
1011 // TODO: match the logic of HasPrefix
1012 // TODO: need to compare against the stdlib
1013 func BenchmarkHasSuffixRussian(b *testing.B) {
1014 if !HasSuffix(russianLower, russianUpper) {
1015 b.Fatalf("HasSuffix(%[1]q, %[1]q) = false; want: true", russianText)
1016 }
1017 b.SetBytes(int64(len(russianLower)))
1018 for i := 0; i < b.N; i++ {
1019 HasSuffix(russianLower, russianUpper)
1020 }
1021 }
1022
1023 func benchmarkIndexAny(b *testing.B, s, chars string) {
1024 i1 := strings.IndexAny(s, chars)
1025 i2 := IndexAny(s, chars)
1026 if i1 != i2 {
1027 b.Fatalf("strings.IndexAny != IndexAny: %d != %d", i1, i2)
1028 }
1029 min := len(s)
1030 for i, r := range chars {
1031 o := strings.IndexRune(s, r)
1032 if 0 <= o && o < min {
1033 min = i + utf8.RuneLen(r) // Include the length of the matched rune
1034 }
1035 }
1036 bytes := int64(min)
1037 if *benchStdLib {
1038 b.SetBytes(bytes)
1039 for i := 0; i < b.N; i++ {
1040 strings.IndexAny(s, chars)
1041 }
1042 } else {
1043 b.SetBytes(bytes)
1044 for i := 0; i < b.N; i++ {
1045 IndexAny(s, chars)
1046 }
1047 }
1048 }
1049
1050 func BenchmarkIndexAnyASCII(b *testing.B) {
1051 x := strings.Repeat("#", 2048) // Never matches set
1052 cs := "0123456789abcdefghijklmnopqrstuvwxyz0123456789abcdefghijklmnopqrstuvwxyz"
1053 for k := 1; k <= 2048; k <<= 4 {
1054 for j := 1; j <= 64; j <<= 1 {
1055 b.Run(fmt.Sprintf("%d:%d", k, j), func(b *testing.B) {
1056 benchmarkIndexAny(b, x[:k], cs[:j])
1057 })
1058 }
1059 }
1060 }
1061
1062 func BenchmarkIndexAnyUTF8(b *testing.B) {
1063 x := strings.Repeat("#", 2048) // Never matches set
1064 // TODO: use a more diverse string (diff languages)
1065 cs := "你好世界, hello world. 你好世界, hello world. 你好世界, hello world."
1066 for k := 1; k <= 2048; k <<= 4 {
1067 for j := 1; j <= 64; j <<= 1 {
1068 b.Run(fmt.Sprintf("%d:%d", k, j), func(b *testing.B) {
1069 var chars string
1070 n := j
1071 for i, r := range cs {
1072 n--
1073 if n <= 0 {
1074 chars = cs[:i+utf8.RuneLen(r)]
1075 break
1076 }
1077 }
1078 benchmarkIndexAny(b, x[:k], chars)
1079 })
1080 }
1081 }
1082 }
1083
1084 func benchmarkLastIndexAny(b *testing.B, s, chars string) {
1085 i1 := strings.LastIndexAny(s, chars)
1086 i2 := LastIndexAny(s, chars)
1087 if i1 != i2 {
1088 b.Fatalf("strings.LastIndexAny != LastIndexAny: %d != %d", i1, i2)
1089 }
1090 // TODO: make sure the logic here is correct
1091 i := strings.LastIndexAny(s, chars)
1092 if i < 0 {
1093 i = 0
1094 }
1095 bytes := int64(len(s) - i)
1096 if *benchStdLib {
1097 b.SetBytes(bytes)
1098 for i := 0; i < b.N; i++ {
1099 strings.LastIndexAny(s, chars)
1100 }
1101 } else {
1102 b.SetBytes(bytes)
1103 for i := 0; i < b.N; i++ {
1104 LastIndexAny(s, chars)
1105 }
1106 }
1107 }
1108
1109 func BenchmarkLastIndexAnyASCII(b *testing.B) {
1110 x := strings.Repeat("#", 2048) // Never matches set
1111 cs := "0123456789abcdefghijklmnopqrstuvwxyz0123456789abcdefghijklmnopqrstuvwxyz"
1112 for k := 1; k <= 2048; k <<= 4 {
1113 for j := 1; j <= 64; j <<= 1 {
1114 b.Run(fmt.Sprintf("%d:%d", k, j), func(b *testing.B) {
1115 benchmarkLastIndexAny(b, x[:k], cs[:j])
1116 })
1117 }
1118 }
1119 }
1120
1121 func BenchmarkLastIndexAnyUTF8(b *testing.B) {
1122 x := strings.Repeat("#", 2048) // Never matches set
1123 cs := "你好世界, hello world. 你好世界, hello world. 你好世界, hello world."
1124 for k := 1; k <= 2048; k <<= 4 {
1125 for j := 1; j <= 64; j <<= 1 {
1126 b.Run(fmt.Sprintf("%d:%d", k, j), func(b *testing.B) {
1127 benchmarkLastIndexAny(b, x[:k], cs[:j])
1128 })
1129 }
1130 }
1131 }
1132
1133 func BenchmarkCount(b *testing.B) {
1134 bench := func(name, s, sep string) {
1135 b.Run(name, func(b *testing.B) {
1136 i := strings.Count(strings.ToLower(s), strings.ToLower(sep))
1137 j := Count(s, sep)
1138 if i != j {
1139 b.Fatalf("Count(%q, %q) = %d; want: %d", s, sep, j, i)
1140 }
1141 b.SetBytes(int64(len(s)))
1142 for i := 0; i < b.N; i++ {
1143 Count(s, sep)
1144 }
1145 })
1146 }
1147 bench("ASCII_Torture", strings.Repeat("ab", 64), "ab")
1148 bench("ASCII_Short", strings.Repeat(" ab", 64), "ab")
1149 bench("ASCII_Long", strings.Repeat(
1150 " abcdefghijklmnopqrstuvwxyz", 64), "abcdefghijklmnopqrstuvwxyz")
1151 bench("Unicode", strings.Repeat("你好世界", 128), "你好世界")
1152 // Make sure we lazily process substr.
1153 bench("NoMatch", strings.Repeat("你", 8), strings.Repeat("好", 256))
1154 }
1155
1156 // Micro-benchmarks for caseFold
1157
1158 var caseFoldBenchmarkRunes = [16]rune{
1159 0xA7C9,
1160 0xA696,
1161 0x03A7,
1162 0x021E,
1163 0x03A3,
1164 0x01B5,
1165 0x01A6,
1166 0xABBC,
1167 0xA72C,
1168 0x1F8E,
1169 0x0056,
1170 0x016E,
1171 0x1E86,
1172 0x1C92,
1173 0x0555,
1174 0x0544,
1175 }
1176
1177 var caseFoldBenchmarkAll []rune
1178
1179 func loadCaseFoldBenchmarkAll() {
1180 if caseFoldBenchmarkAll != nil {
1181 return
1182 }
1183 a := make([]rune, 0, len(test.FoldableRunes()))
1184 for _, r := range test.FoldableRunes() {
1185 if tables.CaseFold(r) != r {
1186 a = append(a, r)
1187 }
1188 }
1189 // Make sure the slice is consistently sorted before
1190 // randomizing order. This is relevant because the
1191 // order of slice elements may change.
1192 less := func(i, j int) bool {
1193 return a[i] < a[j]
1194 }
1195 if !sort.SliceIsSorted(a, less) {
1196 sort.Slice(a, less)
1197 }
1198 rr := rand.New(rand.NewSource(12345))
1199 rr.Shuffle(len(a), func(i, j int) {
1200 a[i], a[j] = a[j], a[i]
1201 })
1202 caseFoldBenchmarkAll = a
1203 }
1204
1205 func BenchmarkCaseFold(b *testing.B) {
1206 for i := 0; i < b.N; i++ {
1207 _ = tables.CaseFold(caseFoldBenchmarkRunes[i%len(caseFoldBenchmarkRunes)])
1208 }
1209 }
1210
1211 func BenchmarkCaseFoldAll(b *testing.B) {
1212 loadCaseFoldBenchmarkAll()
1213 for i := 0; i < b.N; i++ {
1214 for j := i; j < len(caseFoldBenchmarkAll) && j < b.N; j++ {
1215 _ = tables.CaseFold(caseFoldBenchmarkAll[j])
1216 }
1217 }
1218 }
1219
1220 // Micro-benchmarks for toUpperLower
1221
1222 var toUpperLowerBenchmarkRunes = [16]rune{
1223 0xA68A,
1224 0x0204,
1225 0x04EC,
1226 0x00D0,
1227 0x0053,
1228 0xA698,
1229 0x1F1A,
1230 0x038E,
1231 0x1F1B,
1232 0x2126,
1233 0x16E47,
1234 0x01D1,
1235 0x13CC,
1236 0x01BC,
1237 0x048E,
1238 0x0386,
1239 }
1240
1241 func BenchmarkToUpperLower(b *testing.B) {
1242 for i := 0; i < b.N; i++ {
1243 _, _, _ = tables.ToUpperLower(toUpperLowerBenchmarkRunes[i%len(toUpperLowerBenchmarkRunes)])
1244 }
1245 }
1246
1247 func BenchmarkNonLetterASCII(b *testing.B) {
1248 base := "!\"#$%&'()*+,-./0123456789:;<=>?@[\\]^_`{|}~"
1249 base += base + base + base
1250 for _, size := range []int{4, 8, 16, 24, 32, 64, 128} {
1251 b.Run(fmt.Sprint(size), func(b *testing.B) {
1252 s := base[:size]
1253 b.SetBytes(int64(len(s)))
1254 for i := 0; i < b.N; i++ {
1255 nonLetterASCII(s)
1256 }
1257 })
1258 }
1259 }