Source file
src/strings/strings_test.go
1
2
3
4
5 package strings_test
6
7 import (
8 "bytes"
9 "fmt"
10 "io"
11 "iter"
12 "math"
13 "math/rand"
14 "slices"
15 "strconv"
16 . "strings"
17 "testing"
18 "unicode"
19 "unicode/utf8"
20 "unsafe"
21 )
22
23 func collect(t *testing.T, seq iter.Seq[string]) []string {
24 out := slices.Collect(seq)
25 out1 := slices.Collect(seq)
26 if !slices.Equal(out, out1) {
27 t.Fatalf("inconsistent seq:\n%s\n%s", out, out1)
28 }
29 return out
30 }
31
32 type LinesTest struct {
33 a string
34 b []string
35 }
36
37 var linesTests = []LinesTest{
38 {a: "abc\nabc\n", b: []string{"abc\n", "abc\n"}},
39 {a: "abc\r\nabc", b: []string{"abc\r\n", "abc"}},
40 {a: "abc\r\n", b: []string{"abc\r\n"}},
41 {a: "\nabc", b: []string{"\n", "abc"}},
42 {a: "\nabc\n\n", b: []string{"\n", "abc\n", "\n"}},
43 }
44
45 func TestLines(t *testing.T) {
46 for _, s := range linesTests {
47 result := slices.Collect(Lines(s.a))
48 if !slices.Equal(result, s.b) {
49 t.Errorf(`slices.Collect(Lines(%q)) = %q; want %q`, s.a, result, s.b)
50 }
51 }
52 }
53
54 var abcd = "abcd"
55 var faces = "☺☻☹"
56 var commas = "1,2,3,4"
57 var dots = "1....2....3....4"
58
59 type IndexTest struct {
60 s string
61 sep string
62 out int
63 }
64
65 var indexTests = []IndexTest{
66 {"", "", 0},
67 {"", "a", -1},
68 {"", "foo", -1},
69 {"fo", "foo", -1},
70 {"foo", "foo", 0},
71 {"oofofoofooo", "f", 2},
72 {"oofofoofooo", "foo", 4},
73 {"barfoobarfoo", "foo", 3},
74 {"foo", "", 0},
75 {"foo", "o", 1},
76 {"abcABCabc", "A", 3},
77 {"jrzm6jjhorimglljrea4w3rlgosts0w2gia17hno2td4qd1jz", "jz", 47},
78 {"ekkuk5oft4eq0ocpacknhwouic1uua46unx12l37nioq9wbpnocqks6", "ks6", 52},
79 {"999f2xmimunbuyew5vrkla9cpwhmxan8o98ec", "98ec", 33},
80 {"9lpt9r98i04k8bz6c6dsrthb96bhi", "96bhi", 24},
81 {"55u558eqfaod2r2gu42xxsu631xf0zobs5840vl", "5840vl", 33},
82
83 {"", "a", -1},
84 {"x", "a", -1},
85 {"x", "x", 0},
86 {"abc", "a", 0},
87 {"abc", "b", 1},
88 {"abc", "c", 2},
89 {"abc", "x", -1},
90
91 {"", "ab", -1},
92 {"bc", "ab", -1},
93 {"ab", "ab", 0},
94 {"xab", "ab", 1},
95 {"xab"[:2], "ab", -1},
96 {"", "abc", -1},
97 {"xbc", "abc", -1},
98 {"abc", "abc", 0},
99 {"xabc", "abc", 1},
100 {"xabc"[:3], "abc", -1},
101 {"xabxc", "abc", -1},
102 {"", "abcd", -1},
103 {"xbcd", "abcd", -1},
104 {"abcd", "abcd", 0},
105 {"xabcd", "abcd", 1},
106 {"xyabcd"[:5], "abcd", -1},
107 {"xbcqq", "abcqq", -1},
108 {"abcqq", "abcqq", 0},
109 {"xabcqq", "abcqq", 1},
110 {"xyabcqq"[:6], "abcqq", -1},
111 {"xabxcqq", "abcqq", -1},
112 {"xabcqxq", "abcqq", -1},
113 {"", "01234567", -1},
114 {"32145678", "01234567", -1},
115 {"01234567", "01234567", 0},
116 {"x01234567", "01234567", 1},
117 {"x0123456x01234567", "01234567", 9},
118 {"xx01234567"[:9], "01234567", -1},
119 {"", "0123456789", -1},
120 {"3214567844", "0123456789", -1},
121 {"0123456789", "0123456789", 0},
122 {"x0123456789", "0123456789", 1},
123 {"x012345678x0123456789", "0123456789", 11},
124 {"xyz0123456789"[:12], "0123456789", -1},
125 {"x01234567x89", "0123456789", -1},
126 {"", "0123456789012345", -1},
127 {"3214567889012345", "0123456789012345", -1},
128 {"0123456789012345", "0123456789012345", 0},
129 {"x0123456789012345", "0123456789012345", 1},
130 {"x012345678901234x0123456789012345", "0123456789012345", 17},
131 {"", "01234567890123456789", -1},
132 {"32145678890123456789", "01234567890123456789", -1},
133 {"01234567890123456789", "01234567890123456789", 0},
134 {"x01234567890123456789", "01234567890123456789", 1},
135 {"x0123456789012345678x01234567890123456789", "01234567890123456789", 21},
136 {"xyz01234567890123456789"[:22], "01234567890123456789", -1},
137 {"", "0123456789012345678901234567890", -1},
138 {"321456788901234567890123456789012345678911", "0123456789012345678901234567890", -1},
139 {"0123456789012345678901234567890", "0123456789012345678901234567890", 0},
140 {"x0123456789012345678901234567890", "0123456789012345678901234567890", 1},
141 {"x012345678901234567890123456789x0123456789012345678901234567890", "0123456789012345678901234567890", 32},
142 {"xyz0123456789012345678901234567890"[:33], "0123456789012345678901234567890", -1},
143 {"", "01234567890123456789012345678901", -1},
144 {"32145678890123456789012345678901234567890211", "01234567890123456789012345678901", -1},
145 {"01234567890123456789012345678901", "01234567890123456789012345678901", 0},
146 {"x01234567890123456789012345678901", "01234567890123456789012345678901", 1},
147 {"x0123456789012345678901234567890x01234567890123456789012345678901", "01234567890123456789012345678901", 33},
148 {"xyz01234567890123456789012345678901"[:34], "01234567890123456789012345678901", -1},
149 {"xxxxxx012345678901234567890123456789012345678901234567890123456789012", "012345678901234567890123456789012345678901234567890123456789012", 6},
150 {"", "0123456789012345678901234567890123456789", -1},
151 {"xx012345678901234567890123456789012345678901234567890123456789012", "0123456789012345678901234567890123456789", 2},
152 {"xx012345678901234567890123456789012345678901234567890123456789012"[:41], "0123456789012345678901234567890123456789", -1},
153 {"xx012345678901234567890123456789012345678901234567890123456789012", "0123456789012345678901234567890123456xxx", -1},
154 {"xx0123456789012345678901234567890123456789012345678901234567890120123456789012345678901234567890123456xxx", "0123456789012345678901234567890123456xxx", 65},
155
156 {"oxoxoxoxoxoxoxoxoxoxoxoy", "oy", 22},
157 {"oxoxoxoxoxoxoxoxoxoxoxox", "oy", -1},
158
159 {"oxoxoxoxoxoxoxoxoxoxox☺", "☺", 22},
160
161
162 {"xx0123456789012345678901234567890123456789012345678901234567890120123456789012345678901234567890123456xxx\xed\x9f\xc0", "\xed\x9f\xc0", 105},
163 }
164
165 var lastIndexTests = []IndexTest{
166 {"", "", 0},
167 {"", "a", -1},
168 {"", "foo", -1},
169 {"fo", "foo", -1},
170 {"foo", "foo", 0},
171 {"foo", "f", 0},
172 {"oofofoofooo", "f", 7},
173 {"oofofoofooo", "foo", 7},
174 {"barfoobarfoo", "foo", 9},
175 {"foo", "", 3},
176 {"foo", "o", 2},
177 {"abcABCabc", "A", 3},
178 {"abcABCabc", "a", 6},
179 }
180
181 var indexAnyTests = []IndexTest{
182 {"", "", -1},
183 {"", "a", -1},
184 {"", "abc", -1},
185 {"a", "", -1},
186 {"a", "a", 0},
187 {"\x80", "\xffb", 0},
188 {"aaa", "a", 0},
189 {"abc", "xyz", -1},
190 {"abc", "xcz", 2},
191 {"ab☺c", "x☺yz", 2},
192 {"a☺b☻c☹d", "cx", len("a☺b☻")},
193 {"a☺b☻c☹d", "uvw☻xyz", len("a☺b")},
194 {"aRegExp*", ".(|)*+?^$[]", 7},
195 {dots + dots + dots, " ", -1},
196 {"012abcba210", "\xffb", 4},
197 {"012\x80bcb\x80210", "\xffb", 3},
198 {"0123456\xcf\x80abc", "\xcfb\x80", 10},
199 }
200
201 var lastIndexAnyTests = []IndexTest{
202 {"", "", -1},
203 {"", "a", -1},
204 {"", "abc", -1},
205 {"a", "", -1},
206 {"a", "a", 0},
207 {"\x80", "\xffb", 0},
208 {"aaa", "a", 2},
209 {"abc", "xyz", -1},
210 {"abc", "ab", 1},
211 {"ab☺c", "x☺yz", 2},
212 {"a☺b☻c☹d", "cx", len("a☺b☻")},
213 {"a☺b☻c☹d", "uvw☻xyz", len("a☺b")},
214 {"a.RegExp*", ".(|)*+?^$[]", 8},
215 {dots + dots + dots, " ", -1},
216 {"012abcba210", "\xffb", 6},
217 {"012\x80bcb\x80210", "\xffb", 7},
218 {"0123456\xcf\x80abc", "\xcfb\x80", 10},
219 }
220
221
222
223 func runIndexTests(t *testing.T, f func(s, sep string) int, funcName string, testCases []IndexTest) {
224 for _, test := range testCases {
225 actual := f(test.s, test.sep)
226 if actual != test.out {
227 t.Errorf("%s(%q,%q) = %v; want %v", funcName, test.s, test.sep, actual, test.out)
228 }
229 }
230 }
231
232 func TestIndex(t *testing.T) { runIndexTests(t, Index, "Index", indexTests) }
233 func TestLastIndex(t *testing.T) { runIndexTests(t, LastIndex, "LastIndex", lastIndexTests) }
234 func TestIndexAny(t *testing.T) { runIndexTests(t, IndexAny, "IndexAny", indexAnyTests) }
235 func TestLastIndexAny(t *testing.T) {
236 runIndexTests(t, LastIndexAny, "LastIndexAny", lastIndexAnyTests)
237 }
238
239 func TestIndexByte(t *testing.T) {
240 for _, tt := range indexTests {
241 if len(tt.sep) != 1 {
242 continue
243 }
244 pos := IndexByte(tt.s, tt.sep[0])
245 if pos != tt.out {
246 t.Errorf(`IndexByte(%q, %q) = %v; want %v`, tt.s, tt.sep[0], pos, tt.out)
247 }
248 }
249 }
250
251 func TestLastIndexByte(t *testing.T) {
252 testCases := []IndexTest{
253 {"", "q", -1},
254 {"abcdef", "q", -1},
255 {"abcdefabcdef", "a", len("abcdef")},
256 {"abcdefabcdef", "f", len("abcdefabcde")},
257 {"zabcdefabcdef", "z", 0},
258 {"a☺b☻c☹d", "b", len("a☺")},
259 }
260 for _, test := range testCases {
261 actual := LastIndexByte(test.s, test.sep[0])
262 if actual != test.out {
263 t.Errorf("LastIndexByte(%q,%c) = %v; want %v", test.s, test.sep[0], actual, test.out)
264 }
265 }
266 }
267
268 func simpleIndex(s, sep string) int {
269 n := len(sep)
270 for i := n; i <= len(s); i++ {
271 if s[i-n:i] == sep {
272 return i - n
273 }
274 }
275 return -1
276 }
277
278 func TestIndexRandom(t *testing.T) {
279 const chars = "abcdefghijklmnopqrstuvwxyz0123456789"
280 for times := 0; times < 10; times++ {
281 for strLen := 5 + rand.Intn(5); strLen < 140; strLen += 10 {
282 s1 := make([]byte, strLen)
283 for i := range s1 {
284 s1[i] = chars[rand.Intn(len(chars))]
285 }
286 s := string(s1)
287 for i := 0; i < 50; i++ {
288 begin := rand.Intn(len(s) + 1)
289 end := begin + rand.Intn(len(s)+1-begin)
290 sep := s[begin:end]
291 if i%4 == 0 {
292 pos := rand.Intn(len(sep) + 1)
293 sep = sep[:pos] + "A" + sep[pos:]
294 }
295 want := simpleIndex(s, sep)
296 res := Index(s, sep)
297 if res != want {
298 t.Errorf("Index(%s,%s) = %d; want %d", s, sep, res, want)
299 }
300 }
301 }
302 }
303 }
304
305 func TestIndexRune(t *testing.T) {
306 tests := []struct {
307 in string
308 rune rune
309 want int
310 }{
311 {"", 'a', -1},
312 {"", '☺', -1},
313 {"foo", '☹', -1},
314 {"foo", 'o', 1},
315 {"foo☺bar", '☺', 3},
316 {"foo☺☻☹bar", '☹', 9},
317 {"a A x", 'A', 2},
318 {"some_text=some_value", '=', 9},
319 {"☺a", 'a', 3},
320 {"a☻☺b", '☺', 4},
321
322
323 {"�", '�', 0},
324 {"\xff", '�', 0},
325 {"☻x�", '�', len("☻x")},
326 {"☻x\xe2\x98", '�', len("☻x")},
327 {"☻x\xe2\x98�", '�', len("☻x")},
328 {"☻x\xe2\x98x", '�', len("☻x")},
329
330
331 {"a☺b☻c☹d\xe2\x98�\xff�\xed\xa0\x80", -1, -1},
332 {"a☺b☻c☹d\xe2\x98�\xff�\xed\xa0\x80", 0xD800, -1},
333 {"a☺b☻c☹d\xe2\x98�\xff�\xed\xa0\x80", utf8.MaxRune + 1, -1},
334
335
336 {"ӆ", 'ӆ', 0},
337 {"a", 'ӆ', -1},
338 {" ӆ", 'ӆ', 2},
339 {" a", 'ӆ', -1},
340 {Repeat("ц", 64) + "ӆ", 'ӆ', 128},
341 {Repeat("Ꙁ", 64) + "Ꚁ", '䚀', -1},
342
343
344 {"Ꚁ", 'Ꚁ', 0},
345 {"a", 'Ꚁ', -1},
346 {" Ꚁ", 'Ꚁ', 2},
347 {" a", 'Ꚁ', -1},
348 {Repeat("Ꙁ", 64) + "Ꚁ", 'Ꚁ', 192},
349 {Repeat("𡋀", 64) + "𡌀", '𣌀', -1},
350
351
352 {"𡌀", '𡌀', 0},
353 {"a", '𡌀', -1},
354 {" 𡌀", '𡌀', 2},
355 {" a", '𡌀', -1},
356 {Repeat("𡋀", 64) + "𡌀", '𡌀', 256},
357 {Repeat("𡋀", 64), '𡌀', -1},
358
359
360
361 {"aaaaaKKKK\U000bc104", '\U000bc104', 17},
362 {"aaaaaKKKK鄄", '鄄', 17},
363 {"aaKKKKKa\U000bc104", '\U000bc104', 18},
364 {"aaKKKKKa鄄", '鄄', 18},
365 }
366 for _, tt := range tests {
367 if got := IndexRune(tt.in, tt.rune); got != tt.want {
368 t.Errorf("IndexRune(%q, %d) = %v; want %v", tt.in, tt.rune, got, tt.want)
369 }
370 }
371
372
373 haystack := "test" + Repeat("𡋀", 32) + "𡌀"
374 allocs := testing.AllocsPerRun(1000, func() {
375 if i := IndexRune(haystack, 's'); i != 2 {
376 t.Fatalf("'s' at %d; want 2", i)
377 }
378 if i := IndexRune(haystack, '𡌀'); i != 132 {
379 t.Fatalf("'𡌀' at %d; want 4", i)
380 }
381 })
382 if allocs != 0 && testing.CoverMode() == "" {
383 t.Errorf("expected no allocations, got %f", allocs)
384 }
385 }
386
387 const benchmarkString = "some_text=some☺value"
388
389 func BenchmarkIndexRune(b *testing.B) {
390 if got := IndexRune(benchmarkString, '☺'); got != 14 {
391 b.Fatalf("wrong index: expected 14, got=%d", got)
392 }
393 for i := 0; i < b.N; i++ {
394 IndexRune(benchmarkString, '☺')
395 }
396 }
397
398 var benchmarkLongString = Repeat(" ", 100) + benchmarkString
399
400 func BenchmarkIndexRuneLongString(b *testing.B) {
401 if got := IndexRune(benchmarkLongString, '☺'); got != 114 {
402 b.Fatalf("wrong index: expected 114, got=%d", got)
403 }
404 for i := 0; i < b.N; i++ {
405 IndexRune(benchmarkLongString, '☺')
406 }
407 }
408
409 func BenchmarkIndexRuneFastPath(b *testing.B) {
410 if got := IndexRune(benchmarkString, 'v'); got != 17 {
411 b.Fatalf("wrong index: expected 17, got=%d", got)
412 }
413 for i := 0; i < b.N; i++ {
414 IndexRune(benchmarkString, 'v')
415 }
416 }
417
418 func BenchmarkIndex(b *testing.B) {
419 if got := Index(benchmarkString, "v"); got != 17 {
420 b.Fatalf("wrong index: expected 17, got=%d", got)
421 }
422 for i := 0; i < b.N; i++ {
423 Index(benchmarkString, "v")
424 }
425 }
426
427 func BenchmarkLastIndex(b *testing.B) {
428 if got := Index(benchmarkString, "v"); got != 17 {
429 b.Fatalf("wrong index: expected 17, got=%d", got)
430 }
431 for i := 0; i < b.N; i++ {
432 LastIndex(benchmarkString, "v")
433 }
434 }
435
436 func BenchmarkIndexByte(b *testing.B) {
437 if got := IndexByte(benchmarkString, 'v'); got != 17 {
438 b.Fatalf("wrong index: expected 17, got=%d", got)
439 }
440 for i := 0; i < b.N; i++ {
441 IndexByte(benchmarkString, 'v')
442 }
443 }
444
445 type SplitTest struct {
446 s string
447 sep string
448 n int
449 a []string
450 }
451
452 var splittests = []SplitTest{
453 {"", "", -1, []string{}},
454 {abcd, "", 2, []string{"a", "bcd"}},
455 {abcd, "", 4, []string{"a", "b", "c", "d"}},
456 {abcd, "", -1, []string{"a", "b", "c", "d"}},
457 {faces, "", -1, []string{"☺", "☻", "☹"}},
458 {faces, "", 3, []string{"☺", "☻", "☹"}},
459 {faces, "", 17, []string{"☺", "☻", "☹"}},
460 {"☺�☹", "", -1, []string{"☺", "�", "☹"}},
461 {abcd, "a", 0, nil},
462 {abcd, "a", -1, []string{"", "bcd"}},
463 {abcd, "z", -1, []string{"abcd"}},
464 {commas, ",", -1, []string{"1", "2", "3", "4"}},
465 {dots, "...", -1, []string{"1", ".2", ".3", ".4"}},
466 {faces, "☹", -1, []string{"☺☻", ""}},
467 {faces, "~", -1, []string{faces}},
468 {"1 2 3 4", " ", 3, []string{"1", "2", "3 4"}},
469 {"1 2", " ", 3, []string{"1", "2"}},
470 {"", "T", math.MaxInt / 4, []string{""}},
471 {"\xff-\xff", "", -1, []string{"\xff", "-", "\xff"}},
472 {"\xff-\xff", "-", -1, []string{"\xff", "\xff"}},
473 }
474
475 func TestSplit(t *testing.T) {
476 for _, tt := range splittests {
477 a := SplitN(tt.s, tt.sep, tt.n)
478 if !slices.Equal(a, tt.a) {
479 t.Errorf("Split(%q, %q, %d) = %v; want %v", tt.s, tt.sep, tt.n, a, tt.a)
480 continue
481 }
482 if tt.n < 0 {
483 a2 := slices.Collect(SplitSeq(tt.s, tt.sep))
484 if !slices.Equal(a2, tt.a) {
485 t.Errorf(`collect(SplitSeq(%q, %q)) = %v; want %v`, tt.s, tt.sep, a2, tt.a)
486 }
487 }
488 if tt.n == 0 {
489 continue
490 }
491 s := Join(a, tt.sep)
492 if s != tt.s {
493 t.Errorf("Join(Split(%q, %q, %d), %q) = %q", tt.s, tt.sep, tt.n, tt.sep, s)
494 }
495 if tt.n < 0 {
496 b := Split(tt.s, tt.sep)
497 if !slices.Equal(a, b) {
498 t.Errorf("Split disagrees with SplitN(%q, %q, %d) = %v; want %v", tt.s, tt.sep, tt.n, b, a)
499 }
500 }
501 }
502 }
503
504 var splitaftertests = []SplitTest{
505 {abcd, "a", -1, []string{"a", "bcd"}},
506 {abcd, "z", -1, []string{"abcd"}},
507 {abcd, "", -1, []string{"a", "b", "c", "d"}},
508 {commas, ",", -1, []string{"1,", "2,", "3,", "4"}},
509 {dots, "...", -1, []string{"1...", ".2...", ".3...", ".4"}},
510 {faces, "☹", -1, []string{"☺☻☹", ""}},
511 {faces, "~", -1, []string{faces}},
512 {faces, "", -1, []string{"☺", "☻", "☹"}},
513 {"1 2 3 4", " ", 3, []string{"1 ", "2 ", "3 4"}},
514 {"1 2 3", " ", 3, []string{"1 ", "2 ", "3"}},
515 {"1 2", " ", 3, []string{"1 ", "2"}},
516 {"123", "", 2, []string{"1", "23"}},
517 {"123", "", 17, []string{"1", "2", "3"}},
518 }
519
520 func TestSplitAfter(t *testing.T) {
521 for _, tt := range splitaftertests {
522 a := SplitAfterN(tt.s, tt.sep, tt.n)
523 if !slices.Equal(a, tt.a) {
524 t.Errorf(`Split(%q, %q, %d) = %v; want %v`, tt.s, tt.sep, tt.n, a, tt.a)
525 continue
526 }
527 if tt.n < 0 {
528 a2 := slices.Collect(SplitAfterSeq(tt.s, tt.sep))
529 if !slices.Equal(a2, tt.a) {
530 t.Errorf(`collect(SplitAfterSeq(%q, %q)) = %v; want %v`, tt.s, tt.sep, a2, tt.a)
531 }
532 }
533 s := Join(a, "")
534 if s != tt.s {
535 t.Errorf(`Join(Split(%q, %q, %d), %q) = %q`, tt.s, tt.sep, tt.n, tt.sep, s)
536 }
537 if tt.n < 0 {
538 b := SplitAfter(tt.s, tt.sep)
539 if !slices.Equal(a, b) {
540 t.Errorf("SplitAfter disagrees with SplitAfterN(%q, %q, %d) = %v; want %v", tt.s, tt.sep, tt.n, b, a)
541 }
542 }
543 }
544 }
545
546 type FieldsTest struct {
547 s string
548 a []string
549 }
550
551 var fieldstests = []FieldsTest{
552 {"", []string{}},
553 {" ", []string{}},
554 {" \t ", []string{}},
555 {"\u2000", []string{}},
556 {" abc ", []string{"abc"}},
557 {"1 2 3 4", []string{"1", "2", "3", "4"}},
558 {"1 2 3 4", []string{"1", "2", "3", "4"}},
559 {"1\t\t2\t\t3\t4", []string{"1", "2", "3", "4"}},
560 {"1\u20002\u20013\u20024", []string{"1", "2", "3", "4"}},
561 {"\u2000\u2001\u2002", []string{}},
562 {"\n™\t™\n", []string{"™", "™"}},
563 {"\n\u20001™2\u2000 \u2001 ™", []string{"1™2", "™"}},
564 {"\n1\uFFFD \uFFFD2\u20003\uFFFD4", []string{"1\uFFFD", "\uFFFD2", "3\uFFFD4"}},
565 {"1\xFF\u2000\xFF2\xFF \xFF", []string{"1\xFF", "\xFF2\xFF", "\xFF"}},
566 {faces, []string{faces}},
567 }
568
569 func TestFields(t *testing.T) {
570 for _, tt := range fieldstests {
571 a := Fields(tt.s)
572 if !slices.Equal(a, tt.a) {
573 t.Errorf("Fields(%q) = %v; want %v", tt.s, a, tt.a)
574 continue
575 }
576 a2 := collect(t, FieldsSeq(tt.s))
577 if !slices.Equal(a2, tt.a) {
578 t.Errorf(`collect(FieldsSeq(%q)) = %v; want %v`, tt.s, a2, tt.a)
579 }
580 }
581 }
582
583 var FieldsFuncTests = []FieldsTest{
584 {"", []string{}},
585 {"XX", []string{}},
586 {"XXhiXXX", []string{"hi"}},
587 {"aXXbXXXcX", []string{"a", "b", "c"}},
588 }
589
590 func TestFieldsFunc(t *testing.T) {
591 for _, tt := range fieldstests {
592 a := FieldsFunc(tt.s, unicode.IsSpace)
593 if !slices.Equal(a, tt.a) {
594 t.Errorf("FieldsFunc(%q, unicode.IsSpace) = %v; want %v", tt.s, a, tt.a)
595 continue
596 }
597 }
598 pred := func(c rune) bool { return c == 'X' }
599 for _, tt := range FieldsFuncTests {
600 a := FieldsFunc(tt.s, pred)
601 if !slices.Equal(a, tt.a) {
602 t.Errorf("FieldsFunc(%q) = %v, want %v", tt.s, a, tt.a)
603 }
604 a2 := collect(t, FieldsFuncSeq(tt.s, pred))
605 if !slices.Equal(a2, tt.a) {
606 t.Errorf(`collect(FieldsFuncSeq(%q)) = %v; want %v`, tt.s, a2, tt.a)
607 }
608 }
609 }
610
611
612 type StringTest struct {
613 in, out string
614 }
615
616
617
618 func runStringTests(t *testing.T, f func(string) string, funcName string, testCases []StringTest) {
619 for _, tc := range testCases {
620 actual := f(tc.in)
621 if actual != tc.out {
622 t.Errorf("%s(%q) = %q; want %q", funcName, tc.in, actual, tc.out)
623 }
624 }
625 }
626
627 var upperTests = []StringTest{
628 {"", ""},
629 {"ONLYUPPER", "ONLYUPPER"},
630 {"abc", "ABC"},
631 {"AbC123", "ABC123"},
632 {"azAZ09_", "AZAZ09_"},
633 {"longStrinGwitHmixofsmaLLandcAps", "LONGSTRINGWITHMIXOFSMALLANDCAPS"},
634 {"RENAN BASTOS 93 AOSDAJDJAIDJAIDAJIaidsjjaidijadsjiadjiOOKKO", "RENAN BASTOS 93 AOSDAJDJAIDJAIDAJIAIDSJJAIDIJADSJIADJIOOKKO"},
635 {"long\u0250string\u0250with\u0250nonascii\u2C6Fchars", "LONG\u2C6FSTRING\u2C6FWITH\u2C6FNONASCII\u2C6FCHARS"},
636 {"\u0250\u0250\u0250\u0250\u0250", "\u2C6F\u2C6F\u2C6F\u2C6F\u2C6F"},
637 {"a\u0080\U0010FFFF", "A\u0080\U0010FFFF"},
638 }
639
640 var lowerTests = []StringTest{
641 {"", ""},
642 {"abc", "abc"},
643 {"AbC123", "abc123"},
644 {"azAZ09_", "azaz09_"},
645 {"longStrinGwitHmixofsmaLLandcAps", "longstringwithmixofsmallandcaps"},
646 {"renan bastos 93 AOSDAJDJAIDJAIDAJIaidsjjaidijadsjiadjiOOKKO", "renan bastos 93 aosdajdjaidjaidajiaidsjjaidijadsjiadjiookko"},
647 {"LONG\u2C6FSTRING\u2C6FWITH\u2C6FNONASCII\u2C6FCHARS", "long\u0250string\u0250with\u0250nonascii\u0250chars"},
648 {"\u2C6D\u2C6D\u2C6D\u2C6D\u2C6D", "\u0251\u0251\u0251\u0251\u0251"},
649 {"A\u0080\U0010FFFF", "a\u0080\U0010FFFF"},
650 }
651
652 const space = "\t\v\r\f\n\u0085\u00a0\u2000\u3000"
653
654 var trimSpaceTests = []StringTest{
655 {"", ""},
656 {"abc", "abc"},
657 {space + "abc" + space, "abc"},
658 {" ", ""},
659 {" \t\r\n \t\t\r\r\n\n ", ""},
660 {" \t\r\n x\t\t\r\r\n\n ", "x"},
661 {" \u2000\t\r\n x\t\t\r\r\ny\n \u3000", "x\t\t\r\r\ny"},
662 {"1 \t\r\n2", "1 \t\r\n2"},
663 {" x\x80", "x\x80"},
664 {" x\xc0", "x\xc0"},
665 {"x \xc0\xc0 ", "x \xc0\xc0"},
666 {"x \xc0", "x \xc0"},
667 {"x \xc0 ", "x \xc0"},
668 {"x \xc0\xc0 ", "x \xc0\xc0"},
669 {"x ☺\xc0\xc0 ", "x ☺\xc0\xc0"},
670 {"x ☺ ", "x ☺"},
671 }
672
673 func tenRunes(ch rune) string {
674 r := make([]rune, 10)
675 for i := range r {
676 r[i] = ch
677 }
678 return string(r)
679 }
680
681
682 func rot13(r rune) rune {
683 step := rune(13)
684 if r >= 'a' && r <= 'z' {
685 return ((r - 'a' + step) % 26) + 'a'
686 }
687 if r >= 'A' && r <= 'Z' {
688 return ((r - 'A' + step) % 26) + 'A'
689 }
690 return r
691 }
692
693 func TestMap(t *testing.T) {
694
695 a := tenRunes('a')
696
697 maxRune := func(rune) rune { return unicode.MaxRune }
698 m := Map(maxRune, a)
699 expect := tenRunes(unicode.MaxRune)
700 if m != expect {
701 t.Errorf("growing: expected %q got %q", expect, m)
702 }
703
704
705 minRune := func(rune) rune { return 'a' }
706 m = Map(minRune, tenRunes(unicode.MaxRune))
707 expect = a
708 if m != expect {
709 t.Errorf("shrinking: expected %q got %q", expect, m)
710 }
711
712
713 m = Map(rot13, "a to zed")
714 expect = "n gb mrq"
715 if m != expect {
716 t.Errorf("rot13: expected %q got %q", expect, m)
717 }
718
719
720 m = Map(rot13, Map(rot13, "a to zed"))
721 expect = "a to zed"
722 if m != expect {
723 t.Errorf("rot13: expected %q got %q", expect, m)
724 }
725
726
727 dropNotLatin := func(r rune) rune {
728 if unicode.Is(unicode.Latin, r) {
729 return r
730 }
731 return -1
732 }
733 m = Map(dropNotLatin, "Hello, 세계")
734 expect = "Hello"
735 if m != expect {
736 t.Errorf("drop: expected %q got %q", expect, m)
737 }
738
739
740 identity := func(r rune) rune {
741 return r
742 }
743 orig := "Input string that we expect not to be copied."
744 m = Map(identity, orig)
745 if unsafe.StringData(orig) != unsafe.StringData(m) {
746 t.Error("unexpected copy during identity map")
747 }
748
749
750 replaceNotLatin := func(r rune) rune {
751 if unicode.Is(unicode.Latin, r) {
752 return r
753 }
754 return utf8.RuneError
755 }
756 m = Map(replaceNotLatin, "Hello\255World")
757 expect = "Hello\uFFFDWorld"
758 if m != expect {
759 t.Errorf("replace invalid sequence: expected %q got %q", expect, m)
760 }
761
762
763 encode := func(r rune) rune {
764 switch r {
765 case utf8.RuneSelf:
766 return unicode.MaxRune
767 case unicode.MaxRune:
768 return utf8.RuneSelf
769 }
770 return r
771 }
772 s := string(rune(utf8.RuneSelf)) + string(utf8.MaxRune)
773 r := string(utf8.MaxRune) + string(rune(utf8.RuneSelf))
774 m = Map(encode, s)
775 if m != r {
776 t.Errorf("encoding not handled correctly: expected %q got %q", r, m)
777 }
778 m = Map(encode, r)
779 if m != s {
780 t.Errorf("encoding not handled correctly: expected %q got %q", s, m)
781 }
782
783
784 trimSpaces := func(r rune) rune {
785 if unicode.IsSpace(r) {
786 return -1
787 }
788 return r
789 }
790 m = Map(trimSpaces, " abc 123 ")
791 expect = "abc123"
792 if m != expect {
793 t.Errorf("trimSpaces: expected %q got %q", expect, m)
794 }
795 }
796
797 func TestToUpper(t *testing.T) { runStringTests(t, ToUpper, "ToUpper", upperTests) }
798
799 func TestToLower(t *testing.T) { runStringTests(t, ToLower, "ToLower", lowerTests) }
800
801 var toValidUTF8Tests = []struct {
802 in string
803 repl string
804 out string
805 }{
806 {"", "\uFFFD", ""},
807 {"abc", "\uFFFD", "abc"},
808 {"\uFDDD", "\uFFFD", "\uFDDD"},
809 {"a\xffb", "\uFFFD", "a\uFFFDb"},
810 {"a\xffb\uFFFD", "X", "aXb\uFFFD"},
811 {"a☺\xffb☺\xC0\xAFc☺\xff", "", "a☺b☺c☺"},
812 {"a☺\xffb☺\xC0\xAFc☺\xff", "日本語", "a☺日本語b☺日本語c☺日本語"},
813 {"\xC0\xAF", "\uFFFD", "\uFFFD"},
814 {"\xE0\x80\xAF", "\uFFFD", "\uFFFD"},
815 {"\xed\xa0\x80", "abc", "abc"},
816 {"\xed\xbf\xbf", "\uFFFD", "\uFFFD"},
817 {"\xF0\x80\x80\xaf", "☺", "☺"},
818 {"\xF8\x80\x80\x80\xAF", "\uFFFD", "\uFFFD"},
819 {"\xFC\x80\x80\x80\x80\xAF", "\uFFFD", "\uFFFD"},
820 }
821
822 func TestToValidUTF8(t *testing.T) {
823 for _, tc := range toValidUTF8Tests {
824 got := ToValidUTF8(tc.in, tc.repl)
825 if got != tc.out {
826 t.Errorf("ToValidUTF8(%q, %q) = %q; want %q", tc.in, tc.repl, got, tc.out)
827 }
828 }
829 }
830
831 func BenchmarkToUpper(b *testing.B) {
832 for _, tc := range upperTests {
833 b.Run(tc.in, func(b *testing.B) {
834 for i := 0; i < b.N; i++ {
835 actual := ToUpper(tc.in)
836 if actual != tc.out {
837 b.Errorf("ToUpper(%q) = %q; want %q", tc.in, actual, tc.out)
838 }
839 }
840 })
841 }
842 }
843
844 func BenchmarkToLower(b *testing.B) {
845 for _, tc := range lowerTests {
846 b.Run(tc.in, func(b *testing.B) {
847 for i := 0; i < b.N; i++ {
848 actual := ToLower(tc.in)
849 if actual != tc.out {
850 b.Errorf("ToLower(%q) = %q; want %q", tc.in, actual, tc.out)
851 }
852 }
853 })
854 }
855 }
856
857 func BenchmarkMapNoChanges(b *testing.B) {
858 identity := func(r rune) rune {
859 return r
860 }
861 for i := 0; i < b.N; i++ {
862 Map(identity, "Some string that won't be modified.")
863 }
864 }
865
866 func TestSpecialCase(t *testing.T) {
867 lower := "abcçdefgğhıijklmnoöprsştuüvyz"
868 upper := "ABCÇDEFGĞHIİJKLMNOÖPRSŞTUÜVYZ"
869 u := ToUpperSpecial(unicode.TurkishCase, upper)
870 if u != upper {
871 t.Errorf("Upper(upper) is %s not %s", u, upper)
872 }
873 u = ToUpperSpecial(unicode.TurkishCase, lower)
874 if u != upper {
875 t.Errorf("Upper(lower) is %s not %s", u, upper)
876 }
877 l := ToLowerSpecial(unicode.TurkishCase, lower)
878 if l != lower {
879 t.Errorf("Lower(lower) is %s not %s", l, lower)
880 }
881 l = ToLowerSpecial(unicode.TurkishCase, upper)
882 if l != lower {
883 t.Errorf("Lower(upper) is %s not %s", l, lower)
884 }
885 }
886
887 func TestTrimSpace(t *testing.T) { runStringTests(t, TrimSpace, "TrimSpace", trimSpaceTests) }
888
889 var trimTests = []struct {
890 f string
891 in, arg, out string
892 }{
893 {"Trim", "abba", "a", "bb"},
894 {"Trim", "abba", "ab", ""},
895 {"TrimLeft", "abba", "ab", ""},
896 {"TrimRight", "abba", "ab", ""},
897 {"TrimLeft", "abba", "a", "bba"},
898 {"TrimLeft", "abba", "b", "abba"},
899 {"TrimRight", "abba", "a", "abb"},
900 {"TrimRight", "abba", "b", "abba"},
901 {"Trim", "<tag>", "<>", "tag"},
902 {"Trim", "* listitem", " *", "listitem"},
903 {"Trim", `"quote"`, `"`, "quote"},
904 {"Trim", "\u2C6F\u2C6F\u0250\u0250\u2C6F\u2C6F", "\u2C6F", "\u0250\u0250"},
905 {"Trim", "\x80test\xff", "\xff", "test"},
906 {"Trim", " Ġ ", " ", "Ġ"},
907 {"Trim", " Ġİ0", "0 ", "Ġİ"},
908
909 {"Trim", "abba", "", "abba"},
910 {"Trim", "", "123", ""},
911 {"Trim", "", "", ""},
912 {"TrimLeft", "abba", "", "abba"},
913 {"TrimLeft", "", "123", ""},
914 {"TrimLeft", "", "", ""},
915 {"TrimRight", "abba", "", "abba"},
916 {"TrimRight", "", "123", ""},
917 {"TrimRight", "", "", ""},
918 {"TrimRight", "☺\xc0", "☺", "☺\xc0"},
919 {"TrimPrefix", "aabb", "a", "abb"},
920 {"TrimPrefix", "aabb", "b", "aabb"},
921 {"TrimSuffix", "aabb", "a", "aabb"},
922 {"TrimSuffix", "aabb", "b", "aab"},
923 }
924
925 func TestTrim(t *testing.T) {
926 for _, tc := range trimTests {
927 name := tc.f
928 var f func(string, string) string
929 switch name {
930 case "Trim":
931 f = Trim
932 case "TrimLeft":
933 f = TrimLeft
934 case "TrimRight":
935 f = TrimRight
936 case "TrimPrefix":
937 f = TrimPrefix
938 case "TrimSuffix":
939 f = TrimSuffix
940 default:
941 t.Errorf("Undefined trim function %s", name)
942 }
943 actual := f(tc.in, tc.arg)
944 if actual != tc.out {
945 t.Errorf("%s(%q, %q) = %q; want %q", name, tc.in, tc.arg, actual, tc.out)
946 }
947 }
948 }
949
950 func BenchmarkTrim(b *testing.B) {
951 b.ReportAllocs()
952
953 for i := 0; i < b.N; i++ {
954 for _, tc := range trimTests {
955 name := tc.f
956 var f func(string, string) string
957 switch name {
958 case "Trim":
959 f = Trim
960 case "TrimLeft":
961 f = TrimLeft
962 case "TrimRight":
963 f = TrimRight
964 case "TrimPrefix":
965 f = TrimPrefix
966 case "TrimSuffix":
967 f = TrimSuffix
968 default:
969 b.Errorf("Undefined trim function %s", name)
970 }
971 actual := f(tc.in, tc.arg)
972 if actual != tc.out {
973 b.Errorf("%s(%q, %q) = %q; want %q", name, tc.in, tc.arg, actual, tc.out)
974 }
975 }
976 }
977 }
978
979 func BenchmarkToValidUTF8(b *testing.B) {
980 tests := []struct {
981 name string
982 input string
983 }{
984 {"Valid", "typical"},
985 {"InvalidASCII", "foo\xffbar"},
986 {"InvalidNonASCII", "日本語\xff日本語"},
987 }
988 replacement := "\uFFFD"
989 b.ResetTimer()
990 for _, test := range tests {
991 b.Run(test.name, func(b *testing.B) {
992 for i := 0; i < b.N; i++ {
993 ToValidUTF8(test.input, replacement)
994 }
995 })
996 }
997 }
998
999 type predicate struct {
1000 f func(rune) bool
1001 name string
1002 }
1003
1004 var isSpace = predicate{unicode.IsSpace, "IsSpace"}
1005 var isDigit = predicate{unicode.IsDigit, "IsDigit"}
1006 var isUpper = predicate{unicode.IsUpper, "IsUpper"}
1007 var isValidRune = predicate{
1008 func(r rune) bool {
1009 return r != utf8.RuneError
1010 },
1011 "IsValidRune",
1012 }
1013
1014 func not(p predicate) predicate {
1015 return predicate{
1016 func(r rune) bool {
1017 return !p.f(r)
1018 },
1019 "not " + p.name,
1020 }
1021 }
1022
1023 var trimFuncTests = []struct {
1024 f predicate
1025 in string
1026 trimOut string
1027 leftOut string
1028 rightOut string
1029 }{
1030 {isSpace, space + " hello " + space,
1031 "hello",
1032 "hello " + space,
1033 space + " hello"},
1034 {isDigit, "\u0e50\u0e5212hello34\u0e50\u0e51",
1035 "hello",
1036 "hello34\u0e50\u0e51",
1037 "\u0e50\u0e5212hello"},
1038 {isUpper, "\u2C6F\u2C6F\u2C6F\u2C6FABCDhelloEF\u2C6F\u2C6FGH\u2C6F\u2C6F",
1039 "hello",
1040 "helloEF\u2C6F\u2C6FGH\u2C6F\u2C6F",
1041 "\u2C6F\u2C6F\u2C6F\u2C6FABCDhello"},
1042 {not(isSpace), "hello" + space + "hello",
1043 space,
1044 space + "hello",
1045 "hello" + space},
1046 {not(isDigit), "hello\u0e50\u0e521234\u0e50\u0e51helo",
1047 "\u0e50\u0e521234\u0e50\u0e51",
1048 "\u0e50\u0e521234\u0e50\u0e51helo",
1049 "hello\u0e50\u0e521234\u0e50\u0e51"},
1050 {isValidRune, "ab\xc0a\xc0cd",
1051 "\xc0a\xc0",
1052 "\xc0a\xc0cd",
1053 "ab\xc0a\xc0"},
1054 {not(isValidRune), "\xc0a\xc0",
1055 "a",
1056 "a\xc0",
1057 "\xc0a"},
1058 {isSpace, "",
1059 "",
1060 "",
1061 ""},
1062 {isSpace, " ",
1063 "",
1064 "",
1065 ""},
1066 }
1067
1068 func TestTrimFunc(t *testing.T) {
1069 for _, tc := range trimFuncTests {
1070 trimmers := []struct {
1071 name string
1072 trim func(s string, f func(r rune) bool) string
1073 out string
1074 }{
1075 {"TrimFunc", TrimFunc, tc.trimOut},
1076 {"TrimLeftFunc", TrimLeftFunc, tc.leftOut},
1077 {"TrimRightFunc", TrimRightFunc, tc.rightOut},
1078 }
1079 for _, trimmer := range trimmers {
1080 actual := trimmer.trim(tc.in, tc.f.f)
1081 if actual != trimmer.out {
1082 t.Errorf("%s(%q, %q) = %q; want %q", trimmer.name, tc.in, tc.f.name, actual, trimmer.out)
1083 }
1084 }
1085 }
1086 }
1087
1088 var indexFuncTests = []struct {
1089 in string
1090 f predicate
1091 first, last int
1092 }{
1093 {"", isValidRune, -1, -1},
1094 {"abc", isDigit, -1, -1},
1095 {"0123", isDigit, 0, 3},
1096 {"a1b", isDigit, 1, 1},
1097 {space, isSpace, 0, len(space) - 3},
1098 {"\u0e50\u0e5212hello34\u0e50\u0e51", isDigit, 0, 18},
1099 {"\u2C6F\u2C6F\u2C6F\u2C6FABCDhelloEF\u2C6F\u2C6FGH\u2C6F\u2C6F", isUpper, 0, 34},
1100 {"12\u0e50\u0e52hello34\u0e50\u0e51", not(isDigit), 8, 12},
1101
1102
1103 {"\x801", isDigit, 1, 1},
1104 {"\x80abc", isDigit, -1, -1},
1105 {"\xc0a\xc0", isValidRune, 1, 1},
1106 {"\xc0a\xc0", not(isValidRune), 0, 2},
1107 {"\xc0☺\xc0", not(isValidRune), 0, 4},
1108 {"\xc0☺\xc0\xc0", not(isValidRune), 0, 5},
1109 {"ab\xc0a\xc0cd", not(isValidRune), 2, 4},
1110 {"a\xe0\x80cd", not(isValidRune), 1, 2},
1111 {"\x80\x80\x80\x80", not(isValidRune), 0, 3},
1112 }
1113
1114 func TestIndexFunc(t *testing.T) {
1115 for _, tc := range indexFuncTests {
1116 first := IndexFunc(tc.in, tc.f.f)
1117 if first != tc.first {
1118 t.Errorf("IndexFunc(%q, %s) = %d; want %d", tc.in, tc.f.name, first, tc.first)
1119 }
1120 last := LastIndexFunc(tc.in, tc.f.f)
1121 if last != tc.last {
1122 t.Errorf("LastIndexFunc(%q, %s) = %d; want %d", tc.in, tc.f.name, last, tc.last)
1123 }
1124 }
1125 }
1126
1127 func equal(m string, s1, s2 string, t *testing.T) bool {
1128 if s1 == s2 {
1129 return true
1130 }
1131 e1 := Split(s1, "")
1132 e2 := Split(s2, "")
1133 for i, c1 := range e1 {
1134 if i >= len(e2) {
1135 break
1136 }
1137 r1, _ := utf8.DecodeRuneInString(c1)
1138 r2, _ := utf8.DecodeRuneInString(e2[i])
1139 if r1 != r2 {
1140 t.Errorf("%s diff at %d: U+%04X U+%04X", m, i, r1, r2)
1141 }
1142 }
1143 return false
1144 }
1145
1146 func TestCaseConsistency(t *testing.T) {
1147
1148 numRunes := int(unicode.MaxRune + 1)
1149 if testing.Short() {
1150 numRunes = 1000
1151 }
1152 a := make([]rune, numRunes)
1153 for i := range a {
1154 a[i] = rune(i)
1155 }
1156 s := string(a)
1157
1158 upper := ToUpper(s)
1159 lower := ToLower(s)
1160
1161
1162 if n := utf8.RuneCountInString(upper); n != numRunes {
1163 t.Error("rune count wrong in upper:", n)
1164 }
1165 if n := utf8.RuneCountInString(lower); n != numRunes {
1166 t.Error("rune count wrong in lower:", n)
1167 }
1168 if !equal("ToUpper(upper)", ToUpper(upper), upper, t) {
1169 t.Error("ToUpper(upper) consistency fail")
1170 }
1171 if !equal("ToLower(lower)", ToLower(lower), lower, t) {
1172 t.Error("ToLower(lower) consistency fail")
1173 }
1174
1188 }
1189
1190 var longString = "a" + string(make([]byte, 1<<16)) + "z"
1191 var longSpaces = func() string {
1192 b := make([]byte, 200)
1193 for i := range b {
1194 b[i] = ' '
1195 }
1196 return string(b)
1197 }()
1198
1199 var RepeatTests = []struct {
1200 in, out string
1201 count int
1202 }{
1203 {"", "", 0},
1204 {"", "", 1},
1205 {"", "", 2},
1206 {"-", "", 0},
1207 {"-", "-", 1},
1208 {"-", "----------", 10},
1209 {"abc ", "abc abc abc ", 3},
1210 {" ", " ", 1},
1211 {"--", "----", 2},
1212 {"===", "======", 2},
1213 {"000", "000000000", 3},
1214 {"\t\t\t\t", "\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t", 4},
1215 {" ", longSpaces, len(longSpaces)},
1216
1217 {string(rune(0)), string(make([]byte, 1<<16)), 1 << 16},
1218 {longString, longString + longString, 2},
1219 }
1220
1221 func TestRepeat(t *testing.T) {
1222 for _, tt := range RepeatTests {
1223 a := Repeat(tt.in, tt.count)
1224 if !equal("Repeat(s)", a, tt.out, t) {
1225 t.Errorf("Repeat(%v, %d) = %v; want %v", tt.in, tt.count, a, tt.out)
1226 continue
1227 }
1228 }
1229 }
1230
1231 func repeat(s string, count int) (err error) {
1232 defer func() {
1233 if r := recover(); r != nil {
1234 switch v := r.(type) {
1235 case error:
1236 err = v
1237 default:
1238 err = fmt.Errorf("%s", v)
1239 }
1240 }
1241 }()
1242
1243 Repeat(s, count)
1244
1245 return
1246 }
1247
1248
1249 func TestRepeatCatchesOverflow(t *testing.T) {
1250 type testCase struct {
1251 s string
1252 count int
1253 errStr string
1254 }
1255
1256 runTestCases := func(prefix string, tests []testCase) {
1257 for i, tt := range tests {
1258 err := repeat(tt.s, tt.count)
1259 if tt.errStr == "" {
1260 if err != nil {
1261 t.Errorf("#%d panicked %v", i, err)
1262 }
1263 continue
1264 }
1265
1266 if err == nil || !Contains(err.Error(), tt.errStr) {
1267 t.Errorf("%s#%d got %q want %q", prefix, i, err, tt.errStr)
1268 }
1269 }
1270 }
1271
1272 const maxInt = int(^uint(0) >> 1)
1273
1274 runTestCases("", []testCase{
1275 0: {"--", -2147483647, "negative"},
1276 1: {"", maxInt, ""},
1277 2: {"-", 10, ""},
1278 3: {"gopher", 0, ""},
1279 4: {"-", -1, "negative"},
1280 5: {"--", -102, "negative"},
1281 6: {string(make([]byte, 255)), int((^uint(0))/255 + 1), "overflow"},
1282 })
1283
1284 const is64Bit = 1<<(^uintptr(0)>>63)/2 != 0
1285 if !is64Bit {
1286 return
1287 }
1288
1289 runTestCases("64-bit", []testCase{
1290 0: {"-", maxInt, "out of range"},
1291 })
1292 }
1293
1294 func runesEqual(a, b []rune) bool {
1295 if len(a) != len(b) {
1296 return false
1297 }
1298 for i, r := range a {
1299 if r != b[i] {
1300 return false
1301 }
1302 }
1303 return true
1304 }
1305
1306 var RunesTests = []struct {
1307 in string
1308 out []rune
1309 lossy bool
1310 }{
1311 {"", []rune{}, false},
1312 {" ", []rune{32}, false},
1313 {"ABC", []rune{65, 66, 67}, false},
1314 {"abc", []rune{97, 98, 99}, false},
1315 {"\u65e5\u672c\u8a9e", []rune{26085, 26412, 35486}, false},
1316 {"ab\x80c", []rune{97, 98, 0xFFFD, 99}, true},
1317 {"ab\xc0c", []rune{97, 98, 0xFFFD, 99}, true},
1318 }
1319
1320 func TestRunes(t *testing.T) {
1321 for _, tt := range RunesTests {
1322 a := []rune(tt.in)
1323 if !runesEqual(a, tt.out) {
1324 t.Errorf("[]rune(%q) = %v; want %v", tt.in, a, tt.out)
1325 continue
1326 }
1327 if !tt.lossy {
1328
1329 s := string(a)
1330 if s != tt.in {
1331 t.Errorf("string([]rune(%q)) = %x; want %x", tt.in, s, tt.in)
1332 }
1333 }
1334 }
1335 }
1336
1337 func TestReadByte(t *testing.T) {
1338 testStrings := []string{"", abcd, faces, commas}
1339 for _, s := range testStrings {
1340 reader := NewReader(s)
1341 if e := reader.UnreadByte(); e == nil {
1342 t.Errorf("Unreading %q at beginning: expected error", s)
1343 }
1344 var res bytes.Buffer
1345 for {
1346 b, e := reader.ReadByte()
1347 if e == io.EOF {
1348 break
1349 }
1350 if e != nil {
1351 t.Errorf("Reading %q: %s", s, e)
1352 break
1353 }
1354 res.WriteByte(b)
1355
1356 e = reader.UnreadByte()
1357 if e != nil {
1358 t.Errorf("Unreading %q: %s", s, e)
1359 break
1360 }
1361 b1, e := reader.ReadByte()
1362 if e != nil {
1363 t.Errorf("Reading %q after unreading: %s", s, e)
1364 break
1365 }
1366 if b1 != b {
1367 t.Errorf("Reading %q after unreading: want byte %q, got %q", s, b, b1)
1368 break
1369 }
1370 }
1371 if res.String() != s {
1372 t.Errorf("Reader(%q).ReadByte() produced %q", s, res.String())
1373 }
1374 }
1375 }
1376
1377 func TestReadRune(t *testing.T) {
1378 testStrings := []string{"", abcd, faces, commas}
1379 for _, s := range testStrings {
1380 reader := NewReader(s)
1381 if e := reader.UnreadRune(); e == nil {
1382 t.Errorf("Unreading %q at beginning: expected error", s)
1383 }
1384 res := ""
1385 for {
1386 r, z, e := reader.ReadRune()
1387 if e == io.EOF {
1388 break
1389 }
1390 if e != nil {
1391 t.Errorf("Reading %q: %s", s, e)
1392 break
1393 }
1394 res += string(r)
1395
1396 e = reader.UnreadRune()
1397 if e != nil {
1398 t.Errorf("Unreading %q: %s", s, e)
1399 break
1400 }
1401 r1, z1, e := reader.ReadRune()
1402 if e != nil {
1403 t.Errorf("Reading %q after unreading: %s", s, e)
1404 break
1405 }
1406 if r1 != r {
1407 t.Errorf("Reading %q after unreading: want rune %q, got %q", s, r, r1)
1408 break
1409 }
1410 if z1 != z {
1411 t.Errorf("Reading %q after unreading: want size %d, got %d", s, z, z1)
1412 break
1413 }
1414 }
1415 if res != s {
1416 t.Errorf("Reader(%q).ReadRune() produced %q", s, res)
1417 }
1418 }
1419 }
1420
1421 var UnreadRuneErrorTests = []struct {
1422 name string
1423 f func(*Reader)
1424 }{
1425 {"Read", func(r *Reader) { r.Read([]byte{0}) }},
1426 {"ReadByte", func(r *Reader) { r.ReadByte() }},
1427 {"UnreadRune", func(r *Reader) { r.UnreadRune() }},
1428 {"Seek", func(r *Reader) { r.Seek(0, io.SeekCurrent) }},
1429 {"WriteTo", func(r *Reader) { r.WriteTo(&bytes.Buffer{}) }},
1430 }
1431
1432 func TestUnreadRuneError(t *testing.T) {
1433 for _, tt := range UnreadRuneErrorTests {
1434 reader := NewReader("0123456789")
1435 if _, _, err := reader.ReadRune(); err != nil {
1436
1437 t.Fatal(err)
1438 }
1439 tt.f(reader)
1440 err := reader.UnreadRune()
1441 if err == nil {
1442 t.Errorf("Unreading after %s: expected error", tt.name)
1443 }
1444 }
1445 }
1446
1447 var ReplaceTests = []struct {
1448 in string
1449 old, new string
1450 n int
1451 out string
1452 }{
1453 {"hello", "l", "L", 0, "hello"},
1454 {"hello", "l", "L", -1, "heLLo"},
1455 {"hello", "x", "X", -1, "hello"},
1456 {"", "x", "X", -1, ""},
1457 {"radar", "r", "<r>", -1, "<r>ada<r>"},
1458 {"", "", "<>", -1, "<>"},
1459 {"banana", "a", "<>", -1, "b<>n<>n<>"},
1460 {"banana", "a", "<>", 1, "b<>nana"},
1461 {"banana", "a", "<>", 1000, "b<>n<>n<>"},
1462 {"banana", "an", "<>", -1, "b<><>a"},
1463 {"banana", "ana", "<>", -1, "b<>na"},
1464 {"banana", "", "<>", -1, "<>b<>a<>n<>a<>n<>a<>"},
1465 {"banana", "", "<>", 10, "<>b<>a<>n<>a<>n<>a<>"},
1466 {"banana", "", "<>", 6, "<>b<>a<>n<>a<>n<>a"},
1467 {"banana", "", "<>", 5, "<>b<>a<>n<>a<>na"},
1468 {"banana", "", "<>", 1, "<>banana"},
1469 {"banana", "a", "a", -1, "banana"},
1470 {"banana", "a", "a", 1, "banana"},
1471 {"☺☻☹", "", "<>", -1, "<>☺<>☻<>☹<>"},
1472 }
1473
1474 func TestReplace(t *testing.T) {
1475 for _, tt := range ReplaceTests {
1476 if s := Replace(tt.in, tt.old, tt.new, tt.n); s != tt.out {
1477 t.Errorf("Replace(%q, %q, %q, %d) = %q, want %q", tt.in, tt.old, tt.new, tt.n, s, tt.out)
1478 }
1479 if tt.n == -1 {
1480 s := ReplaceAll(tt.in, tt.old, tt.new)
1481 if s != tt.out {
1482 t.Errorf("ReplaceAll(%q, %q, %q) = %q, want %q", tt.in, tt.old, tt.new, s, tt.out)
1483 }
1484 }
1485 }
1486 }
1487
1488 var TitleTests = []struct {
1489 in, out string
1490 }{
1491 {"", ""},
1492 {"a", "A"},
1493 {" aaa aaa aaa ", " Aaa Aaa Aaa "},
1494 {" Aaa Aaa Aaa ", " Aaa Aaa Aaa "},
1495 {"123a456", "123a456"},
1496 {"double-blind", "Double-Blind"},
1497 {"ÿøû", "Ÿøû"},
1498 {"with_underscore", "With_underscore"},
1499 {"unicode \xe2\x80\xa8 line separator", "Unicode \xe2\x80\xa8 Line Separator"},
1500 }
1501
1502 func TestTitle(t *testing.T) {
1503 for _, tt := range TitleTests {
1504 if s := Title(tt.in); s != tt.out {
1505 t.Errorf("Title(%q) = %q, want %q", tt.in, s, tt.out)
1506 }
1507 }
1508 }
1509
1510 var ContainsTests = []struct {
1511 str, substr string
1512 expected bool
1513 }{
1514 {"abc", "bc", true},
1515 {"abc", "bcd", false},
1516 {"abc", "", true},
1517 {"", "a", false},
1518
1519
1520
1521 {"xxxxxx", "01", false},
1522 {"01xxxx", "01", true},
1523 {"xx01xx", "01", true},
1524 {"xxxx01", "01", true},
1525 {"01xxxxx"[1:], "01", false},
1526 {"xxxxx01"[:6], "01", false},
1527
1528 {"xxxxxxx", "012", false},
1529 {"012xxxx", "012", true},
1530 {"xx012xx", "012", true},
1531 {"xxxx012", "012", true},
1532 {"012xxxxx"[1:], "012", false},
1533 {"xxxxx012"[:7], "012", false},
1534
1535 {"xxxxxxxx", "0123", false},
1536 {"0123xxxx", "0123", true},
1537 {"xx0123xx", "0123", true},
1538 {"xxxx0123", "0123", true},
1539 {"0123xxxxx"[1:], "0123", false},
1540 {"xxxxx0123"[:8], "0123", false},
1541
1542 {"xxxxxxxxx", "01234", false},
1543 {"01234xxxx", "01234", true},
1544 {"xx01234xx", "01234", true},
1545 {"xxxx01234", "01234", true},
1546 {"01234xxxxx"[1:], "01234", false},
1547 {"xxxxx01234"[:9], "01234", false},
1548
1549 {"xxxxxxxxxxxx", "01234567", false},
1550 {"01234567xxxx", "01234567", true},
1551 {"xx01234567xx", "01234567", true},
1552 {"xxxx01234567", "01234567", true},
1553 {"01234567xxxxx"[1:], "01234567", false},
1554 {"xxxxx01234567"[:12], "01234567", false},
1555
1556 {"xxxxxxxxxxxxx", "012345678", false},
1557 {"012345678xxxx", "012345678", true},
1558 {"xx012345678xx", "012345678", true},
1559 {"xxxx012345678", "012345678", true},
1560 {"012345678xxxxx"[1:], "012345678", false},
1561 {"xxxxx012345678"[:13], "012345678", false},
1562
1563 {"xxxxxxxxxxxxxxxxxxxx", "0123456789ABCDEF", false},
1564 {"0123456789ABCDEFxxxx", "0123456789ABCDEF", true},
1565 {"xx0123456789ABCDEFxx", "0123456789ABCDEF", true},
1566 {"xxxx0123456789ABCDEF", "0123456789ABCDEF", true},
1567 {"0123456789ABCDEFxxxxx"[1:], "0123456789ABCDEF", false},
1568 {"xxxxx0123456789ABCDEF"[:20], "0123456789ABCDEF", false},
1569
1570 {"xxxxxxxxxxxxxxxxxxxxx", "0123456789ABCDEFG", false},
1571 {"0123456789ABCDEFGxxxx", "0123456789ABCDEFG", true},
1572 {"xx0123456789ABCDEFGxx", "0123456789ABCDEFG", true},
1573 {"xxxx0123456789ABCDEFG", "0123456789ABCDEFG", true},
1574 {"0123456789ABCDEFGxxxxx"[1:], "0123456789ABCDEFG", false},
1575 {"xxxxx0123456789ABCDEFG"[:21], "0123456789ABCDEFG", false},
1576
1577
1578 {"xx01x", "012", false},
1579 {"xx0123x", "01234", false},
1580 {"xx01234567x", "012345678", false},
1581 {"xx0123456789ABCDEFx", "0123456789ABCDEFG", false},
1582 }
1583
1584 func TestContains(t *testing.T) {
1585 for _, ct := range ContainsTests {
1586 if Contains(ct.str, ct.substr) != ct.expected {
1587 t.Errorf("Contains(%s, %s) = %v, want %v",
1588 ct.str, ct.substr, !ct.expected, ct.expected)
1589 }
1590 }
1591 }
1592
1593 var ContainsAnyTests = []struct {
1594 str, substr string
1595 expected bool
1596 }{
1597 {"", "", false},
1598 {"", "a", false},
1599 {"", "abc", false},
1600 {"a", "", false},
1601 {"a", "a", true},
1602 {"aaa", "a", true},
1603 {"abc", "xyz", false},
1604 {"abc", "xcz", true},
1605 {"a☺b☻c☹d", "uvw☻xyz", true},
1606 {"aRegExp*", ".(|)*+?^$[]", true},
1607 {dots + dots + dots, " ", false},
1608 }
1609
1610 func TestContainsAny(t *testing.T) {
1611 for _, ct := range ContainsAnyTests {
1612 if ContainsAny(ct.str, ct.substr) != ct.expected {
1613 t.Errorf("ContainsAny(%s, %s) = %v, want %v",
1614 ct.str, ct.substr, !ct.expected, ct.expected)
1615 }
1616 }
1617 }
1618
1619 var ContainsRuneTests = []struct {
1620 str string
1621 r rune
1622 expected bool
1623 }{
1624 {"", 'a', false},
1625 {"a", 'a', true},
1626 {"aaa", 'a', true},
1627 {"abc", 'y', false},
1628 {"abc", 'c', true},
1629 {"a☺b☻c☹d", 'x', false},
1630 {"a☺b☻c☹d", '☻', true},
1631 {"aRegExp*", '*', true},
1632 }
1633
1634 func TestContainsRune(t *testing.T) {
1635 for _, ct := range ContainsRuneTests {
1636 if ContainsRune(ct.str, ct.r) != ct.expected {
1637 t.Errorf("ContainsRune(%q, %q) = %v, want %v",
1638 ct.str, ct.r, !ct.expected, ct.expected)
1639 }
1640 }
1641 }
1642
1643 func TestContainsFunc(t *testing.T) {
1644 for _, ct := range ContainsRuneTests {
1645 if ContainsFunc(ct.str, func(r rune) bool {
1646 return ct.r == r
1647 }) != ct.expected {
1648 t.Errorf("ContainsFunc(%q, func(%q)) = %v, want %v",
1649 ct.str, ct.r, !ct.expected, ct.expected)
1650 }
1651 }
1652 }
1653
1654 var EqualFoldTests = []struct {
1655 s, t string
1656 out bool
1657 }{
1658 {"abc", "abc", true},
1659 {"ABcd", "ABcd", true},
1660 {"123abc", "123ABC", true},
1661 {"αβδ", "ΑΒΔ", true},
1662 {"abc", "xyz", false},
1663 {"abc", "XYZ", false},
1664 {"abcdefghijk", "abcdefghijX", false},
1665 {"abcdefghijk", "abcdefghij\u212A", true},
1666 {"abcdefghijK", "abcdefghij\u212A", true},
1667 {"abcdefghijkz", "abcdefghij\u212Ay", false},
1668 {"abcdefghijKz", "abcdefghij\u212Ay", false},
1669 {"1", "2", false},
1670 {"utf-8", "US-ASCII", false},
1671 }
1672
1673 func TestEqualFold(t *testing.T) {
1674 for _, tt := range EqualFoldTests {
1675 if out := EqualFold(tt.s, tt.t); out != tt.out {
1676 t.Errorf("EqualFold(%#q, %#q) = %v, want %v", tt.s, tt.t, out, tt.out)
1677 }
1678 if out := EqualFold(tt.t, tt.s); out != tt.out {
1679 t.Errorf("EqualFold(%#q, %#q) = %v, want %v", tt.t, tt.s, out, tt.out)
1680 }
1681 }
1682 }
1683
1684 func BenchmarkEqualFold(b *testing.B) {
1685 b.Run("Tests", func(b *testing.B) {
1686 for i := 0; i < b.N; i++ {
1687 for _, tt := range EqualFoldTests {
1688 if out := EqualFold(tt.s, tt.t); out != tt.out {
1689 b.Fatal("wrong result")
1690 }
1691 }
1692 }
1693 })
1694
1695 const s1 = "abcdefghijKz"
1696 const s2 = "abcDefGhijKz"
1697
1698 b.Run("ASCII", func(b *testing.B) {
1699 for i := 0; i < b.N; i++ {
1700 EqualFold(s1, s2)
1701 }
1702 })
1703
1704 b.Run("UnicodePrefix", func(b *testing.B) {
1705 for i := 0; i < b.N; i++ {
1706 EqualFold("αβδ"+s1, "ΑΒΔ"+s2)
1707 }
1708 })
1709
1710 b.Run("UnicodeSuffix", func(b *testing.B) {
1711 for i := 0; i < b.N; i++ {
1712 EqualFold(s1+"αβδ", s2+"ΑΒΔ")
1713 }
1714 })
1715 }
1716
1717 var CountTests = []struct {
1718 s, sep string
1719 num int
1720 }{
1721 {"", "", 1},
1722 {"", "notempty", 0},
1723 {"notempty", "", 9},
1724 {"smaller", "not smaller", 0},
1725 {"12345678987654321", "6", 2},
1726 {"611161116", "6", 3},
1727 {"notequal", "NotEqual", 0},
1728 {"equal", "equal", 1},
1729 {"abc1231231123q", "123", 3},
1730 {"11111", "11", 2},
1731 }
1732
1733 func TestCount(t *testing.T) {
1734 for _, tt := range CountTests {
1735 if num := Count(tt.s, tt.sep); num != tt.num {
1736 t.Errorf("Count(%q, %q) = %d, want %d", tt.s, tt.sep, num, tt.num)
1737 }
1738 }
1739 }
1740
1741 var cutTests = []struct {
1742 s, sep string
1743 before, after string
1744 found bool
1745 }{
1746 {"abc", "b", "a", "c", true},
1747 {"abc", "a", "", "bc", true},
1748 {"abc", "c", "ab", "", true},
1749 {"abc", "abc", "", "", true},
1750 {"abc", "", "", "abc", true},
1751 {"abc", "d", "abc", "", false},
1752 {"", "d", "", "", false},
1753 {"", "", "", "", true},
1754 }
1755
1756 func TestCut(t *testing.T) {
1757 for _, tt := range cutTests {
1758 if before, after, found := Cut(tt.s, tt.sep); before != tt.before || after != tt.after || found != tt.found {
1759 t.Errorf("Cut(%q, %q) = %q, %q, %v, want %q, %q, %v", tt.s, tt.sep, before, after, found, tt.before, tt.after, tt.found)
1760 }
1761 }
1762 }
1763
1764 var cutPrefixTests = []struct {
1765 s, sep string
1766 after string
1767 found bool
1768 }{
1769 {"abc", "a", "bc", true},
1770 {"abc", "abc", "", true},
1771 {"abc", "", "abc", true},
1772 {"abc", "d", "abc", false},
1773 {"", "d", "", false},
1774 {"", "", "", true},
1775 }
1776
1777 func TestCutPrefix(t *testing.T) {
1778 for _, tt := range cutPrefixTests {
1779 if after, found := CutPrefix(tt.s, tt.sep); after != tt.after || found != tt.found {
1780 t.Errorf("CutPrefix(%q, %q) = %q, %v, want %q, %v", tt.s, tt.sep, after, found, tt.after, tt.found)
1781 }
1782 }
1783 }
1784
1785 var cutSuffixTests = []struct {
1786 s, sep string
1787 before string
1788 found bool
1789 }{
1790 {"abc", "bc", "a", true},
1791 {"abc", "abc", "", true},
1792 {"abc", "", "abc", true},
1793 {"abc", "d", "abc", false},
1794 {"", "d", "", false},
1795 {"", "", "", true},
1796 }
1797
1798 func TestCutSuffix(t *testing.T) {
1799 for _, tt := range cutSuffixTests {
1800 if before, found := CutSuffix(tt.s, tt.sep); before != tt.before || found != tt.found {
1801 t.Errorf("CutSuffix(%q, %q) = %q, %v, want %q, %v", tt.s, tt.sep, before, found, tt.before, tt.found)
1802 }
1803 }
1804 }
1805
1806 func makeBenchInputHard() string {
1807 tokens := [...]string{
1808 "<a>", "<p>", "<b>", "<strong>",
1809 "</a>", "</p>", "</b>", "</strong>",
1810 "hello", "world",
1811 }
1812 x := make([]byte, 0, 1<<20)
1813 for {
1814 i := rand.Intn(len(tokens))
1815 if len(x)+len(tokens[i]) >= 1<<20 {
1816 break
1817 }
1818 x = append(x, tokens[i]...)
1819 }
1820 return string(x)
1821 }
1822
1823 var benchInputHard = makeBenchInputHard()
1824
1825 func benchmarkIndexHard(b *testing.B, sep string) {
1826 for i := 0; i < b.N; i++ {
1827 Index(benchInputHard, sep)
1828 }
1829 }
1830
1831 func benchmarkLastIndexHard(b *testing.B, sep string) {
1832 for i := 0; i < b.N; i++ {
1833 LastIndex(benchInputHard, sep)
1834 }
1835 }
1836
1837 func benchmarkCountHard(b *testing.B, sep string) {
1838 for i := 0; i < b.N; i++ {
1839 Count(benchInputHard, sep)
1840 }
1841 }
1842
1843 func BenchmarkIndexHard1(b *testing.B) { benchmarkIndexHard(b, "<>") }
1844 func BenchmarkIndexHard2(b *testing.B) { benchmarkIndexHard(b, "</pre>") }
1845 func BenchmarkIndexHard3(b *testing.B) { benchmarkIndexHard(b, "<b>hello world</b>") }
1846 func BenchmarkIndexHard4(b *testing.B) {
1847 benchmarkIndexHard(b, "<pre><b>hello</b><strong>world</strong></pre>")
1848 }
1849
1850 func BenchmarkLastIndexHard1(b *testing.B) { benchmarkLastIndexHard(b, "<>") }
1851 func BenchmarkLastIndexHard2(b *testing.B) { benchmarkLastIndexHard(b, "</pre>") }
1852 func BenchmarkLastIndexHard3(b *testing.B) { benchmarkLastIndexHard(b, "<b>hello world</b>") }
1853
1854 func BenchmarkCountHard1(b *testing.B) { benchmarkCountHard(b, "<>") }
1855 func BenchmarkCountHard2(b *testing.B) { benchmarkCountHard(b, "</pre>") }
1856 func BenchmarkCountHard3(b *testing.B) { benchmarkCountHard(b, "<b>hello world</b>") }
1857
1858 var benchInputTorture = Repeat("ABC", 1<<10) + "123" + Repeat("ABC", 1<<10)
1859 var benchNeedleTorture = Repeat("ABC", 1<<10+1)
1860
1861 func BenchmarkIndexTorture(b *testing.B) {
1862 for i := 0; i < b.N; i++ {
1863 Index(benchInputTorture, benchNeedleTorture)
1864 }
1865 }
1866
1867 func BenchmarkCountTorture(b *testing.B) {
1868 for i := 0; i < b.N; i++ {
1869 Count(benchInputTorture, benchNeedleTorture)
1870 }
1871 }
1872
1873 func BenchmarkCountTortureOverlapping(b *testing.B) {
1874 A := Repeat("ABC", 1<<20)
1875 B := Repeat("ABC", 1<<10)
1876 for i := 0; i < b.N; i++ {
1877 Count(A, B)
1878 }
1879 }
1880
1881 func BenchmarkCountByte(b *testing.B) {
1882 indexSizes := []int{10, 32, 4 << 10, 4 << 20, 64 << 20}
1883 benchStr := Repeat(benchmarkString,
1884 (indexSizes[len(indexSizes)-1]+len(benchmarkString)-1)/len(benchmarkString))
1885 benchFunc := func(b *testing.B, benchStr string) {
1886 b.SetBytes(int64(len(benchStr)))
1887 for i := 0; i < b.N; i++ {
1888 Count(benchStr, "=")
1889 }
1890 }
1891 for _, size := range indexSizes {
1892 b.Run(fmt.Sprintf("%d", size), func(b *testing.B) {
1893 benchFunc(b, benchStr[:size])
1894 })
1895 }
1896
1897 }
1898
1899 var makeFieldsInput = func() string {
1900 x := make([]byte, 1<<20)
1901
1902 for i := range x {
1903 switch rand.Intn(10) {
1904 case 0:
1905 x[i] = ' '
1906 case 1:
1907 if i > 0 && x[i-1] == 'x' {
1908 copy(x[i-1:], "χ")
1909 break
1910 }
1911 fallthrough
1912 default:
1913 x[i] = 'x'
1914 }
1915 }
1916 return string(x)
1917 }
1918
1919 var makeFieldsInputASCII = func() string {
1920 x := make([]byte, 1<<20)
1921
1922 for i := range x {
1923 if rand.Intn(10) == 0 {
1924 x[i] = ' '
1925 } else {
1926 x[i] = 'x'
1927 }
1928 }
1929 return string(x)
1930 }
1931
1932 var stringdata = []struct{ name, data string }{
1933 {"ASCII", makeFieldsInputASCII()},
1934 {"Mixed", makeFieldsInput()},
1935 }
1936
1937 func BenchmarkFields(b *testing.B) {
1938 for _, sd := range stringdata {
1939 b.Run(sd.name, func(b *testing.B) {
1940 for j := 1 << 4; j <= 1<<20; j <<= 4 {
1941 b.Run(fmt.Sprintf("%d", j), func(b *testing.B) {
1942 b.ReportAllocs()
1943 b.SetBytes(int64(j))
1944 data := sd.data[:j]
1945 for i := 0; i < b.N; i++ {
1946 Fields(data)
1947 }
1948 })
1949 }
1950 })
1951 }
1952 }
1953
1954 func BenchmarkFieldsFunc(b *testing.B) {
1955 for _, sd := range stringdata {
1956 b.Run(sd.name, func(b *testing.B) {
1957 for j := 1 << 4; j <= 1<<20; j <<= 4 {
1958 b.Run(fmt.Sprintf("%d", j), func(b *testing.B) {
1959 b.ReportAllocs()
1960 b.SetBytes(int64(j))
1961 data := sd.data[:j]
1962 for i := 0; i < b.N; i++ {
1963 FieldsFunc(data, unicode.IsSpace)
1964 }
1965 })
1966 }
1967 })
1968 }
1969 }
1970
1971 func BenchmarkSplitEmptySeparator(b *testing.B) {
1972 for i := 0; i < b.N; i++ {
1973 Split(benchInputHard, "")
1974 }
1975 }
1976
1977 func BenchmarkSplitSingleByteSeparator(b *testing.B) {
1978 for i := 0; i < b.N; i++ {
1979 Split(benchInputHard, "/")
1980 }
1981 }
1982
1983 func BenchmarkSplitMultiByteSeparator(b *testing.B) {
1984 for i := 0; i < b.N; i++ {
1985 Split(benchInputHard, "hello")
1986 }
1987 }
1988
1989 func BenchmarkSplitNSingleByteSeparator(b *testing.B) {
1990 for i := 0; i < b.N; i++ {
1991 SplitN(benchInputHard, "/", 10)
1992 }
1993 }
1994
1995 func BenchmarkSplitNMultiByteSeparator(b *testing.B) {
1996 for i := 0; i < b.N; i++ {
1997 SplitN(benchInputHard, "hello", 10)
1998 }
1999 }
2000
2001 func BenchmarkRepeat(b *testing.B) {
2002 s := "0123456789"
2003 for _, n := range []int{5, 10} {
2004 for _, c := range []int{0, 1, 2, 6} {
2005 b.Run(fmt.Sprintf("%dx%d", n, c), func(b *testing.B) {
2006 for i := 0; i < b.N; i++ {
2007 Repeat(s[:n], c)
2008 }
2009 })
2010 }
2011 }
2012 }
2013
2014 func BenchmarkRepeatLarge(b *testing.B) {
2015 s := Repeat("@", 8*1024)
2016 for j := 8; j <= 30; j++ {
2017 for _, k := range []int{1, 16, 4097} {
2018 s := s[:k]
2019 n := (1 << j) / k
2020 if n == 0 {
2021 continue
2022 }
2023 b.Run(fmt.Sprintf("%d/%d", 1<<j, k), func(b *testing.B) {
2024 for i := 0; i < b.N; i++ {
2025 Repeat(s, n)
2026 }
2027 b.SetBytes(int64(n * len(s)))
2028 })
2029 }
2030 }
2031 }
2032
2033 func BenchmarkRepeatSpaces(b *testing.B) {
2034 b.ReportAllocs()
2035 for i := 0; i < b.N; i++ {
2036 Repeat(" ", 2)
2037 }
2038 }
2039
2040 func BenchmarkIndexAnyASCII(b *testing.B) {
2041 x := Repeat("#", 2048)
2042 cs := "0123456789abcdefghijklmnopqrstuvwxyz0123456789abcdefghijklmnopqrstuvwxyz"
2043 for k := 1; k <= 2048; k <<= 4 {
2044 for j := 1; j <= 64; j <<= 1 {
2045 b.Run(fmt.Sprintf("%d:%d", k, j), func(b *testing.B) {
2046 for i := 0; i < b.N; i++ {
2047 IndexAny(x[:k], cs[:j])
2048 }
2049 })
2050 }
2051 }
2052 }
2053
2054 func BenchmarkIndexAnyUTF8(b *testing.B) {
2055 x := Repeat("#", 2048)
2056 cs := "你好世界, hello world. 你好世界, hello world. 你好世界, hello world."
2057 for k := 1; k <= 2048; k <<= 4 {
2058 for j := 1; j <= 64; j <<= 1 {
2059 b.Run(fmt.Sprintf("%d:%d", k, j), func(b *testing.B) {
2060 for i := 0; i < b.N; i++ {
2061 IndexAny(x[:k], cs[:j])
2062 }
2063 })
2064 }
2065 }
2066 }
2067
2068 func BenchmarkLastIndexAnyASCII(b *testing.B) {
2069 x := Repeat("#", 2048)
2070 cs := "0123456789abcdefghijklmnopqrstuvwxyz0123456789abcdefghijklmnopqrstuvwxyz"
2071 for k := 1; k <= 2048; k <<= 4 {
2072 for j := 1; j <= 64; j <<= 1 {
2073 b.Run(fmt.Sprintf("%d:%d", k, j), func(b *testing.B) {
2074 for i := 0; i < b.N; i++ {
2075 LastIndexAny(x[:k], cs[:j])
2076 }
2077 })
2078 }
2079 }
2080 }
2081
2082 func BenchmarkLastIndexAnyUTF8(b *testing.B) {
2083 x := Repeat("#", 2048)
2084 cs := "你好世界, hello world. 你好世界, hello world. 你好世界, hello world."
2085 for k := 1; k <= 2048; k <<= 4 {
2086 for j := 1; j <= 64; j <<= 1 {
2087 b.Run(fmt.Sprintf("%d:%d", k, j), func(b *testing.B) {
2088 for i := 0; i < b.N; i++ {
2089 LastIndexAny(x[:k], cs[:j])
2090 }
2091 })
2092 }
2093 }
2094 }
2095
2096 func BenchmarkTrimASCII(b *testing.B) {
2097 cs := "0123456789abcdef"
2098 for k := 1; k <= 4096; k <<= 4 {
2099 for j := 1; j <= 16; j <<= 1 {
2100 b.Run(fmt.Sprintf("%d:%d", k, j), func(b *testing.B) {
2101 x := Repeat(cs[:j], k)
2102 for i := 0; i < b.N; i++ {
2103 Trim(x[:k], cs[:j])
2104 }
2105 })
2106 }
2107 }
2108 }
2109
2110 func BenchmarkTrimByte(b *testing.B) {
2111 x := " the quick brown fox "
2112 for i := 0; i < b.N; i++ {
2113 Trim(x, " ")
2114 }
2115 }
2116
2117 func BenchmarkIndexPeriodic(b *testing.B) {
2118 key := "aa"
2119 for _, skip := range [...]int{2, 4, 8, 16, 32, 64} {
2120 b.Run(fmt.Sprintf("IndexPeriodic%d", skip), func(b *testing.B) {
2121 s := Repeat("a"+Repeat(" ", skip-1), 1<<16/skip)
2122 for i := 0; i < b.N; i++ {
2123 Index(s, key)
2124 }
2125 })
2126 }
2127 }
2128
2129 func BenchmarkJoin(b *testing.B) {
2130 vals := []string{"red", "yellow", "pink", "green", "purple", "orange", "blue"}
2131 for l := 0; l <= len(vals); l++ {
2132 b.Run(strconv.Itoa(l), func(b *testing.B) {
2133 b.ReportAllocs()
2134 vals := vals[:l]
2135 for i := 0; i < b.N; i++ {
2136 Join(vals, " and ")
2137 }
2138 })
2139 }
2140 }
2141
2142 func BenchmarkTrimSpace(b *testing.B) {
2143 tests := []struct{ name, input string }{
2144 {"NoTrim", "typical"},
2145 {"ASCII", " foo bar "},
2146 {"SomeNonASCII", " \u2000\t\r\n x\t\t\r\r\ny\n \u3000 "},
2147 {"JustNonASCII", "\u2000\u2000\u2000☺☺☺☺\u3000\u3000\u3000"},
2148 }
2149 for _, test := range tests {
2150 b.Run(test.name, func(b *testing.B) {
2151 for i := 0; i < b.N; i++ {
2152 TrimSpace(test.input)
2153 }
2154 })
2155 }
2156 }
2157
2158 var stringSink string
2159
2160 func BenchmarkReplaceAll(b *testing.B) {
2161 b.ReportAllocs()
2162 for i := 0; i < b.N; i++ {
2163 stringSink = ReplaceAll("banana", "a", "<>")
2164 }
2165 }
2166
View as plain text