-
-
Notifications
You must be signed in to change notification settings - Fork 17
/
utils.go
50 lines (41 loc) · 1013 Bytes
/
utils.go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
package irc
import (
"bytes"
"regexp"
)
var maskTranslations = map[byte]string{
'?': ".",
'*': ".*",
}
// MaskToRegex converts an irc mask to a go Regexp for more convenient
// use. This should never return an error, but we have this here just
// in case.
func MaskToRegex(rawMask string) (*regexp.Regexp, error) {
input := bytes.NewBufferString(rawMask)
output := &bytes.Buffer{}
output.WriteByte('^')
for {
c, err := input.ReadByte()
if err != nil {
break
}
if c == '\\' { //nolint:nestif
c, err = input.ReadByte()
if err != nil {
output.WriteString(regexp.QuoteMeta("\\"))
break
}
if c == '?' || c == '*' || c == '\\' {
output.WriteString(regexp.QuoteMeta(string(c)))
} else {
output.WriteString(regexp.QuoteMeta("\\" + string(c)))
}
} else if trans, ok := maskTranslations[c]; ok {
output.WriteString(trans)
} else {
output.WriteString(regexp.QuoteMeta(string(c)))
}
}
output.WriteByte('$')
return regexp.Compile(output.String())
}