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