This commit is contained in:
2025-04-04 19:06:29 -07:00
parent ebb45b13bb
commit 393381d456
275 changed files with 56094 additions and 2 deletions

20
pattern/pattern.go Normal file
View File

@ -0,0 +1,20 @@
package pattern
import (
"path/filepath"
"strings"
)
// Match checks whether a string matches a pattern
func Match(pattern, s string) bool {
if pattern == "*" {
return true
}
// Separators found in the string break filepath.Match, so we'll remove all of them.
// This has a pretty significant impact on performance when there are separators in
// the strings, but at least it doesn't break filepath.Match.
s = strings.ReplaceAll(s, string(filepath.Separator), "")
pattern = strings.ReplaceAll(pattern, string(filepath.Separator), "")
matched, _ := filepath.Match(pattern, s)
return matched
}

View File

@ -0,0 +1,21 @@
package pattern
import "testing"
func BenchmarkMatch(b *testing.B) {
for n := 0; n < b.N; n++ {
if !Match("*ing*", "livingroom") {
b.Error("should've matched")
}
}
b.ReportAllocs()
}
func BenchmarkMatchWithBackslash(b *testing.B) {
for n := 0; n < b.N; n++ {
if !Match("*ing*", "living\\room") {
b.Error("should've matched")
}
}
b.ReportAllocs()
}

43
pattern/pattern_test.go Normal file
View File

@ -0,0 +1,43 @@
package pattern
import (
"fmt"
"testing"
)
func TestMatch(t *testing.T) {
testMatch(t, "*", "livingroom_123", true)
testMatch(t, "**", "livingroom_123", true)
testMatch(t, "living*", "livingroom_123", true)
testMatch(t, "*living*", "livingroom_123", true)
testMatch(t, "*123", "livingroom_123", true)
testMatch(t, "*_*", "livingroom_123", true)
testMatch(t, "living*_*3", "livingroom_123", true)
testMatch(t, "living*room_*3", "livingroom_123", true)
testMatch(t, "living*room_*3", "livingroom_123", true)
testMatch(t, "*vin*om*2*", "livingroom_123", true)
testMatch(t, "livingroom_123", "livingroom_123", true)
testMatch(t, "*livingroom_123*", "livingroom_123", true)
testMatch(t, "*test*", "\\test", true)
testMatch(t, "livingroom", "livingroom_123", false)
testMatch(t, "livingroom123", "livingroom_123", false)
testMatch(t, "what", "livingroom_123", false)
testMatch(t, "*what*", "livingroom_123", false)
testMatch(t, "*.*", "livingroom_123", false)
testMatch(t, "room*123", "livingroom_123", false)
}
func testMatch(t *testing.T, pattern, key string, expectedToMatch bool) {
t.Run(fmt.Sprintf("pattern '%s' from '%s'", pattern, key), func(t *testing.T) {
matched := Match(pattern, key)
if expectedToMatch {
if !matched {
t.Errorf("%s should've matched pattern '%s'", key, pattern)
}
} else {
if matched {
t.Errorf("%s shouldn't have matched pattern '%s'", key, pattern)
}
}
})
}