*: improve ErrKeyExists generation and MemoizeStr (#54412)

ref pingcap/tidb#53004
This commit is contained in:
lance6716
2024-07-04 11:46:28 +08:00
committed by GitHub
parent 22f9a3bab3
commit eaa603231f
8 changed files with 99 additions and 70 deletions

View File

@ -360,10 +360,18 @@ func (l StringerFunc) String() string {
return l()
}
// MemoizeStr returns memoized version of stringFunc.
// MemoizeStr returns memoized version of stringFunc. When the result of l is not
// "", it will be cached and returned directly next time.
//
// MemoizeStr is not concurrency safe.
func MemoizeStr(l func() string) fmt.Stringer {
var result string
return StringerFunc(func() string {
return l()
if result != "" {
return result
}
result = l()
return result
})
}

View File

@ -206,6 +206,18 @@ func TestEscapeGlobQuestionMark(t *testing.T) {
}
}
func TestMemoizeStr(t *testing.T) {
cnt := 0
slowStringFn := func() string {
cnt++
return "slow"
}
stringer := MemoizeStr(slowStringFn)
require.Equal(t, "slow", stringer.String())
require.Equal(t, "slow", stringer.String())
require.Equal(t, 1, cnt)
}
func BenchmarkDoMatch(b *testing.B) {
escape := byte('\\')
tbl := []struct {