summaryrefslogtreecommitdiff
path: root/lib/diskio/kmp_test.go
blob: 6c6ef789c7cf1630514b2f7909155a948aae4ded (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
// Copyright (C) 2022  Luke Shumaker <lukeshu@lukeshu.com>
//
// SPDX-License-Identifier: GPL-2.0-or-later

package diskio

import (
	"bytes"
	"testing"

	"github.com/stretchr/testify/assert"
)

func TestBuildKMPTable(t *testing.T) {
	substr := []byte("ababaa")
	table := buildKMPTable(substr)
	assert.Equal(t,
		[]int{0, 0, 1, 2, 3, 1},
		table)
	for j, val := range table {
		matchLen := j + 1
		assert.Equalf(t, substr[:val], substr[matchLen-val:matchLen],
			"for table[%d]=%d", j, val)
	}
}

func FuzzBuildKMPTable(f *testing.F) {
	f.Add([]byte("ababaa"))
	f.Fuzz(func(t *testing.T, substr []byte) {
		table := buildKMPTable(substr)
		assert.Equal(t, len(substr), len(table), "length")
		for j, val := range table {
			matchLen := j + 1
			assert.Equalf(t, substr[:val], substr[matchLen-val:matchLen],
				"for table[%d]=%d", j, val)
		}
	})
}

func NaiveFindAll(str, substr []byte) []int64 {
	var matches []int64
	for i := range str {
		if bytes.HasPrefix(str[i:], substr) {
			matches = append(matches, int64(i))
		}
	}
	return matches
}

func FuzzFindAll(f *testing.F) {
	f.Fuzz(func(t *testing.T, str, substr []byte) {
		if len(substr) == 0 {
			t.Skip()
		}
		t.Logf("str   =%q", str)
		t.Logf("substr=%q", substr)
		exp := NaiveFindAll(str, substr)
		act, err := FindAll(bytes.NewReader(str), substr)
		assert.NoError(t, err)
		assert.Equal(t, exp, act)
	})
}