From e943cdd3277ad21e34fc8813c413e0c35ac40e85 Mon Sep 17 00:00:00 2001 From: Alberto Carretero Date: Wed, 11 Dec 2024 10:41:41 +0100 Subject: [PATCH] feat: optimize common case of GlobPath --- internal/strdist/strdist.go | 18 ++++++++++++++++++ 1 file changed, 18 insertions(+) diff --git a/internal/strdist/strdist.go b/internal/strdist/strdist.go index f205bfcf..ac2b446a 100644 --- a/internal/strdist/strdist.go +++ b/internal/strdist/strdist.go @@ -105,6 +105,11 @@ func Distance(a, b string, f CostFunc, cut int64) int64 { // * - Any zero or more characters, except for / // ** - Any zero or more characters, including / func GlobPath(a, b string) bool { + if !wildcardPrefixMatch(a, b) { + // Fast path. + return false + } + a = strings.ReplaceAll(a, "**", "⁑") b = strings.ReplaceAll(b, "**", "⁑") return Distance(a, b, globCost, 1) == 0 @@ -125,3 +130,16 @@ func globCost(ar, br rune) Cost { } return Cost{SwapAB: 1, DeleteA: 1, InsertB: 1} } + +func wildcardPrefixMatch(a, b string) bool { + ai := strings.IndexAny(a, "*?") + bi := strings.IndexAny(b, "*?") + if ai == -1 { + ai = len(a) + } + if bi == -1 { + bi = len(b) + } + mini := min(ai, bi) + return a[:mini] == b[:mini] +}