summaryrefslogtreecommitdiff
path: root/src/crypto/internal/boring/bcache/cache_test.go
blob: 19458a1c245dfcc4432950557d7e5e59d8ca2657 (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
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
// Copyright 2022 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 bcache

import (
	"fmt"
	"runtime"
	"sync"
	"sync/atomic"
	"testing"
)

var registeredCache Cache[int, int32]

func init() {
	registeredCache.Register()
}

var seq atomic.Uint32

func next[T int | int32]() *T {
	x := new(T)
	*x = T(seq.Add(1))
	return x
}

func str[T int | int32](x *T) string {
	if x == nil {
		return "nil"
	}
	return fmt.Sprint(*x)
}

func TestCache(t *testing.T) {
	// Use unregistered cache for functionality tests,
	// to keep the runtime from clearing behind our backs.
	c := new(Cache[int, int32])

	// Create many entries.
	m := make(map[*int]*int32)
	for i := 0; i < 10000; i++ {
		k := next[int]()
		v := next[int32]()
		m[k] = v
		c.Put(k, v)
	}

	// Overwrite a random 20% of those.
	n := 0
	for k := range m {
		v := next[int32]()
		m[k] = v
		c.Put(k, v)
		if n++; n >= 2000 {
			break
		}
	}

	// Check results.
	for k, v := range m {
		if cv := c.Get(k); cv != v {
			t.Fatalf("c.Get(%v) = %v, want %v", str(k), str(cv), str(v))
		}
	}

	c.Clear()
	for k := range m {
		if cv := c.Get(k); cv != nil {
			t.Fatalf("after GC, c.Get(%v) = %v, want nil", str(k), str(cv))
		}
	}

	// Check that registered cache is cleared at GC.
	c = &registeredCache
	for k, v := range m {
		c.Put(k, v)
	}
	runtime.GC()
	for k := range m {
		if cv := c.Get(k); cv != nil {
			t.Fatalf("after Clear, c.Get(%v) = %v, want nil", str(k), str(cv))
		}
	}

	// Check that cache works for concurrent access.
	// Lists are discarded if they reach 1000 entries,
	// and there are cacheSize list heads, so we should be
	// able to do 100 * cacheSize entries with no problem at all.
	c = new(Cache[int, int32])
	var barrier, wg sync.WaitGroup
	const N = 100
	barrier.Add(N)
	wg.Add(N)
	var lost int32
	for i := 0; i < N; i++ {
		go func() {
			defer wg.Done()

			m := make(map[*int]*int32)
			for j := 0; j < cacheSize; j++ {
				k, v := next[int](), next[int32]()
				m[k] = v
				c.Put(k, v)
			}
			barrier.Done()
			barrier.Wait()

			for k, v := range m {
				if cv := c.Get(k); cv != v {
					t.Errorf("c.Get(%v) = %v, want %v", str(k), str(cv), str(v))
					atomic.AddInt32(&lost, +1)
				}
			}
		}()
	}
	wg.Wait()
	if lost != 0 {
		t.Errorf("lost %d entries", lost)
	}
}