Debian Codegraph @

vt/cache_sweep_test.go

raw symbols SCIP
1 // Copyright 2026 The TCell Authors
2 //
3 // Licensed under the Apache License, Version 2.0 (the "License");
4 // you may not use this file except in compliance with the License.
5 // You may obtain a copy of the License at
6 //
7 // http://www.apache.org/licenses/LICENSE-2.0
8 //
9 // Unless required by applicable law or agreed to in writing, software
10 // distributed under the License is distributed on an "AS IS" BASIS,
11 // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12 // See the License for the specific language governing permissions and
13 // limitations under the License.
14
15 package vt
16
17 import (
18 "fmt"
19 "testing"
20 "unicode/utf8"
21 )
22
23 type benchRuneCache struct {
24 entries []benchRuneCacheEntry
25 n int
26 }
27
28 type benchRuneCacheEntry struct {
29 r rune
30 s string
31 }
32
33 func newBenchRuneCache(size int) *benchRuneCache {
34 return &benchRuneCache{entries: make([]benchRuneCacheEntry, size)}
35 }
36
37 func (c *benchRuneCache) stringFor(r rune) string {
38 if r < utf8.RuneSelf {
39 return asciiRuneStrings[r]
40 }
41
42 for i := 0; i < c.n; i++ {
43 if c.entries[i].r == r {
44 return c.entries[i].s
45 }
46 }
47
48 s := string(r)
49 if c.n < len(c.entries) {
50 c.n++
51 }
52 copy(c.entries[1:c.n], c.entries[:c.n-1])
53 c.entries[0] = benchRuneCacheEntry{r: r, s: s}
54 return s
55 }
56
57 var sweepMixedRunes32 = []rune{
58 '\u0416', '\u0414', '\u042E', '\u042F',
59 '\u041F', '\u041B', '\u0424', '\u042B',
60 '\u042D', '\u0411', '\u0413', '\u0428',
61 '\u00E9', '\u00F6', '\u00FC', '\u00F1',
62 '\u00E7', '\u00F8', '\u00E5', '\u00DF',
63 '\u0142', '\u0111', '\u0127', '\u0131',
64 '\U0001F600', '\U0001F680', '\U0001F9EA', '\U0001F525',
65 '\U0001F355', '\U0001F389', '\U0001F4BB', '\U0001F4E6',
66 }
67
68 var sweepMixedRunes64 = append(append([]rune{}, sweepMixedRunes32...),
69 '\u0105', '\u0107', '\u0119', '\u0123',
70 '\u0135', '\u0137', '\u0144', '\u015B',
71 '\u015F', '\u0163', '\u0165', '\u017A',
72 '\U0001F31F', '\U0001F4A1', '\U0001F4AF', '\U0001F680',
73 '\U0001F9F0', '\U0001F9D1', '\U0001F9EB', '\U0001FAE0',
74 '\u250C', '\u2510', '\u2514', '\u2518',
75 '\u2500', '\u2502', '\u251C', '\u2524',
76 '\u252C', '\u2534', '\u253C', '\u2571',
77 )
78
79 func BenchmarkRuneStringCacheSweep(b *testing.B) {
80 for _, tc := range []struct {
81 name string
82 seq []rune
83 }{
84 {name: "mixed32", seq: sweepMixedRunes32},
85 {name: "mixed64", seq: sweepMixedRunes64},
86 } {
87 b.Run(tc.name, func(b *testing.B) {
88 for _, size := range []int{8, 16, 32, 64} {
89 b.Run(fmt.Sprintf("size=%d", size), func(b *testing.B) {
90 cache := newBenchRuneCache(size)
91 for _, r := range tc.seq {
92 _ = cache.stringFor(r)
93 }
94 b.ReportAllocs()
95 b.ResetTimer()
96 for i := 0; i < b.N; i++ {
97 _ = cache.stringFor(tc.seq[i%len(tc.seq)])
98 }
99 })
100 }
101 })
102 }
103 }