8000 levenshtein: do not panic · coder/coder@f74d0e8 · GitHub
[go: up one dir, main page]

Skip to content

Commit f74d0e8

Browse files
committed
levenshtein: do not panic
1 parent 5bec286 commit f74d0e8

File tree

2 files changed

+12
-8
lines changed

2 files changed

+12
-8
lines changed

cli/cliutil/levenshtein/levenshtein.go

Lines changed: 10 additions & 7 deletions
Original file line numberDiff line numberDiff line change
@@ -10,7 +10,7 @@ import (
1010
// If no matches are found, an empty slice is returned.
1111
func Matches(needle string, maxDistance int, haystack ...string) (matches []string) {
1212
for _, hay := range haystack {
13-
if Distance(needle, hay) <= maxDistance {
13+
if d, err := Distance(needle, hay); err == nil && d <= maxDistance {
1414
matches = append(matches, hay)
1515
}
1616
}
@@ -21,19 +21,22 @@ func Matches(needle string, maxDistance int, haystack ...string) (matches []stri
2121
// Distance returns the edit distance between a and b using the
2222
// Wagner-Fischer algorithm.
2323
// A and B must be less than 255 characters long.
24-
func Distance(a, b string) int {
25-
if len(a) > 255 || len(b) > 255 {
26-
panic(xerrors.Errorf("levenshtein: strings too long: %q, %q", a, b))
24+
func Distance(a, b string) (int, error) {
25+
if len(a) > 255 {
26+
return 0, xerrors.Errorf("levenshtein: a must be less than 255 characters long")
27+
}
28+
if len(b) > 255 {
29+
return 0, xerrors.Errorf("levenshtein: b must be less than 255 characters long")
2730
}
2831
m := uint8(len(a))
2932
n := uint8(len(b))
3033

3134
// Special cases for empty strings
3235
if m == 0 {
33-
return int(n)
36+
return int(n), nil
3437
}
3538
if n == 0 {
36-
return int(m)
39+
return int(m), nil
3740
}
3841

3942
// Allocate a matrix of size m+1 * n+1
@@ -71,7 +74,7 @@ func Distance(a, b string) int {
7174
}
7275
}
7376

74-
return int(d[m][n])
77+
return int(d[m][n]), nil
7578
}
7679

7780
func min[T constraints.Ordered](ts ...T) T {

cli/cliutil/levenshtein/levenshtein_test.go

Lines changed: 2 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -158,7 +158,8 @@ func Test_Levenshtein_Distance(t *testing.T) {
158158
tt := tt
159159
t.Run(tt.Name, func(t *testing.T) {
160160
t.Parallel()
161-
actual := levenshtein.Distance(tt.A, tt.B)
161+
actual, err := levenshtein.Distance(tt.A, tt.B)
162+
require.NoError(t, err)
162163
require.Equal(t, tt.Expected, actual)
163164
})
164165
}

0 commit comments

Comments
 (0)
0