summaryrefslogtreecommitdiff
path: root/internal/regex/regex.go
blob: a34f7c1f3e7e1aabbae273b4fda2d87ed7d0e354 (plain)
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
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
package regex

import (
	"bytes"
	"fmt"
	"regexp"
	"strings"
)

// Regex for filtering lines.
type Regex struct {
	// The original regex string
	regexStr string
	// The Golang regexp object
	re *regexp.Regexp
	// For now only use the first flag at flags[0], but in the future we can
	// set and use multiple flags.
	flags       []Flag
	initialized bool
	// Fields for optimized literal string matching
	isLiteral    bool   // true if pattern contains no regex metacharacters
	literalStr   string // literal string for string matching
	literalBytes []byte // literal bytes for byte matching
}

// String returns the string representation of Regex.
func (r Regex) String() string {
	return fmt.Sprintf("Regex(regexStr:%s,flags:%s,initialized:%t,re==nil:%t,isLiteral:%t)",
		r.regexStr, r.flags, r.initialized, r.re == nil, r.isLiteral)
}

// isLiteralPattern checks if the pattern contains no regex metacharacters.
// It returns true only for patterns that can be matched using simple string contains.
func isLiteralPattern(pattern string) bool {
	// Check for common regex metacharacters
	// Note: We're being conservative here - only treating truly literal strings as literals
	metaChars := `.+*?^$[]{}()|\\`
	for _, ch := range pattern {
		if strings.ContainsRune(metaChars, ch) {
			return false
		}
	}
	return true
}

// NewNoop is a noop regex (doing nothing).
func NewNoop() Regex {
	return Regex{
		flags:       []Flag{Noop},
		initialized: true,
	}
}

// New returns a new regex object.
func New(regexStr string, flag Flag) (Regex, error) {
	if regexStr == "" || regexStr == "." || regexStr == ".*" {
		return NewNoop(), nil
	}
	return new(regexStr, []Flag{flag})
}

func new(regexStr string, flags []Flag) (Regex, error) {
	if len(flags) == 0 {
		flags = append(flags, Default)
	}

	r := Regex{
		regexStr: regexStr,
		flags:    flags,
	}

	// Check if this is a literal pattern for optimization
	if isLiteralPattern(regexStr) {
		r.isLiteral = true
		r.literalStr = regexStr
		r.literalBytes = []byte(regexStr)
		r.initialized = true
		// We still compile the regex for backward compatibility and as a fallback
		// This ensures serialization/deserialization works correctly
		re, err := regexp.Compile(regexStr)
		if err != nil {
			return r, err
		}
		r.re = re
		return r, nil
	}

	// For non-literal patterns, compile as regex
	re, err := regexp.Compile(regexStr)
	if err != nil {
		return r, err
	}

	r.re = re
	r.initialized = true
	return r, nil
}

// Match a byte string.
func (r Regex) Match(b []byte) bool {
	// Use optimized literal matching if possible
	if r.isLiteral {
		switch r.flags[0] {
		case Default:
			return bytes.Contains(b, r.literalBytes)
		case Invert:
			return !bytes.Contains(b, r.literalBytes)
		case Noop:
			return true
		default:
			return false
		}
	}

	// Fall back to regex matching for non-literal patterns
	switch r.flags[0] {
	case Default:
		return r.re.Match(b)
	case Invert:
		return !r.re.Match(b)
	case Noop:
		return true
	default:
		return false
	}
}

// MatchString matches a string.
func (r Regex) MatchString(str string) bool {
	// Use optimized literal matching if possible
	if r.isLiteral {
		switch r.flags[0] {
		case Default:
			return strings.Contains(str, r.literalStr)
		case Invert:
			return !strings.Contains(str, r.literalStr)
		case Noop:
			return true
		default:
			return false
		}
	}

	// Fall back to regex matching for non-literal patterns
	switch r.flags[0] {
	case Default:
		return r.re.MatchString(str)
	case Invert:
		return !r.re.MatchString(str)
	case Noop:
		return true
	default:
		return false
	}
}

// Serialize the regex.
func (r Regex) Serialize() (string, error) {
	var flags []string
	for _, flag := range r.flags {
		flags = append(flags, flag.String())
	}
	if !r.initialized {
		return "", fmt.Errorf("Unable to serialize regex as not initialized properly: %v", r)
	}
	// Include literal flag in serialization if applicable
	if r.isLiteral {
		flags = append(flags, "literal")
	}
	return fmt.Sprintf("regex:%s %s", strings.Join(flags, ","), r.regexStr), nil
}

// IsLiteral returns true if this regex is using literal string matching
func (r Regex) IsLiteral() bool {
	return r.isLiteral
}

// Pattern returns the original pattern string
func (r Regex) Pattern() string {
	return r.regexStr
}

// Deserialize the regex.
func Deserialize(str string) (Regex, error) {
	// Get regex string
	s := strings.SplitN(str, " ", 2)
	if len(s) < 2 {
		return NewNoop(), nil
	}
	flagsStr := s[0]
	regexStr := s[1]

	if !strings.HasPrefix(flagsStr, "regex") {
		return Regex{}, fmt.Errorf("unable to deserialize regex '%s': should start "+
			"with string 'regex'", str)
	}

	// Parse regex flags, e.g. "regex:flag1,flag2,flag3..."
	var flags []Flag
	forceLiteral := false
	if strings.Contains(flagsStr, ":") {
		s := strings.SplitN(flagsStr, ":", 2)
		for _, flagStr := range strings.Split(s[1], ",") {
			if flagStr == "literal" {
				// This is our optimization hint, not a regular flag
				forceLiteral = true
				continue
			}
			flag, err := NewFlag(flagStr)
			if err != nil {
				continue
			}
			flags = append(flags, flag)
		}
	}
	
	// Create the regex with proper literal detection
	r, err := new(regexStr, flags)
	if err != nil {
		return r, err
	}
	
	// If the serialized form indicated it was literal, ensure we treat it as such
	// This maintains consistency across client-server communication
	if forceLiteral && !r.isLiteral {
		// The pattern might have been literal on the client but not detected as such here
		// This could happen if our isLiteralPattern logic changes
		// For safety, we'll trust the serialized hint
		r.isLiteral = true
		r.literalStr = regexStr
		r.literalBytes = []byte(regexStr)
	}
	
	return r, nil
}