Fix memory leak and split CompileGlob into ConvertGlob

This commit is contained in:
Elara 2022-05-21 11:40:09 -07:00
parent 0a475038e1
commit a937a67bab
1 changed files with 18 additions and 8 deletions

26
glob.go
View File

@ -7,17 +7,17 @@ import (
"modernc.org/libc" "modernc.org/libc"
) )
// CompileGlob converts the given glob into a // ConvertGlob converts the given glob into a
// pcre regular expression, and then compiles it, // pcre regular expression, and then returns
// returning the result. // the result.
func CompileGlob(glob string) (*Regexp, error) { func ConvertGlob(glob string) (string, error) {
tls := libc.NewTLS() tls := libc.NewTLS()
defer tls.Close() defer tls.Close()
// Get C string from given glob // Get C string from given glob
cGlob, err := libc.CString(glob) cGlob, err := libc.CString(glob)
if err != nil { if err != nil {
return nil, err return "", err
} }
defer libc.Xfree(tls, cGlob) defer libc.Xfree(tls, cGlob)
// Convert length to size_t // Convert length to size_t
@ -44,15 +44,25 @@ func CompileGlob(glob string) (*Regexp, error) {
0, 0,
) )
if ret != 0 { if ret != 0 {
return nil, codeToError(tls, ret) return "", codeToError(tls, ret)
} }
defer lib.Xpcre2_converted_pattern_free_8(tls, outPtr)
// Get output as byte slice // Get output as byte slice
out := unsafe.Slice((*byte)(unsafe.Pointer(outPtr)), outLen) out := unsafe.Slice((*byte)(unsafe.Pointer(outPtr)), outLen)
// Convert output to string // Convert output to string
// This copies the data, so it's safe for later use // This copies the data, so it's safe for later use
pattern := string(out) return string(out), nil
}
// CompileGlob is a convenience function that converts
// a glob to a pcre regular expression and then compiles
// it.
func CompileGlob(glob string) (*Regexp, error) {
pattern, err := ConvertGlob(glob)
if err != nil {
return nil, err
}
// Compile converted glob and return results // Compile converted glob and return results
return Compile(pattern) return Compile(pattern)
} }