File: utils.go

package info (click to toggle)
golang-gopkg-irc.v4 4.0.0%2Bdfsg-2
  • links: PTS, VCS
  • area: main
  • in suites: sid, trixie
  • size: 244 kB
  • sloc: python: 63; makefile: 2
file content (50 lines) | stat: -rw-r--r-- 1,013 bytes parent folder | download
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())
}