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