aboutsummaryrefslogtreecommitdiff
path: root/hashtable_test.go
blob: 2d4199729ab217ecc2f438f6d40bcd5eeebcdf19 (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
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
// Copyright 2017 The Bazel 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 skylark

import (
	"math/rand"
	"testing"
)

func TestHashtable(t *testing.T) {
	testHashtable(t, make(map[int]bool))
}

func BenchmarkHashtable(b *testing.B) {
	// TODO(adonovan): MakeInt probably dominates the cost of this benchmark.
	// Optimise or avoid it.
	for i := 0; i < b.N; i++ {
		testHashtable(b, nil)
	}
}

// testHashtable is both a test and a benchmark of hashtable.
// When sane != nil, it acts as a test against the semantics of Go's map.
func testHashtable(tb testing.TB, sane map[int]bool) {
	zipf := rand.NewZipf(rand.New(rand.NewSource(0)), 1.1, 1.0, 1000.0)
	var ht hashtable

	// Insert 10000 random ints into the map.
	for j := 0; j < 10000; j++ {
		k := int(zipf.Uint64())
		if err := ht.insert(MakeInt(k), None); err != nil {
			tb.Fatal(err)
		}
		if sane != nil {
			sane[k] = true
		}
	}

	// Do 10000 random lookups in the map.
	for j := 0; j < 10000; j++ {
		k := int(zipf.Uint64())
		_, found, err := ht.lookup(MakeInt(k))
		if err != nil {
			tb.Fatal(err)
		}
		if sane != nil {
			_, found2 := sane[k]
			if found != found2 {
				tb.Fatal("sanity check failed")
			}
		}
	}

	// Do 10000 random deletes from the map.
	for j := 0; j < 10000; j++ {
		k := int(zipf.Uint64())
		_, found, err := ht.delete(MakeInt(k))
		if err != nil {
			tb.Fatal(err)
		}
		if sane != nil {
			_, found2 := sane[k]
			if found != found2 {
				tb.Fatal("sanity check failed")
			}
			delete(sane, k)
		}
	}

	if sane != nil {
		if int(ht.len) != len(sane) {
			tb.Fatal("sanity check failed")
		}
	}
}