forked from mirror/glob
quote meta func
This commit is contained in:
parent
f910d4c1c7
commit
1801ade38c
19
glob.go
19
glob.go
|
@ -54,3 +54,22 @@ func MustCompile(pattern string, separators ...rune) Glob {
|
|||
|
||||
return g
|
||||
}
|
||||
|
||||
// QuoteMeta returns a string that quotes all glob pattern metacharacters
|
||||
// inside the argument text; For example, QuoteMeta(`{foo*}`) returns `\[foo\*\]`.
|
||||
func QuoteMeta(s string) string {
|
||||
b := make([]byte, 2*len(s))
|
||||
|
||||
// A byte loop is correct because all metacharacters are ASCII.
|
||||
j := 0
|
||||
for i := 0; i < len(s); i++ {
|
||||
if special(s[i]) {
|
||||
b[j] = '\\'
|
||||
j++
|
||||
}
|
||||
b[j] = s[i]
|
||||
j++
|
||||
}
|
||||
|
||||
return string(b[0:j])
|
||||
}
|
||||
|
|
20
glob_test.go
20
glob_test.go
|
@ -150,6 +150,22 @@ func TestGlob(t *testing.T) {
|
|||
}
|
||||
}
|
||||
|
||||
func TestQuoteMeta(t *testing.T) {
|
||||
for id, test := range []struct {
|
||||
in, out string
|
||||
}{
|
||||
{
|
||||
in: `[foo*]`,
|
||||
out: `\[foo\*\]`,
|
||||
},
|
||||
} {
|
||||
act := QuoteMeta(test.in)
|
||||
if act != test.out {
|
||||
t.Errorf("#%d QuoteMeta(%q) = %q; want %q", id, test.in, act, test.out)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
func BenchmarkParseGlob(b *testing.B) {
|
||||
for i := 0; i < b.N; i++ {
|
||||
Compile(pattern_all)
|
||||
|
@ -193,12 +209,12 @@ func BenchmarkAllGlobMismatch(b *testing.B) {
|
|||
_ = m.Match(fixture_all_mismatch)
|
||||
}
|
||||
}
|
||||
func BenchmarkAllGlobMatchParallel(b *testing.B) {
|
||||
func BenchmarkAllGlobMismatchParallel(b *testing.B) {
|
||||
m, _ := Compile(pattern_all)
|
||||
|
||||
b.RunParallel(func(pb *testing.PB) {
|
||||
for pb.Next() {
|
||||
_ = m.Match(fixture_all_match)
|
||||
_ = m.Match(fixture_all_mismatch)
|
||||
}
|
||||
})
|
||||
}
|
||||
|
|
18
lexer.go
18
lexer.go
|
@ -1,6 +1,7 @@
|
|||
package glob
|
||||
|
||||
import (
|
||||
"bytes"
|
||||
"fmt"
|
||||
"strings"
|
||||
"unicode/utf8"
|
||||
|
@ -19,6 +20,23 @@ const (
|
|||
char_range_between = '-'
|
||||
)
|
||||
|
||||
var specials = []byte{
|
||||
char_any,
|
||||
char_separator,
|
||||
char_single,
|
||||
char_escape,
|
||||
char_range_open,
|
||||
char_range_close,
|
||||
char_terms_open,
|
||||
char_terms_close,
|
||||
char_range_not,
|
||||
char_range_between,
|
||||
}
|
||||
|
||||
func special(c byte) bool {
|
||||
return bytes.IndexByte(specials, c) != -1
|
||||
}
|
||||
|
||||
var eof rune = 0
|
||||
|
||||
type stateFn func(*lexer) stateFn
|
||||
|
|
Loading…
Reference in New Issue