suffixarray_test.go 7.15 KB
Newer Older
1 2 3 4 5 6 7
// Copyright 2010 The Go Authors. All rights reserved.
// Use of this source code is governed by a BSD-style
// license that can be found in the LICENSE file.

package suffixarray

import (
8
	"bytes"
9
	"math/rand"
10
	"regexp"
11 12 13 14 15 16
	"sort"
	"strings"
	"testing"
)

type testCase struct {
17 18 19
	name     string   // name of test case
	source   string   // source to index
	patterns []string // patterns to lookup
20 21 22 23 24 25 26 27 28
}

var testCases = []testCase{
	{
		"empty string",
		"",
		[]string{
			"",
			"foo",
29 30 31
			"(foo)",
			".*",
			"a*",
32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50
		},
	},

	{
		"all a's",
		"aaaaaaaaaa", // 10 a's
		[]string{
			"",
			"a",
			"aa",
			"aaa",
			"aaaa",
			"aaaaa",
			"aaaaaa",
			"aaaaaaa",
			"aaaaaaaa",
			"aaaaaaaaa",
			"aaaaaaaaaa",
			"aaaaaaaaaaa", // 11 a's
51 52 53 54 55 56
			".",
			".*",
			"a+",
			"aa+",
			"aaaa[b]?",
			"aaa*",
57 58 59 60 61 62 63 64 65 66 67 68 69
		},
	},

	{
		"abc",
		"abc",
		[]string{
			"a",
			"b",
			"c",
			"ab",
			"bc",
			"abc",
70 71 72
			"a.c",
			"a(b|c)",
			"abc?",
73 74 75 76 77 78 79 80 81 82 83 84
		},
	},

	{
		"barbara*3",
		"barbarabarbarabarbara",
		[]string{
			"a",
			"bar",
			"rab",
			"arab",
			"barbar",
85
			"bara?bar",
86 87 88 89 90 91 92 93 94 95 96
		},
	},

	{
		"typing drill",
		"Now is the time for all good men to come to the aid of their country.",
		[]string{
			"Now",
			"the time",
			"to come the aid",
			"is the time for all good men to come to the aid of their",
97
			"to (come|the)?",
98 99
		},
	},
100 101 102 103 104 105

	{
		"godoc simulation",
		"package main\n\nimport(\n    \"rand\"\n    ",
		[]string{},
	},
106 107
}

108
// find all occurrences of s in source; report at most n occurrences
109
func find(src, s string, n int) []int {
110
	var res []int
111
	if s != "" && n != 0 {
112
		// find at most n occurrences of s in src
113 114 115 116 117 118
		for i := -1; n < 0 || len(res) < n; {
			j := strings.Index(src[i+1:], s)
			if j < 0 {
				break
			}
			i += j + 1
119
			res = append(res, i)
120 121 122 123 124
		}
	}
	return res
}

125 126 127
func testLookup(t *testing.T, tc *testCase, x *Index, s string, n int) {
	res := x.Lookup([]byte(s), n)
	exp := find(tc.source, s, n)
128

129 130 131 132
	// check that the lengths match
	if len(res) != len(exp) {
		t.Errorf("test %q, lookup %q (n = %d): expected %d results; got %d", tc.name, s, n, len(exp), len(res))
	}
133

134 135 136 137 138 139
	// if n >= 0 the number of results is limited --- unless n >= all results,
	// we may obtain different positions from the Index and from find (because
	// Index may not find the results in the same order as find) => in general
	// we cannot simply check that the res and exp lists are equal

	// check that each result is in fact a correct match and there are no duplicates
140
	sort.Ints(res)
141 142 143 144 145 146 147 148 149 150
	for i, r := range res {
		if r < 0 || len(tc.source) <= r {
			t.Errorf("test %q, lookup %q, result %d (n = %d): index %d out of range [0, %d[", tc.name, s, i, n, r, len(tc.source))
		} else if !strings.HasPrefix(tc.source[r:], s) {
			t.Errorf("test %q, lookup %q, result %d (n = %d): index %d not a match", tc.name, s, i, n, r)
		}
		if i > 0 && res[i-1] == r {
			t.Errorf("test %q, lookup %q, result %d (n = %d): found duplicate index %d", tc.name, s, i, n, r)
		}
	}
151

152 153
	if n < 0 {
		// all results computed - sorted res and exp must be equal
154
		for i, r := range res {
155 156 157
			e := exp[i]
			if r != e {
				t.Errorf("test %q, lookup %q, result %d: expected index %d; got %d", tc.name, s, i, e, r)
158 159
			}
		}
160 161
	}
}
162

163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187
func testFindAllIndex(t *testing.T, tc *testCase, x *Index, rx *regexp.Regexp, n int) {
	res := x.FindAllIndex(rx, n)
	exp := rx.FindAllStringIndex(tc.source, n)

	// check that the lengths match
	if len(res) != len(exp) {
		t.Errorf("test %q, FindAllIndex %q (n = %d): expected %d results; got %d", tc.name, rx, n, len(exp), len(res))
	}

	// if n >= 0 the number of results is limited --- unless n >= all results,
	// we may obtain different positions from the Index and from regexp (because
	// Index may not find the results in the same order as regexp) => in general
	// we cannot simply check that the res and exp lists are equal

	// check that each result is in fact a correct match and the result is sorted
	for i, r := range res {
		if r[0] < 0 || r[0] > r[1] || len(tc.source) < r[1] {
			t.Errorf("test %q, FindAllIndex %q, result %d (n == %d): illegal match [%d, %d]", tc.name, rx, i, n, r[0], r[1])
		} else if !rx.MatchString(tc.source[r[0]:r[1]]) {
			t.Errorf("test %q, FindAllIndex %q, result %d (n = %d): [%d, %d] not a match", tc.name, rx, i, n, r[0], r[1])
		}
	}

	if n < 0 {
		// all results computed - sorted res and exp must be equal
188
		for i, r := range res {
189 190 191 192
			e := exp[i]
			if r[0] != e[0] || r[1] != e[1] {
				t.Errorf("test %q, FindAllIndex %q, result %d: expected match [%d, %d]; got [%d, %d]",
					tc.name, rx, i, e[0], e[1], r[0], r[1])
193 194
			}
		}
195 196
	}
}
197

198 199 200 201 202
func testLookups(t *testing.T, tc *testCase, x *Index, n int) {
	for _, pat := range tc.patterns {
		testLookup(t, tc, x, pat, n)
		if rx, err := regexp.Compile(pat); err == nil {
			testFindAllIndex(t, tc, x, rx, n)
203 204 205 206
		}
	}
}

207 208 209 210 211 212 213 214 215 216
// index is used to hide the sort.Interface
type index Index

func (x *index) Len() int           { return len(x.sa) }
func (x *index) Less(i, j int) bool { return bytes.Compare(x.at(i), x.at(j)) < 0 }
func (x *index) Swap(i, j int)      { x.sa[i], x.sa[j] = x.sa[j], x.sa[i] }
func (a *index) at(i int) []byte    { return a.data[a.sa[i]:] }

func testConstruction(t *testing.T, tc *testCase, x *Index) {
	if !sort.IsSorted((*index)(x)) {
217
		t.Errorf("failed testConstruction %s", tc.name)
218 219 220
	}
}

221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249
func equal(x, y *Index) bool {
	if !bytes.Equal(x.data, y.data) {
		return false
	}
	for i, j := range x.sa {
		if j != y.sa[i] {
			return false
		}
	}
	return true
}

// returns the serialized index size
func testSaveRestore(t *testing.T, tc *testCase, x *Index) int {
	var buf bytes.Buffer
	if err := x.Write(&buf); err != nil {
		t.Errorf("failed writing index %s (%s)", tc.name, err)
	}
	size := buf.Len()
	var y Index
	if err := y.Read(&buf); err != nil {
		t.Errorf("failed reading index %s (%s)", tc.name, err)
	}
	if !equal(x, &y) {
		t.Errorf("restored index doesn't match saved index %s", tc.name)
	}
	return size
}

250 251 252
func TestIndex(t *testing.T) {
	for _, tc := range testCases {
		x := New([]byte(tc.source))
253
		testConstruction(t, &tc, x)
254
		testSaveRestore(t, &tc, x)
255 256 257 258 259
		testLookups(t, &tc, x, 0)
		testLookups(t, &tc, x, 1)
		testLookups(t, &tc, x, 10)
		testLookups(t, &tc, x, 2e9)
		testLookups(t, &tc, x, -1)
260 261
	}
}
262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304

// Of all possible inputs, the random bytes have the least amount of substring
// repetition, and the repeated bytes have the most. For most algorithms,
// the running time of every input will be between these two.
func benchmarkNew(b *testing.B, random bool) {
	b.StopTimer()
	data := make([]byte, 1e6)
	if random {
		for i := range data {
			data[i] = byte(rand.Intn(256))
		}
	}
	b.StartTimer()
	for i := 0; i < b.N; i++ {
		New(data)
	}
}

func BenchmarkNewIndexRandom(b *testing.B) {
	benchmarkNew(b, true)
}
func BenchmarkNewIndexRepeat(b *testing.B) {
	benchmarkNew(b, false)
}

func BenchmarkSaveRestore(b *testing.B) {
	b.StopTimer()
	r := rand.New(rand.NewSource(0x5a77a1)) // guarantee always same sequence
	data := make([]byte, 10<<20)            // 10MB of data to index
	for i := range data {
		data[i] = byte(r.Intn(256))
	}
	x := New(data)
	size := testSaveRestore(nil, nil, x)       // verify correctness
	buf := bytes.NewBuffer(make([]byte, size)) // avoid growing
	b.SetBytes(int64(size))
	b.StartTimer()
	for i := 0; i < b.N; i++ {
		x.Write(buf)
		var y Index
		y.Read(buf)
	}
}