github.com/mh-cbon/go@v0.0.0-20160603070303-9e112a3fe4c0/src/strings/strings_test.go (about) 1 // Copyright 2009 The Go Authors. All rights reserved. 2 // Use of this source code is governed by a BSD-style 3 // license that can be found in the LICENSE file. 4 5 package strings_test 6 7 import ( 8 "bytes" 9 "io" 10 "math/rand" 11 "reflect" 12 . "strings" 13 "testing" 14 "unicode" 15 "unicode/utf8" 16 "unsafe" 17 ) 18 19 func eq(a, b []string) bool { 20 if len(a) != len(b) { 21 return false 22 } 23 for i := 0; i < len(a); i++ { 24 if a[i] != b[i] { 25 return false 26 } 27 } 28 return true 29 } 30 31 var abcd = "abcd" 32 var faces = "☺☻☹" 33 var commas = "1,2,3,4" 34 var dots = "1....2....3....4" 35 36 type IndexTest struct { 37 s string 38 sep string 39 out int 40 } 41 42 var indexTests = []IndexTest{ 43 {"", "", 0}, 44 {"", "a", -1}, 45 {"", "foo", -1}, 46 {"fo", "foo", -1}, 47 {"foo", "foo", 0}, 48 {"oofofoofooo", "f", 2}, 49 {"oofofoofooo", "foo", 4}, 50 {"barfoobarfoo", "foo", 3}, 51 {"foo", "", 0}, 52 {"foo", "o", 1}, 53 {"abcABCabc", "A", 3}, 54 // cases with one byte strings - test special case in Index() 55 {"", "a", -1}, 56 {"x", "a", -1}, 57 {"x", "x", 0}, 58 {"abc", "a", 0}, 59 {"abc", "b", 1}, 60 {"abc", "c", 2}, 61 {"abc", "x", -1}, 62 // test special cases in Index() for short strings 63 {"", "ab", -1}, 64 {"bc", "ab", -1}, 65 {"ab", "ab", 0}, 66 {"xab", "ab", 1}, 67 {"xab"[:2], "ab", -1}, 68 {"", "abc", -1}, 69 {"xbc", "abc", -1}, 70 {"abc", "abc", 0}, 71 {"xabc", "abc", 1}, 72 {"xabc"[:3], "abc", -1}, 73 {"xabxc", "abc", -1}, 74 {"", "abcd", -1}, 75 {"xbcd", "abcd", -1}, 76 {"abcd", "abcd", 0}, 77 {"xabcd", "abcd", 1}, 78 {"xyabcd"[:5], "abcd", -1}, 79 {"xbcqq", "abcqq", -1}, 80 {"abcqq", "abcqq", 0}, 81 {"xabcqq", "abcqq", 1}, 82 {"xyabcqq"[:6], "abcqq", -1}, 83 {"xabxcqq", "abcqq", -1}, 84 {"xabcqxq", "abcqq", -1}, 85 {"", "01234567", -1}, 86 {"32145678", "01234567", -1}, 87 {"01234567", "01234567", 0}, 88 {"x01234567", "01234567", 1}, 89 {"xx01234567"[:9], "01234567", -1}, 90 {"", "0123456789", -1}, 91 {"3214567844", "0123456789", -1}, 92 {"0123456789", "0123456789", 0}, 93 {"x0123456789", "0123456789", 1}, 94 {"xyz0123456789"[:12], "0123456789", -1}, 95 {"x01234567x89", "0123456789", -1}, 96 {"", "0123456789012345", -1}, 97 {"3214567889012345", "0123456789012345", -1}, 98 {"0123456789012345", "0123456789012345", 0}, 99 {"x0123456789012345", "0123456789012345", 1}, 100 {"", "01234567890123456789", -1}, 101 {"32145678890123456789", "01234567890123456789", -1}, 102 {"01234567890123456789", "01234567890123456789", 0}, 103 {"x01234567890123456789", "01234567890123456789", 1}, 104 {"xyz01234567890123456789"[:22], "01234567890123456789", -1}, 105 {"", "0123456789012345678901234567890", -1}, 106 {"321456788901234567890123456789012345678911", "0123456789012345678901234567890", -1}, 107 {"0123456789012345678901234567890", "0123456789012345678901234567890", 0}, 108 {"x0123456789012345678901234567890", "0123456789012345678901234567890", 1}, 109 {"xyz0123456789012345678901234567890"[:33], "0123456789012345678901234567890", -1}, 110 {"", "01234567890123456789012345678901", -1}, 111 {"32145678890123456789012345678901234567890211", "01234567890123456789012345678901", -1}, 112 {"01234567890123456789012345678901", "01234567890123456789012345678901", 0}, 113 {"x01234567890123456789012345678901", "01234567890123456789012345678901", 1}, 114 {"xyz01234567890123456789012345678901"[:34], "01234567890123456789012345678901", -1}, 115 } 116 117 var lastIndexTests = []IndexTest{ 118 {"", "", 0}, 119 {"", "a", -1}, 120 {"", "foo", -1}, 121 {"fo", "foo", -1}, 122 {"foo", "foo", 0}, 123 {"foo", "f", 0}, 124 {"oofofoofooo", "f", 7}, 125 {"oofofoofooo", "foo", 7}, 126 {"barfoobarfoo", "foo", 9}, 127 {"foo", "", 3}, 128 {"foo", "o", 2}, 129 {"abcABCabc", "A", 3}, 130 {"abcABCabc", "a", 6}, 131 } 132 133 var indexAnyTests = []IndexTest{ 134 {"", "", -1}, 135 {"", "a", -1}, 136 {"", "abc", -1}, 137 {"a", "", -1}, 138 {"a", "a", 0}, 139 {"aaa", "a", 0}, 140 {"abc", "xyz", -1}, 141 {"abc", "xcz", 2}, 142 {"a☺b☻c☹d", "uvw☻xyz", 2 + len("☺")}, 143 {"aRegExp*", ".(|)*+?^$[]", 7}, 144 {dots + dots + dots, " ", -1}, 145 } 146 var lastIndexAnyTests = []IndexTest{ 147 {"", "", -1}, 148 {"", "a", -1}, 149 {"", "abc", -1}, 150 {"a", "", -1}, 151 {"a", "a", 0}, 152 {"aaa", "a", 2}, 153 {"abc", "xyz", -1}, 154 {"abc", "ab", 1}, 155 {"a☺b☻c☹d", "uvw☻xyz", 2 + len("☺")}, 156 {"a.RegExp*", ".(|)*+?^$[]", 8}, 157 {dots + dots + dots, " ", -1}, 158 } 159 160 // Execute f on each test case. funcName should be the name of f; it's used 161 // in failure reports. 162 func runIndexTests(t *testing.T, f func(s, sep string) int, funcName string, testCases []IndexTest) { 163 for _, test := range testCases { 164 actual := f(test.s, test.sep) 165 if actual != test.out { 166 t.Errorf("%s(%q,%q) = %v; want %v", funcName, test.s, test.sep, actual, test.out) 167 } 168 } 169 } 170 171 func TestIndex(t *testing.T) { runIndexTests(t, Index, "Index", indexTests) } 172 func TestLastIndex(t *testing.T) { runIndexTests(t, LastIndex, "LastIndex", lastIndexTests) } 173 func TestIndexAny(t *testing.T) { runIndexTests(t, IndexAny, "IndexAny", indexAnyTests) } 174 func TestLastIndexAny(t *testing.T) { runIndexTests(t, LastIndexAny, "LastIndexAny", lastIndexAnyTests) } 175 176 func TestLastIndexByte(t *testing.T) { 177 testCases := []IndexTest{ 178 {"", "q", -1}, 179 {"abcdef", "q", -1}, 180 {"abcdefabcdef", "a", len("abcdef")}, // something in the middle 181 {"abcdefabcdef", "f", len("abcdefabcde")}, // last byte 182 {"zabcdefabcdef", "z", 0}, // first byte 183 {"a☺b☻c☹d", "b", len("a☺")}, // non-ascii 184 } 185 for _, test := range testCases { 186 actual := LastIndexByte(test.s, test.sep[0]) 187 if actual != test.out { 188 t.Errorf("LastIndexByte(%q,%c) = %v; want %v", test.s, test.sep[0], actual, test.out) 189 } 190 } 191 } 192 193 func simpleIndex(s, sep string) int { 194 n := len(sep) 195 for i := n; i <= len(s); i++ { 196 if s[i-n:i] == sep { 197 return i - n 198 } 199 } 200 return -1 201 } 202 203 func TestIndexRandom(t *testing.T) { 204 const chars = "abcdefghijklmnopqrstuvwxyz0123456789" 205 for times := 0; times < 10; times++ { 206 for strLen := 5 + rand.Intn(5); strLen < 140; strLen += 10 { // Arbitrary 207 s1 := make([]byte, strLen) 208 for i := range s1 { 209 s1[i] = chars[rand.Intn(len(chars))] 210 } 211 s := string(s1) 212 for i := 0; i < 50; i++ { 213 begin := rand.Intn(len(s) + 1) 214 end := begin + rand.Intn(len(s)+1-begin) 215 sep := s[begin:end] 216 if i%4 == 0 { 217 pos := rand.Intn(len(sep) + 1) 218 sep = sep[:pos] + "A" + sep[pos:] 219 } 220 want := simpleIndex(s, sep) 221 res := Index(s, sep) 222 if res != want { 223 t.Errorf("Index(%s,%s) = %d; want %d", s, sep, res, want) 224 } 225 } 226 } 227 } 228 } 229 230 var indexRuneTests = []struct { 231 s string 232 rune rune 233 out int 234 }{ 235 {"a A x", 'A', 2}, 236 {"some_text=some_value", '=', 9}, 237 {"☺a", 'a', 3}, 238 {"a☻☺b", '☺', 4}, 239 } 240 241 func TestIndexRune(t *testing.T) { 242 for _, test := range indexRuneTests { 243 if actual := IndexRune(test.s, test.rune); actual != test.out { 244 t.Errorf("IndexRune(%q,%d)= %v; want %v", test.s, test.rune, actual, test.out) 245 } 246 } 247 } 248 249 const benchmarkString = "some_text=some☺value" 250 251 func BenchmarkIndexRune(b *testing.B) { 252 if got := IndexRune(benchmarkString, '☺'); got != 14 { 253 b.Fatalf("wrong index: expected 14, got=%d", got) 254 } 255 for i := 0; i < b.N; i++ { 256 IndexRune(benchmarkString, '☺') 257 } 258 } 259 260 func BenchmarkIndexRuneFastPath(b *testing.B) { 261 if got := IndexRune(benchmarkString, 'v'); got != 17 { 262 b.Fatalf("wrong index: expected 17, got=%d", got) 263 } 264 for i := 0; i < b.N; i++ { 265 IndexRune(benchmarkString, 'v') 266 } 267 } 268 269 func BenchmarkIndex(b *testing.B) { 270 if got := Index(benchmarkString, "v"); got != 17 { 271 b.Fatalf("wrong index: expected 17, got=%d", got) 272 } 273 for i := 0; i < b.N; i++ { 274 Index(benchmarkString, "v") 275 } 276 } 277 278 func BenchmarkLastIndex(b *testing.B) { 279 if got := Index(benchmarkString, "v"); got != 17 { 280 b.Fatalf("wrong index: expected 17, got=%d", got) 281 } 282 for i := 0; i < b.N; i++ { 283 LastIndex(benchmarkString, "v") 284 } 285 } 286 287 func BenchmarkIndexByte(b *testing.B) { 288 if got := IndexByte(benchmarkString, 'v'); got != 17 { 289 b.Fatalf("wrong index: expected 17, got=%d", got) 290 } 291 for i := 0; i < b.N; i++ { 292 IndexByte(benchmarkString, 'v') 293 } 294 } 295 296 type SplitTest struct { 297 s string 298 sep string 299 n int 300 a []string 301 } 302 303 var splittests = []SplitTest{ 304 {"", "", -1, []string{}}, 305 {abcd, "", 2, []string{"a", "bcd"}}, 306 {abcd, "", 4, []string{"a", "b", "c", "d"}}, 307 {abcd, "", -1, []string{"a", "b", "c", "d"}}, 308 {faces, "", -1, []string{"☺", "☻", "☹"}}, 309 {faces, "", 3, []string{"☺", "☻", "☹"}}, 310 {faces, "", 17, []string{"☺", "☻", "☹"}}, 311 {"☺�☹", "", -1, []string{"☺", "�", "☹"}}, 312 {abcd, "a", 0, nil}, 313 {abcd, "a", -1, []string{"", "bcd"}}, 314 {abcd, "z", -1, []string{"abcd"}}, 315 {commas, ",", -1, []string{"1", "2", "3", "4"}}, 316 {dots, "...", -1, []string{"1", ".2", ".3", ".4"}}, 317 {faces, "☹", -1, []string{"☺☻", ""}}, 318 {faces, "~", -1, []string{faces}}, 319 {"1 2 3 4", " ", 3, []string{"1", "2", "3 4"}}, 320 {"1 2", " ", 3, []string{"1", "2"}}, 321 } 322 323 func TestSplit(t *testing.T) { 324 for _, tt := range splittests { 325 a := SplitN(tt.s, tt.sep, tt.n) 326 if !eq(a, tt.a) { 327 t.Errorf("Split(%q, %q, %d) = %v; want %v", tt.s, tt.sep, tt.n, a, tt.a) 328 continue 329 } 330 if tt.n == 0 { 331 continue 332 } 333 s := Join(a, tt.sep) 334 if s != tt.s { 335 t.Errorf("Join(Split(%q, %q, %d), %q) = %q", tt.s, tt.sep, tt.n, tt.sep, s) 336 } 337 if tt.n < 0 { 338 b := Split(tt.s, tt.sep) 339 if !reflect.DeepEqual(a, b) { 340 t.Errorf("Split disagrees with SplitN(%q, %q, %d) = %v; want %v", tt.s, tt.sep, tt.n, b, a) 341 } 342 } 343 } 344 } 345 346 var splitaftertests = []SplitTest{ 347 {abcd, "a", -1, []string{"a", "bcd"}}, 348 {abcd, "z", -1, []string{"abcd"}}, 349 {abcd, "", -1, []string{"a", "b", "c", "d"}}, 350 {commas, ",", -1, []string{"1,", "2,", "3,", "4"}}, 351 {dots, "...", -1, []string{"1...", ".2...", ".3...", ".4"}}, 352 {faces, "☹", -1, []string{"☺☻☹", ""}}, 353 {faces, "~", -1, []string{faces}}, 354 {faces, "", -1, []string{"☺", "☻", "☹"}}, 355 {"1 2 3 4", " ", 3, []string{"1 ", "2 ", "3 4"}}, 356 {"1 2 3", " ", 3, []string{"1 ", "2 ", "3"}}, 357 {"1 2", " ", 3, []string{"1 ", "2"}}, 358 {"123", "", 2, []string{"1", "23"}}, 359 {"123", "", 17, []string{"1", "2", "3"}}, 360 } 361 362 func TestSplitAfter(t *testing.T) { 363 for _, tt := range splitaftertests { 364 a := SplitAfterN(tt.s, tt.sep, tt.n) 365 if !eq(a, tt.a) { 366 t.Errorf(`Split(%q, %q, %d) = %v; want %v`, tt.s, tt.sep, tt.n, a, tt.a) 367 continue 368 } 369 s := Join(a, "") 370 if s != tt.s { 371 t.Errorf(`Join(Split(%q, %q, %d), %q) = %q`, tt.s, tt.sep, tt.n, tt.sep, s) 372 } 373 if tt.n < 0 { 374 b := SplitAfter(tt.s, tt.sep) 375 if !reflect.DeepEqual(a, b) { 376 t.Errorf("SplitAfter disagrees with SplitAfterN(%q, %q, %d) = %v; want %v", tt.s, tt.sep, tt.n, b, a) 377 } 378 } 379 } 380 } 381 382 type FieldsTest struct { 383 s string 384 a []string 385 } 386 387 var fieldstests = []FieldsTest{ 388 {"", []string{}}, 389 {" ", []string{}}, 390 {" \t ", []string{}}, 391 {" abc ", []string{"abc"}}, 392 {"1 2 3 4", []string{"1", "2", "3", "4"}}, 393 {"1 2 3 4", []string{"1", "2", "3", "4"}}, 394 {"1\t\t2\t\t3\t4", []string{"1", "2", "3", "4"}}, 395 {"1\u20002\u20013\u20024", []string{"1", "2", "3", "4"}}, 396 {"\u2000\u2001\u2002", []string{}}, 397 {"\n™\t™\n", []string{"™", "™"}}, 398 {faces, []string{faces}}, 399 } 400 401 func TestFields(t *testing.T) { 402 for _, tt := range fieldstests { 403 a := Fields(tt.s) 404 if !eq(a, tt.a) { 405 t.Errorf("Fields(%q) = %v; want %v", tt.s, a, tt.a) 406 continue 407 } 408 } 409 } 410 411 var FieldsFuncTests = []FieldsTest{ 412 {"", []string{}}, 413 {"XX", []string{}}, 414 {"XXhiXXX", []string{"hi"}}, 415 {"aXXbXXXcX", []string{"a", "b", "c"}}, 416 } 417 418 func TestFieldsFunc(t *testing.T) { 419 for _, tt := range fieldstests { 420 a := FieldsFunc(tt.s, unicode.IsSpace) 421 if !eq(a, tt.a) { 422 t.Errorf("FieldsFunc(%q, unicode.IsSpace) = %v; want %v", tt.s, a, tt.a) 423 continue 424 } 425 } 426 pred := func(c rune) bool { return c == 'X' } 427 for _, tt := range FieldsFuncTests { 428 a := FieldsFunc(tt.s, pred) 429 if !eq(a, tt.a) { 430 t.Errorf("FieldsFunc(%q) = %v, want %v", tt.s, a, tt.a) 431 } 432 } 433 } 434 435 // Test case for any function which accepts and returns a single string. 436 type StringTest struct { 437 in, out string 438 } 439 440 // Execute f on each test case. funcName should be the name of f; it's used 441 // in failure reports. 442 func runStringTests(t *testing.T, f func(string) string, funcName string, testCases []StringTest) { 443 for _, tc := range testCases { 444 actual := f(tc.in) 445 if actual != tc.out { 446 t.Errorf("%s(%q) = %q; want %q", funcName, tc.in, actual, tc.out) 447 } 448 } 449 } 450 451 var upperTests = []StringTest{ 452 {"", ""}, 453 {"abc", "ABC"}, 454 {"AbC123", "ABC123"}, 455 {"azAZ09_", "AZAZ09_"}, 456 {"\u0250\u0250\u0250\u0250\u0250", "\u2C6F\u2C6F\u2C6F\u2C6F\u2C6F"}, // grows one byte per char 457 } 458 459 var lowerTests = []StringTest{ 460 {"", ""}, 461 {"abc", "abc"}, 462 {"AbC123", "abc123"}, 463 {"azAZ09_", "azaz09_"}, 464 {"\u2C6D\u2C6D\u2C6D\u2C6D\u2C6D", "\u0251\u0251\u0251\u0251\u0251"}, // shrinks one byte per char 465 } 466 467 const space = "\t\v\r\f\n\u0085\u00a0\u2000\u3000" 468 469 var trimSpaceTests = []StringTest{ 470 {"", ""}, 471 {"abc", "abc"}, 472 {space + "abc" + space, "abc"}, 473 {" ", ""}, 474 {" \t\r\n \t\t\r\r\n\n ", ""}, 475 {" \t\r\n x\t\t\r\r\n\n ", "x"}, 476 {" \u2000\t\r\n x\t\t\r\r\ny\n \u3000", "x\t\t\r\r\ny"}, 477 {"1 \t\r\n2", "1 \t\r\n2"}, 478 {" x\x80", "x\x80"}, 479 {" x\xc0", "x\xc0"}, 480 {"x \xc0\xc0 ", "x \xc0\xc0"}, 481 {"x \xc0", "x \xc0"}, 482 {"x \xc0 ", "x \xc0"}, 483 {"x \xc0\xc0 ", "x \xc0\xc0"}, 484 {"x ☺\xc0\xc0 ", "x ☺\xc0\xc0"}, 485 {"x ☺ ", "x ☺"}, 486 } 487 488 func tenRunes(ch rune) string { 489 r := make([]rune, 10) 490 for i := range r { 491 r[i] = ch 492 } 493 return string(r) 494 } 495 496 // User-defined self-inverse mapping function 497 func rot13(r rune) rune { 498 step := rune(13) 499 if r >= 'a' && r <= 'z' { 500 return ((r - 'a' + step) % 26) + 'a' 501 } 502 if r >= 'A' && r <= 'Z' { 503 return ((r - 'A' + step) % 26) + 'A' 504 } 505 return r 506 } 507 508 func TestMap(t *testing.T) { 509 // Run a couple of awful growth/shrinkage tests 510 a := tenRunes('a') 511 // 1. Grow. This triggers two reallocations in Map. 512 maxRune := func(rune) rune { return unicode.MaxRune } 513 m := Map(maxRune, a) 514 expect := tenRunes(unicode.MaxRune) 515 if m != expect { 516 t.Errorf("growing: expected %q got %q", expect, m) 517 } 518 519 // 2. Shrink 520 minRune := func(rune) rune { return 'a' } 521 m = Map(minRune, tenRunes(unicode.MaxRune)) 522 expect = a 523 if m != expect { 524 t.Errorf("shrinking: expected %q got %q", expect, m) 525 } 526 527 // 3. Rot13 528 m = Map(rot13, "a to zed") 529 expect = "n gb mrq" 530 if m != expect { 531 t.Errorf("rot13: expected %q got %q", expect, m) 532 } 533 534 // 4. Rot13^2 535 m = Map(rot13, Map(rot13, "a to zed")) 536 expect = "a to zed" 537 if m != expect { 538 t.Errorf("rot13: expected %q got %q", expect, m) 539 } 540 541 // 5. Drop 542 dropNotLatin := func(r rune) rune { 543 if unicode.Is(unicode.Latin, r) { 544 return r 545 } 546 return -1 547 } 548 m = Map(dropNotLatin, "Hello, 세계") 549 expect = "Hello" 550 if m != expect { 551 t.Errorf("drop: expected %q got %q", expect, m) 552 } 553 554 // 6. Identity 555 identity := func(r rune) rune { 556 return r 557 } 558 orig := "Input string that we expect not to be copied." 559 m = Map(identity, orig) 560 if (*reflect.StringHeader)(unsafe.Pointer(&orig)).Data != 561 (*reflect.StringHeader)(unsafe.Pointer(&m)).Data { 562 t.Error("unexpected copy during identity map") 563 } 564 } 565 566 func TestToUpper(t *testing.T) { runStringTests(t, ToUpper, "ToUpper", upperTests) } 567 568 func TestToLower(t *testing.T) { runStringTests(t, ToLower, "ToLower", lowerTests) } 569 570 func BenchmarkMapNoChanges(b *testing.B) { 571 identity := func(r rune) rune { 572 return r 573 } 574 for i := 0; i < b.N; i++ { 575 Map(identity, "Some string that won't be modified.") 576 } 577 } 578 579 func TestSpecialCase(t *testing.T) { 580 lower := "abcçdefgğhıijklmnoöprsştuüvyz" 581 upper := "ABCÇDEFGĞHIİJKLMNOÖPRSŞTUÜVYZ" 582 u := ToUpperSpecial(unicode.TurkishCase, upper) 583 if u != upper { 584 t.Errorf("Upper(upper) is %s not %s", u, upper) 585 } 586 u = ToUpperSpecial(unicode.TurkishCase, lower) 587 if u != upper { 588 t.Errorf("Upper(lower) is %s not %s", u, upper) 589 } 590 l := ToLowerSpecial(unicode.TurkishCase, lower) 591 if l != lower { 592 t.Errorf("Lower(lower) is %s not %s", l, lower) 593 } 594 l = ToLowerSpecial(unicode.TurkishCase, upper) 595 if l != lower { 596 t.Errorf("Lower(upper) is %s not %s", l, lower) 597 } 598 } 599 600 func TestTrimSpace(t *testing.T) { runStringTests(t, TrimSpace, "TrimSpace", trimSpaceTests) } 601 602 var trimTests = []struct { 603 f string 604 in, arg, out string 605 }{ 606 {"Trim", "abba", "a", "bb"}, 607 {"Trim", "abba", "ab", ""}, 608 {"TrimLeft", "abba", "ab", ""}, 609 {"TrimRight", "abba", "ab", ""}, 610 {"TrimLeft", "abba", "a", "bba"}, 611 {"TrimRight", "abba", "a", "abb"}, 612 {"Trim", "<tag>", "<>", "tag"}, 613 {"Trim", "* listitem", " *", "listitem"}, 614 {"Trim", `"quote"`, `"`, "quote"}, 615 {"Trim", "\u2C6F\u2C6F\u0250\u0250\u2C6F\u2C6F", "\u2C6F", "\u0250\u0250"}, 616 //empty string tests 617 {"Trim", "abba", "", "abba"}, 618 {"Trim", "", "123", ""}, 619 {"Trim", "", "", ""}, 620 {"TrimLeft", "abba", "", "abba"}, 621 {"TrimLeft", "", "123", ""}, 622 {"TrimLeft", "", "", ""}, 623 {"TrimRight", "abba", "", "abba"}, 624 {"TrimRight", "", "123", ""}, 625 {"TrimRight", "", "", ""}, 626 {"TrimRight", "☺\xc0", "☺", "☺\xc0"}, 627 {"TrimPrefix", "aabb", "a", "abb"}, 628 {"TrimPrefix", "aabb", "b", "aabb"}, 629 {"TrimSuffix", "aabb", "a", "aabb"}, 630 {"TrimSuffix", "aabb", "b", "aab"}, 631 } 632 633 func TestTrim(t *testing.T) { 634 for _, tc := range trimTests { 635 name := tc.f 636 var f func(string, string) string 637 switch name { 638 case "Trim": 639 f = Trim 640 case "TrimLeft": 641 f = TrimLeft 642 case "TrimRight": 643 f = TrimRight 644 case "TrimPrefix": 645 f = TrimPrefix 646 case "TrimSuffix": 647 f = TrimSuffix 648 default: 649 t.Errorf("Undefined trim function %s", name) 650 } 651 actual := f(tc.in, tc.arg) 652 if actual != tc.out { 653 t.Errorf("%s(%q, %q) = %q; want %q", name, tc.in, tc.arg, actual, tc.out) 654 } 655 } 656 } 657 658 func BenchmarkTrim(b *testing.B) { 659 b.ReportAllocs() 660 661 for i := 0; i < b.N; i++ { 662 for _, tc := range trimTests { 663 name := tc.f 664 var f func(string, string) string 665 switch name { 666 case "Trim": 667 f = Trim 668 case "TrimLeft": 669 f = TrimLeft 670 case "TrimRight": 671 f = TrimRight 672 case "TrimPrefix": 673 f = TrimPrefix 674 case "TrimSuffix": 675 f = TrimSuffix 676 default: 677 b.Errorf("Undefined trim function %s", name) 678 } 679 actual := f(tc.in, tc.arg) 680 if actual != tc.out { 681 b.Errorf("%s(%q, %q) = %q; want %q", name, tc.in, tc.arg, actual, tc.out) 682 } 683 } 684 } 685 } 686 687 type predicate struct { 688 f func(rune) bool 689 name string 690 } 691 692 var isSpace = predicate{unicode.IsSpace, "IsSpace"} 693 var isDigit = predicate{unicode.IsDigit, "IsDigit"} 694 var isUpper = predicate{unicode.IsUpper, "IsUpper"} 695 var isValidRune = predicate{ 696 func(r rune) bool { 697 return r != utf8.RuneError 698 }, 699 "IsValidRune", 700 } 701 702 func not(p predicate) predicate { 703 return predicate{ 704 func(r rune) bool { 705 return !p.f(r) 706 }, 707 "not " + p.name, 708 } 709 } 710 711 var trimFuncTests = []struct { 712 f predicate 713 in, out string 714 }{ 715 {isSpace, space + " hello " + space, "hello"}, 716 {isDigit, "\u0e50\u0e5212hello34\u0e50\u0e51", "hello"}, 717 {isUpper, "\u2C6F\u2C6F\u2C6F\u2C6FABCDhelloEF\u2C6F\u2C6FGH\u2C6F\u2C6F", "hello"}, 718 {not(isSpace), "hello" + space + "hello", space}, 719 {not(isDigit), "hello\u0e50\u0e521234\u0e50\u0e51helo", "\u0e50\u0e521234\u0e50\u0e51"}, 720 {isValidRune, "ab\xc0a\xc0cd", "\xc0a\xc0"}, 721 {not(isValidRune), "\xc0a\xc0", "a"}, 722 } 723 724 func TestTrimFunc(t *testing.T) { 725 for _, tc := range trimFuncTests { 726 actual := TrimFunc(tc.in, tc.f.f) 727 if actual != tc.out { 728 t.Errorf("TrimFunc(%q, %q) = %q; want %q", tc.in, tc.f.name, actual, tc.out) 729 } 730 } 731 } 732 733 var indexFuncTests = []struct { 734 in string 735 f predicate 736 first, last int 737 }{ 738 {"", isValidRune, -1, -1}, 739 {"abc", isDigit, -1, -1}, 740 {"0123", isDigit, 0, 3}, 741 {"a1b", isDigit, 1, 1}, 742 {space, isSpace, 0, len(space) - 3}, // last rune in space is 3 bytes 743 {"\u0e50\u0e5212hello34\u0e50\u0e51", isDigit, 0, 18}, 744 {"\u2C6F\u2C6F\u2C6F\u2C6FABCDhelloEF\u2C6F\u2C6FGH\u2C6F\u2C6F", isUpper, 0, 34}, 745 {"12\u0e50\u0e52hello34\u0e50\u0e51", not(isDigit), 8, 12}, 746 747 // tests of invalid UTF-8 748 {"\x801", isDigit, 1, 1}, 749 {"\x80abc", isDigit, -1, -1}, 750 {"\xc0a\xc0", isValidRune, 1, 1}, 751 {"\xc0a\xc0", not(isValidRune), 0, 2}, 752 {"\xc0☺\xc0", not(isValidRune), 0, 4}, 753 {"\xc0☺\xc0\xc0", not(isValidRune), 0, 5}, 754 {"ab\xc0a\xc0cd", not(isValidRune), 2, 4}, 755 {"a\xe0\x80cd", not(isValidRune), 1, 2}, 756 {"\x80\x80\x80\x80", not(isValidRune), 0, 3}, 757 } 758 759 func TestIndexFunc(t *testing.T) { 760 for _, tc := range indexFuncTests { 761 first := IndexFunc(tc.in, tc.f.f) 762 if first != tc.first { 763 t.Errorf("IndexFunc(%q, %s) = %d; want %d", tc.in, tc.f.name, first, tc.first) 764 } 765 last := LastIndexFunc(tc.in, tc.f.f) 766 if last != tc.last { 767 t.Errorf("LastIndexFunc(%q, %s) = %d; want %d", tc.in, tc.f.name, last, tc.last) 768 } 769 } 770 } 771 772 func equal(m string, s1, s2 string, t *testing.T) bool { 773 if s1 == s2 { 774 return true 775 } 776 e1 := Split(s1, "") 777 e2 := Split(s2, "") 778 for i, c1 := range e1 { 779 if i >= len(e2) { 780 break 781 } 782 r1, _ := utf8.DecodeRuneInString(c1) 783 r2, _ := utf8.DecodeRuneInString(e2[i]) 784 if r1 != r2 { 785 t.Errorf("%s diff at %d: U+%04X U+%04X", m, i, r1, r2) 786 } 787 } 788 return false 789 } 790 791 func TestCaseConsistency(t *testing.T) { 792 // Make a string of all the runes. 793 numRunes := int(unicode.MaxRune + 1) 794 if testing.Short() { 795 numRunes = 1000 796 } 797 a := make([]rune, numRunes) 798 for i := range a { 799 a[i] = rune(i) 800 } 801 s := string(a) 802 // convert the cases. 803 upper := ToUpper(s) 804 lower := ToLower(s) 805 806 // Consistency checks 807 if n := utf8.RuneCountInString(upper); n != numRunes { 808 t.Error("rune count wrong in upper:", n) 809 } 810 if n := utf8.RuneCountInString(lower); n != numRunes { 811 t.Error("rune count wrong in lower:", n) 812 } 813 if !equal("ToUpper(upper)", ToUpper(upper), upper, t) { 814 t.Error("ToUpper(upper) consistency fail") 815 } 816 if !equal("ToLower(lower)", ToLower(lower), lower, t) { 817 t.Error("ToLower(lower) consistency fail") 818 } 819 /* 820 These fail because of non-one-to-oneness of the data, such as multiple 821 upper case 'I' mapping to 'i'. We comment them out but keep them for 822 interest. 823 For instance: CAPITAL LETTER I WITH DOT ABOVE: 824 unicode.ToUpper(unicode.ToLower('\u0130')) != '\u0130' 825 826 if !equal("ToUpper(lower)", ToUpper(lower), upper, t) { 827 t.Error("ToUpper(lower) consistency fail"); 828 } 829 if !equal("ToLower(upper)", ToLower(upper), lower, t) { 830 t.Error("ToLower(upper) consistency fail"); 831 } 832 */ 833 } 834 835 var RepeatTests = []struct { 836 in, out string 837 count int 838 }{ 839 {"", "", 0}, 840 {"", "", 1}, 841 {"", "", 2}, 842 {"-", "", 0}, 843 {"-", "-", 1}, 844 {"-", "----------", 10}, 845 {"abc ", "abc abc abc ", 3}, 846 } 847 848 func TestRepeat(t *testing.T) { 849 for _, tt := range RepeatTests { 850 a := Repeat(tt.in, tt.count) 851 if !equal("Repeat(s)", a, tt.out, t) { 852 t.Errorf("Repeat(%v, %d) = %v; want %v", tt.in, tt.count, a, tt.out) 853 continue 854 } 855 } 856 } 857 858 func runesEqual(a, b []rune) bool { 859 if len(a) != len(b) { 860 return false 861 } 862 for i, r := range a { 863 if r != b[i] { 864 return false 865 } 866 } 867 return true 868 } 869 870 var RunesTests = []struct { 871 in string 872 out []rune 873 lossy bool 874 }{ 875 {"", []rune{}, false}, 876 {" ", []rune{32}, false}, 877 {"ABC", []rune{65, 66, 67}, false}, 878 {"abc", []rune{97, 98, 99}, false}, 879 {"\u65e5\u672c\u8a9e", []rune{26085, 26412, 35486}, false}, 880 {"ab\x80c", []rune{97, 98, 0xFFFD, 99}, true}, 881 {"ab\xc0c", []rune{97, 98, 0xFFFD, 99}, true}, 882 } 883 884 func TestRunes(t *testing.T) { 885 for _, tt := range RunesTests { 886 a := []rune(tt.in) 887 if !runesEqual(a, tt.out) { 888 t.Errorf("[]rune(%q) = %v; want %v", tt.in, a, tt.out) 889 continue 890 } 891 if !tt.lossy { 892 // can only test reassembly if we didn't lose information 893 s := string(a) 894 if s != tt.in { 895 t.Errorf("string([]rune(%q)) = %x; want %x", tt.in, s, tt.in) 896 } 897 } 898 } 899 } 900 901 func TestReadByte(t *testing.T) { 902 testStrings := []string{"", abcd, faces, commas} 903 for _, s := range testStrings { 904 reader := NewReader(s) 905 if e := reader.UnreadByte(); e == nil { 906 t.Errorf("Unreading %q at beginning: expected error", s) 907 } 908 var res bytes.Buffer 909 for { 910 b, e := reader.ReadByte() 911 if e == io.EOF { 912 break 913 } 914 if e != nil { 915 t.Errorf("Reading %q: %s", s, e) 916 break 917 } 918 res.WriteByte(b) 919 // unread and read again 920 e = reader.UnreadByte() 921 if e != nil { 922 t.Errorf("Unreading %q: %s", s, e) 923 break 924 } 925 b1, e := reader.ReadByte() 926 if e != nil { 927 t.Errorf("Reading %q after unreading: %s", s, e) 928 break 929 } 930 if b1 != b { 931 t.Errorf("Reading %q after unreading: want byte %q, got %q", s, b, b1) 932 break 933 } 934 } 935 if res.String() != s { 936 t.Errorf("Reader(%q).ReadByte() produced %q", s, res.String()) 937 } 938 } 939 } 940 941 func TestReadRune(t *testing.T) { 942 testStrings := []string{"", abcd, faces, commas} 943 for _, s := range testStrings { 944 reader := NewReader(s) 945 if e := reader.UnreadRune(); e == nil { 946 t.Errorf("Unreading %q at beginning: expected error", s) 947 } 948 res := "" 949 for { 950 r, z, e := reader.ReadRune() 951 if e == io.EOF { 952 break 953 } 954 if e != nil { 955 t.Errorf("Reading %q: %s", s, e) 956 break 957 } 958 res += string(r) 959 // unread and read again 960 e = reader.UnreadRune() 961 if e != nil { 962 t.Errorf("Unreading %q: %s", s, e) 963 break 964 } 965 r1, z1, e := reader.ReadRune() 966 if e != nil { 967 t.Errorf("Reading %q after unreading: %s", s, e) 968 break 969 } 970 if r1 != r { 971 t.Errorf("Reading %q after unreading: want rune %q, got %q", s, r, r1) 972 break 973 } 974 if z1 != z { 975 t.Errorf("Reading %q after unreading: want size %d, got %d", s, z, z1) 976 break 977 } 978 } 979 if res != s { 980 t.Errorf("Reader(%q).ReadRune() produced %q", s, res) 981 } 982 } 983 } 984 985 var UnreadRuneErrorTests = []struct { 986 name string 987 f func(*Reader) 988 }{ 989 {"Read", func(r *Reader) { r.Read([]byte{0}) }}, 990 {"ReadByte", func(r *Reader) { r.ReadByte() }}, 991 {"UnreadRune", func(r *Reader) { r.UnreadRune() }}, 992 {"Seek", func(r *Reader) { r.Seek(0, io.SeekCurrent) }}, 993 {"WriteTo", func(r *Reader) { r.WriteTo(&bytes.Buffer{}) }}, 994 } 995 996 func TestUnreadRuneError(t *testing.T) { 997 for _, tt := range UnreadRuneErrorTests { 998 reader := NewReader("0123456789") 999 if _, _, err := reader.ReadRune(); err != nil { 1000 // should not happen 1001 t.Fatal(err) 1002 } 1003 tt.f(reader) 1004 err := reader.UnreadRune() 1005 if err == nil { 1006 t.Errorf("Unreading after %s: expected error", tt.name) 1007 } 1008 } 1009 } 1010 1011 var ReplaceTests = []struct { 1012 in string 1013 old, new string 1014 n int 1015 out string 1016 }{ 1017 {"hello", "l", "L", 0, "hello"}, 1018 {"hello", "l", "L", -1, "heLLo"}, 1019 {"hello", "x", "X", -1, "hello"}, 1020 {"", "x", "X", -1, ""}, 1021 {"radar", "r", "<r>", -1, "<r>ada<r>"}, 1022 {"", "", "<>", -1, "<>"}, 1023 {"banana", "a", "<>", -1, "b<>n<>n<>"}, 1024 {"banana", "a", "<>", 1, "b<>nana"}, 1025 {"banana", "a", "<>", 1000, "b<>n<>n<>"}, 1026 {"banana", "an", "<>", -1, "b<><>a"}, 1027 {"banana", "ana", "<>", -1, "b<>na"}, 1028 {"banana", "", "<>", -1, "<>b<>a<>n<>a<>n<>a<>"}, 1029 {"banana", "", "<>", 10, "<>b<>a<>n<>a<>n<>a<>"}, 1030 {"banana", "", "<>", 6, "<>b<>a<>n<>a<>n<>a"}, 1031 {"banana", "", "<>", 5, "<>b<>a<>n<>a<>na"}, 1032 {"banana", "", "<>", 1, "<>banana"}, 1033 {"banana", "a", "a", -1, "banana"}, 1034 {"banana", "a", "a", 1, "banana"}, 1035 {"☺☻☹", "", "<>", -1, "<>☺<>☻<>☹<>"}, 1036 } 1037 1038 func TestReplace(t *testing.T) { 1039 for _, tt := range ReplaceTests { 1040 if s := Replace(tt.in, tt.old, tt.new, tt.n); s != tt.out { 1041 t.Errorf("Replace(%q, %q, %q, %d) = %q, want %q", tt.in, tt.old, tt.new, tt.n, s, tt.out) 1042 } 1043 } 1044 } 1045 1046 var TitleTests = []struct { 1047 in, out string 1048 }{ 1049 {"", ""}, 1050 {"a", "A"}, 1051 {" aaa aaa aaa ", " Aaa Aaa Aaa "}, 1052 {" Aaa Aaa Aaa ", " Aaa Aaa Aaa "}, 1053 {"123a456", "123a456"}, 1054 {"double-blind", "Double-Blind"}, 1055 {"ÿøû", "Ÿøû"}, 1056 {"with_underscore", "With_underscore"}, 1057 {"unicode \xe2\x80\xa8 line separator", "Unicode \xe2\x80\xa8 Line Separator"}, 1058 } 1059 1060 func TestTitle(t *testing.T) { 1061 for _, tt := range TitleTests { 1062 if s := Title(tt.in); s != tt.out { 1063 t.Errorf("Title(%q) = %q, want %q", tt.in, s, tt.out) 1064 } 1065 } 1066 } 1067 1068 var ContainsTests = []struct { 1069 str, substr string 1070 expected bool 1071 }{ 1072 {"abc", "bc", true}, 1073 {"abc", "bcd", false}, 1074 {"abc", "", true}, 1075 {"", "a", false}, 1076 1077 // cases to cover code in runtime/asm_amd64.s:indexShortStr 1078 // 2-byte needle 1079 {"xxxxxx", "01", false}, 1080 {"01xxxx", "01", true}, 1081 {"xx01xx", "01", true}, 1082 {"xxxx01", "01", true}, 1083 {"01xxxxx"[1:], "01", false}, 1084 {"xxxxx01"[:6], "01", false}, 1085 // 3-byte needle 1086 {"xxxxxxx", "012", false}, 1087 {"012xxxx", "012", true}, 1088 {"xx012xx", "012", true}, 1089 {"xxxx012", "012", true}, 1090 {"012xxxxx"[1:], "012", false}, 1091 {"xxxxx012"[:7], "012", false}, 1092 // 4-byte needle 1093 {"xxxxxxxx", "0123", false}, 1094 {"0123xxxx", "0123", true}, 1095 {"xx0123xx", "0123", true}, 1096 {"xxxx0123", "0123", true}, 1097 {"0123xxxxx"[1:], "0123", false}, 1098 {"xxxxx0123"[:8], "0123", false}, 1099 // 5-7-byte needle 1100 {"xxxxxxxxx", "01234", false}, 1101 {"01234xxxx", "01234", true}, 1102 {"xx01234xx", "01234", true}, 1103 {"xxxx01234", "01234", true}, 1104 {"01234xxxxx"[1:], "01234", false}, 1105 {"xxxxx01234"[:9], "01234", false}, 1106 // 8-byte needle 1107 {"xxxxxxxxxxxx", "01234567", false}, 1108 {"01234567xxxx", "01234567", true}, 1109 {"xx01234567xx", "01234567", true}, 1110 {"xxxx01234567", "01234567", true}, 1111 {"01234567xxxxx"[1:], "01234567", false}, 1112 {"xxxxx01234567"[:12], "01234567", false}, 1113 // 9-15-byte needle 1114 {"xxxxxxxxxxxxx", "012345678", false}, 1115 {"012345678xxxx", "012345678", true}, 1116 {"xx012345678xx", "012345678", true}, 1117 {"xxxx012345678", "012345678", true}, 1118 {"012345678xxxxx"[1:], "012345678", false}, 1119 {"xxxxx012345678"[:13], "012345678", false}, 1120 // 16-byte needle 1121 {"xxxxxxxxxxxxxxxxxxxx", "0123456789ABCDEF", false}, 1122 {"0123456789ABCDEFxxxx", "0123456789ABCDEF", true}, 1123 {"xx0123456789ABCDEFxx", "0123456789ABCDEF", true}, 1124 {"xxxx0123456789ABCDEF", "0123456789ABCDEF", true}, 1125 {"0123456789ABCDEFxxxxx"[1:], "0123456789ABCDEF", false}, 1126 {"xxxxx0123456789ABCDEF"[:20], "0123456789ABCDEF", false}, 1127 // 17-31-byte needle 1128 {"xxxxxxxxxxxxxxxxxxxxx", "0123456789ABCDEFG", false}, 1129 {"0123456789ABCDEFGxxxx", "0123456789ABCDEFG", true}, 1130 {"xx0123456789ABCDEFGxx", "0123456789ABCDEFG", true}, 1131 {"xxxx0123456789ABCDEFG", "0123456789ABCDEFG", true}, 1132 {"0123456789ABCDEFGxxxxx"[1:], "0123456789ABCDEFG", false}, 1133 {"xxxxx0123456789ABCDEFG"[:21], "0123456789ABCDEFG", false}, 1134 1135 // partial match cases 1136 {"xx01x", "012", false}, // 3 1137 {"xx0123x", "01234", false}, // 5-7 1138 {"xx01234567x", "012345678", false}, // 9-15 1139 {"xx0123456789ABCDEFx", "0123456789ABCDEFG", false}, // 17-31, issue 15679 1140 } 1141 1142 func TestContains(t *testing.T) { 1143 for _, ct := range ContainsTests { 1144 if Contains(ct.str, ct.substr) != ct.expected { 1145 t.Errorf("Contains(%s, %s) = %v, want %v", 1146 ct.str, ct.substr, !ct.expected, ct.expected) 1147 } 1148 } 1149 } 1150 1151 var ContainsAnyTests = []struct { 1152 str, substr string 1153 expected bool 1154 }{ 1155 {"", "", false}, 1156 {"", "a", false}, 1157 {"", "abc", false}, 1158 {"a", "", false}, 1159 {"a", "a", true}, 1160 {"aaa", "a", true}, 1161 {"abc", "xyz", false}, 1162 {"abc", "xcz", true}, 1163 {"a☺b☻c☹d", "uvw☻xyz", true}, 1164 {"aRegExp*", ".(|)*+?^$[]", true}, 1165 {dots + dots + dots, " ", false}, 1166 } 1167 1168 func TestContainsAny(t *testing.T) { 1169 for _, ct := range ContainsAnyTests { 1170 if ContainsAny(ct.str, ct.substr) != ct.expected { 1171 t.Errorf("ContainsAny(%s, %s) = %v, want %v", 1172 ct.str, ct.substr, !ct.expected, ct.expected) 1173 } 1174 } 1175 } 1176 1177 var ContainsRuneTests = []struct { 1178 str string 1179 r rune 1180 expected bool 1181 }{ 1182 {"", 'a', false}, 1183 {"a", 'a', true}, 1184 {"aaa", 'a', true}, 1185 {"abc", 'y', false}, 1186 {"abc", 'c', true}, 1187 {"a☺b☻c☹d", 'x', false}, 1188 {"a☺b☻c☹d", '☻', true}, 1189 {"aRegExp*", '*', true}, 1190 } 1191 1192 func TestContainsRune(t *testing.T) { 1193 for _, ct := range ContainsRuneTests { 1194 if ContainsRune(ct.str, ct.r) != ct.expected { 1195 t.Errorf("ContainsRune(%q, %q) = %v, want %v", 1196 ct.str, ct.r, !ct.expected, ct.expected) 1197 } 1198 } 1199 } 1200 1201 var EqualFoldTests = []struct { 1202 s, t string 1203 out bool 1204 }{ 1205 {"abc", "abc", true}, 1206 {"ABcd", "ABcd", true}, 1207 {"123abc", "123ABC", true}, 1208 {"αβδ", "ΑΒΔ", true}, 1209 {"abc", "xyz", false}, 1210 {"abc", "XYZ", false}, 1211 {"abcdefghijk", "abcdefghijX", false}, 1212 {"abcdefghijk", "abcdefghij\u212A", true}, 1213 {"abcdefghijK", "abcdefghij\u212A", true}, 1214 {"abcdefghijkz", "abcdefghij\u212Ay", false}, 1215 {"abcdefghijKz", "abcdefghij\u212Ay", false}, 1216 } 1217 1218 func TestEqualFold(t *testing.T) { 1219 for _, tt := range EqualFoldTests { 1220 if out := EqualFold(tt.s, tt.t); out != tt.out { 1221 t.Errorf("EqualFold(%#q, %#q) = %v, want %v", tt.s, tt.t, out, tt.out) 1222 } 1223 if out := EqualFold(tt.t, tt.s); out != tt.out { 1224 t.Errorf("EqualFold(%#q, %#q) = %v, want %v", tt.t, tt.s, out, tt.out) 1225 } 1226 } 1227 } 1228 1229 var CountTests = []struct { 1230 s, sep string 1231 num int 1232 }{ 1233 {"", "", 1}, 1234 {"", "notempty", 0}, 1235 {"notempty", "", 9}, 1236 {"smaller", "not smaller", 0}, 1237 {"12345678987654321", "6", 2}, 1238 {"611161116", "6", 3}, 1239 {"notequal", "NotEqual", 0}, 1240 {"equal", "equal", 1}, 1241 {"abc1231231123q", "123", 3}, 1242 {"11111", "11", 2}, 1243 } 1244 1245 func TestCount(t *testing.T) { 1246 for _, tt := range CountTests { 1247 if num := Count(tt.s, tt.sep); num != tt.num { 1248 t.Errorf("Count(\"%s\", \"%s\") = %d, want %d", tt.s, tt.sep, num, tt.num) 1249 } 1250 } 1251 } 1252 1253 func makeBenchInputHard() string { 1254 tokens := [...]string{ 1255 "<a>", "<p>", "<b>", "<strong>", 1256 "</a>", "</p>", "</b>", "</strong>", 1257 "hello", "world", 1258 } 1259 x := make([]byte, 0, 1<<20) 1260 for { 1261 i := rand.Intn(len(tokens)) 1262 if len(x)+len(tokens[i]) >= 1<<20 { 1263 break 1264 } 1265 x = append(x, tokens[i]...) 1266 } 1267 return string(x) 1268 } 1269 1270 var benchInputHard = makeBenchInputHard() 1271 1272 func benchmarkIndexHard(b *testing.B, sep string) { 1273 for i := 0; i < b.N; i++ { 1274 Index(benchInputHard, sep) 1275 } 1276 } 1277 1278 func benchmarkLastIndexHard(b *testing.B, sep string) { 1279 for i := 0; i < b.N; i++ { 1280 LastIndex(benchInputHard, sep) 1281 } 1282 } 1283 1284 func benchmarkCountHard(b *testing.B, sep string) { 1285 for i := 0; i < b.N; i++ { 1286 Count(benchInputHard, sep) 1287 } 1288 } 1289 1290 func BenchmarkIndexHard1(b *testing.B) { benchmarkIndexHard(b, "<>") } 1291 func BenchmarkIndexHard2(b *testing.B) { benchmarkIndexHard(b, "</pre>") } 1292 func BenchmarkIndexHard3(b *testing.B) { benchmarkIndexHard(b, "<b>hello world</b>") } 1293 1294 func BenchmarkLastIndexHard1(b *testing.B) { benchmarkLastIndexHard(b, "<>") } 1295 func BenchmarkLastIndexHard2(b *testing.B) { benchmarkLastIndexHard(b, "</pre>") } 1296 func BenchmarkLastIndexHard3(b *testing.B) { benchmarkLastIndexHard(b, "<b>hello world</b>") } 1297 1298 func BenchmarkCountHard1(b *testing.B) { benchmarkCountHard(b, "<>") } 1299 func BenchmarkCountHard2(b *testing.B) { benchmarkCountHard(b, "</pre>") } 1300 func BenchmarkCountHard3(b *testing.B) { benchmarkCountHard(b, "<b>hello world</b>") } 1301 1302 var benchInputTorture = Repeat("ABC", 1<<10) + "123" + Repeat("ABC", 1<<10) 1303 var benchNeedleTorture = Repeat("ABC", 1<<10+1) 1304 1305 func BenchmarkIndexTorture(b *testing.B) { 1306 for i := 0; i < b.N; i++ { 1307 Index(benchInputTorture, benchNeedleTorture) 1308 } 1309 } 1310 1311 func BenchmarkCountTorture(b *testing.B) { 1312 for i := 0; i < b.N; i++ { 1313 Count(benchInputTorture, benchNeedleTorture) 1314 } 1315 } 1316 1317 func BenchmarkCountTortureOverlapping(b *testing.B) { 1318 A := Repeat("ABC", 1<<20) 1319 B := Repeat("ABC", 1<<10) 1320 for i := 0; i < b.N; i++ { 1321 Count(A, B) 1322 } 1323 } 1324 1325 var makeFieldsInput = func() string { 1326 x := make([]byte, 1<<20) 1327 // Input is ~10% space, ~10% 2-byte UTF-8, rest ASCII non-space. 1328 for i := range x { 1329 switch rand.Intn(10) { 1330 case 0: 1331 x[i] = ' ' 1332 case 1: 1333 if i > 0 && x[i-1] == 'x' { 1334 copy(x[i-1:], "χ") 1335 break 1336 } 1337 fallthrough 1338 default: 1339 x[i] = 'x' 1340 } 1341 } 1342 return string(x) 1343 } 1344 1345 var fieldsInput = makeFieldsInput() 1346 1347 func BenchmarkFields(b *testing.B) { 1348 b.SetBytes(int64(len(fieldsInput))) 1349 for i := 0; i < b.N; i++ { 1350 Fields(fieldsInput) 1351 } 1352 } 1353 1354 func BenchmarkFieldsFunc(b *testing.B) { 1355 b.SetBytes(int64(len(fieldsInput))) 1356 for i := 0; i < b.N; i++ { 1357 FieldsFunc(fieldsInput, unicode.IsSpace) 1358 } 1359 } 1360 1361 func BenchmarkSplit1(b *testing.B) { 1362 for i := 0; i < b.N; i++ { 1363 Split(benchInputHard, "") 1364 } 1365 } 1366 1367 func BenchmarkSplit2(b *testing.B) { 1368 for i := 0; i < b.N; i++ { 1369 Split(benchInputHard, "/") 1370 } 1371 } 1372 1373 func BenchmarkSplit3(b *testing.B) { 1374 for i := 0; i < b.N; i++ { 1375 Split(benchInputHard, "hello") 1376 } 1377 } 1378 1379 func BenchmarkRepeat(b *testing.B) { 1380 for i := 0; i < b.N; i++ { 1381 Repeat("-", 80) 1382 } 1383 }