| 1 |
package mem |
| 2 |
|
| 3 |
import ( |
| 4 |
"bytes" |
| 5 |
"testing" |
| 6 |
) |
| 7 |
|
| 8 |
func TestContainsByte(t *testing.T) { |
| 9 |
for _, test := range []struct { |
| 10 |
name string |
| 11 |
haystack []byte |
| 12 |
needle byte |
| 13 |
expect bool |
| 14 |
}{ |
| 15 |
{ |
| 16 |
name: "nil", |
| 17 |
haystack: nil, |
| 18 |
needle: 'x', |
| 19 |
expect: false, |
| 20 |
}, |
| 21 |
{ |
| 22 |
name: "empty", |
| 23 |
haystack: []byte{}, |
| 24 |
needle: 'x', |
| 25 |
expect: false, |
| 26 |
}, |
| 27 |
{ |
| 28 |
name: "one equal byte", |
| 29 |
haystack: []byte{'x'}, |
| 30 |
needle: 'x', |
| 31 |
expect: true, |
| 32 |
}, |
| 33 |
{ |
| 34 |
name: "one unequal byte", |
| 35 |
haystack: []byte{'a'}, |
| 36 |
needle: 'x', |
| 37 |
expect: false, |
| 38 |
}, |
| 39 |
{ |
| 40 |
name: "run without byte", |
| 41 |
haystack: []byte("aaaaaaaaaaaaaaaaaa"), |
| 42 |
needle: 'x', |
| 43 |
expect: false, |
| 44 |
}, |
| 45 |
{ |
| 46 |
name: "run with byte prefix", |
| 47 |
haystack: []byte("xaaaaaaaaaaaaaaaaaa"), |
| 48 |
needle: 'x', |
| 49 |
expect: true, |
| 50 |
}, |
| 51 |
{ |
| 52 |
name: "run with byte suffix", |
| 53 |
haystack: []byte("aaaaaaaaaaaaaaaaaax"), |
| 54 |
needle: 'x', |
| 55 |
expect: true, |
| 56 |
}, |
| 57 |
} { |
| 58 |
t.Run(test.name, func(t *testing.T) { |
| 59 |
if actual := ContainsByte(test.haystack, test.needle); actual != test.expect { |
| 60 |
t.Fatalf("ContainsByte(%v, %v) => %v", test.haystack, test.needle, actual) |
| 61 |
} |
| 62 |
}) |
| 63 |
} |
| 64 |
|
| 65 |
// Test specific lengths up to 1KB. |
| 66 |
var src []byte |
| 67 |
for i := 0; i < 1000; i++ { |
| 68 |
if ContainsByte(src, 'x') { |
| 69 |
t.Fatalf("ContainsByte(%v, 'x') => true", src) |
| 70 |
} |
| 71 |
src = append(src, 'x') |
| 72 |
if !ContainsByte(src, 'x') { |
| 73 |
t.Fatalf("ContainsByte(%v, 'x') => false", src) |
| 74 |
} |
| 75 |
src[i] = '0' |
| 76 |
} |
| 77 |
} |
| 78 |
|
| 79 |
func BenchmarkContainsByte(b *testing.B) { |
| 80 |
benchmarkContainsByte(b, ContainsByte) |
| 81 |
} |
| 82 |
|
| 83 |
func benchmarkContainsByte(b *testing.B, contains func([]byte, byte) bool) { |
| 84 |
large := bytes.Repeat([]byte{'a'}, 8*1024) |
| 85 |
|
| 86 |
b.Run("empty", benchmarkContainsByteCase(contains, nil, 'x')) |
| 87 |
b.Run("small-not-found", benchmarkContainsByteCase(contains, []byte("abcdef"), 'x')) |
| 88 |
b.Run("small-found-at-end", benchmarkContainsByteCase(contains, []byte("abcdefx"), 'x')) |
| 89 |
b.Run("large-not-found", benchmarkContainsByteCase(contains, large, 'x')) |
| 90 |
b.Run("large-found-at-end", benchmarkContainsByteCase(contains, append(large, 'x'), 'x')) |
| 91 |
} |
| 92 |
|
| 93 |
func benchmarkContainsByteCase(contains func([]byte, byte) bool, haystack []byte, needle byte) func(*testing.B) { |
| 94 |
return func(b *testing.B) { |
| 95 |
b.SetBytes(int64(len(haystack))) |
| 96 |
b.ResetTimer() |
| 97 |
for i := 0; i < b.N; i++ { |
| 98 |
contains(haystack, needle) |
| 99 |
} |
| 100 |
} |
| 101 |
} |