Skip to content

Commit da85a26

Browse files
psydvlpolyfloyd
authored andcommitted
refactor: speed up isAllowedErrAndFunc via map
1 parent d3851a4 commit da85a26

File tree

2 files changed

+58
-4
lines changed

2 files changed

+58
-4
lines changed

errorlint/allowed.go

+16-4
Original file line numberDiff line numberDiff line change
@@ -77,6 +77,17 @@ var allowedErrors = []struct {
7777
{err: "context.Canceled", fun: "(context.Context).Err"},
7878
}
7979

80+
var allowedErrorsMap = make(map[string]map[string]struct{})
81+
82+
func init() {
83+
for _, pair := range allowedErrors {
84+
if _, ok := allowedErrorsMap[pair.err]; !ok {
85+
allowedErrorsMap[pair.err] = make(map[string]struct{})
86+
}
87+
allowedErrorsMap[pair.err][pair.fun] = struct{}{}
88+
}
89+
}
90+
8091
var allowedErrorWildcards = []struct {
8192
err string
8293
fun string
@@ -86,17 +97,18 @@ var allowedErrorWildcards = []struct {
8697
}
8798

8899
func isAllowedErrAndFunc(err, fun string) bool {
89-
for _, allow := range allowedErrorWildcards {
90-
if strings.HasPrefix(fun, allow.fun) && strings.HasPrefix(err, allow.err) {
100+
if allowedFuncs, allowErr := allowedErrorsMap[err]; allowErr {
101+
if _, allow := allowedFuncs[fun]; allow {
91102
return true
92103
}
93104
}
94105

95-
for _, allow := range allowedErrors {
96-
if allow.fun == fun && allow.err == err {
106+
for _, allow := range allowedErrorWildcards {
107+
if strings.HasPrefix(fun, allow.fun) && strings.HasPrefix(err, allow.err) {
97108
return true
98109
}
99110
}
111+
100112
return false
101113
}
102114

errorlint/allowed_test.go

+42
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,42 @@
1+
package errorlint
2+
3+
import (
4+
"testing"
5+
)
6+
7+
func Test_isAllowedErrAndFunc(t *testing.T) {
8+
testCases := []struct {
9+
desc string
10+
fun string
11+
err string
12+
expect bool
13+
}{
14+
{
15+
desc: "allowedErrors: (io.Reader).Read",
16+
err: "io.EOF",
17+
fun: "(io.Reader).Read",
18+
expect: true,
19+
},
20+
{
21+
desc: "allowedErrorWildcards: golang.org/x/sys/unix.",
22+
err: "golang.org/x/sys/unix.EINVAL",
23+
fun: "golang.org/x/sys/unix.EpollCreate",
24+
expect: true,
25+
},
26+
{
27+
desc: "errorlint.Reader Read",
28+
err: "io.EOF",
29+
fun: "(errorlint.Reader).Read",
30+
expect: false,
31+
},
32+
// {desc: "fail test", expect: true},
33+
}
34+
for _, tt := range testCases {
35+
t.Run(tt.desc, func(t *testing.T) {
36+
result := isAllowedErrAndFunc(tt.err, tt.fun)
37+
if tt.expect != result {
38+
t.Errorf("Not equal:\n\texpect: %t,\n\tactual: %t\n", tt.expect, result)
39+
}
40+
})
41+
}
42+
}

0 commit comments

Comments
 (0)