add quote meta func

This commit is contained in:
gobwas 2016-02-25 00:31:30 +03:00
parent f3d7e5e3d7
commit eccf734cd7
2 changed files with 19 additions and 2 deletions

View File

@ -60,7 +60,7 @@ func MustCompile(pattern string, separators ...rune) Glob {
func QuoteMeta(s string) string { func QuoteMeta(s string) string {
b := make([]byte, 2*len(s)) b := make([]byte, 2*len(s))
// A byte loop is correct because all metacharacters are ASCII. // a byte loop is correct because all meta characters are ASCII
j := 0 j := 0
for i := 0; i < len(s); i++ { for i := 0; i < len(s); i++ {
if special(s[i]) { if special(s[i]) {

View File

@ -151,6 +151,12 @@ func TestGlob(t *testing.T) {
} }
func TestQuoteMeta(t *testing.T) { func TestQuoteMeta(t *testing.T) {
specialsQuoted := make([]byte, len(specials)*2)
for i, j := 0, 0; i < len(specials); i, j = i+1, j+2 {
specialsQuoted[j] = '\\'
specialsQuoted[j+1] = specials[i]
}
for id, test := range []struct { for id, test := range []struct {
in, out string in, out string
}{ }{
@ -158,11 +164,22 @@ func TestQuoteMeta(t *testing.T) {
in: `[foo*]`, in: `[foo*]`,
out: `\[foo\*\]`, out: `\[foo\*\]`,
}, },
{
in: string(specials),
out: string(specialsQuoted),
},
{
in: string(append([]byte("some text and"), specials...)),
out: string(append([]byte("some text and"), specialsQuoted...)),
},
} { } {
act := QuoteMeta(test.in) act := QuoteMeta(test.in)
if act != test.out { if act != test.out {
t.Errorf("#%d QuoteMeta(%q) = %q; want %q", id, test.in, act, test.out) t.Errorf("#%d QuoteMeta(%q) = %q; want %q", id, test.in, act, test.out)
} }
if _, err := Compile(act); err != nil {
t.Errorf("#%d _, err := Compile(QuoteMeta(%q) = %q); err = %q", id, test.in, act, err)
}
} }
} }