@@ -10,7 +10,7 @@ import (
10
10
// If no matches are found, an empty slice is returned.
11
11
func Matches (needle string , maxDistance int , haystack ... string ) (matches []string ) {
12
12
for _ , hay := range haystack {
13
- if Distance (needle , hay ) <= maxDistance {
13
+ if d , err := Distance (needle , hay ); err == nil && d <= maxDistance {
14
14
matches = append (matches , hay )
15
15
}
16
16
}
@@ -21,19 +21,22 @@ func Matches(needle string, maxDistance int, haystack ...string) (matches []stri
21
21
// Distance returns the edit distance between a and b using the
22
22
// Wagner-Fischer algorithm.
23
23
// 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" )
27
30
}
28
31
m := uint8 (len (a ))
29
32
n := uint8 (len (b ))
30
33
31
34
// Special cases for empty strings
32
35
if m == 0 {
33
- return int (n )
36
+ return int (n ), nil
34
37
}
35
38
if n == 0 {
36
- return int (m )
39
+ return int (m ), nil
37
40
}
38
41
39
42
// Allocate a matrix of size m+1 * n+1
@@ -71,7 +74,7 @@ func Distance(a, b string) int {
71
74
}
72
75
}
73
76
74
- return int (d [m ][n ])
77
+ return int (d [m ][n ]), nil
75
78
}
76
79
77
80
func min [T constraints.Ordered ](ts ... T ) T {
0 commit comments