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