Ensure manipulating the returned FastRegexMatcher.SetMatches() doesn't pollute the matcher's internal state

Signed-off-by: Marco Pracucci <marco@pracucci.com>
This commit is contained in:
Marco Pracucci 2023-12-07 11:34:45 +01:00
parent e239c5eda5
commit 986ca1a16a
No known key found for this signature in database
GPG key ID: 74C1BD403D2DF9B5
2 changed files with 21 additions and 1 deletions

View file

@ -339,7 +339,13 @@ func (m *FastRegexMatcher) MatchString(s string) bool {
}
func (m *FastRegexMatcher) SetMatches() []string {
return m.setMatches
// IMPORTANT: always return a copy, otherwise if the caller manipulate this slice it will
// also get manipulated in the cached FastRegexMatcher instance.
ret := make([]string, 0, len(m.setMatches))
for _, value := range m.setMatches {
ret = append(ret, value)
}
return ret
}
func (m *FastRegexMatcher) GetRegexString() string {

View file

@ -344,6 +344,20 @@ func TestFindSetMatches(t *testing.T) {
}
}
func TestFastRegexMatcher_SetMatches_ShouldReturnACopy(t *testing.T) {
m, err := newFastRegexMatcherWithoutCache("a|b")
require.NoError(t, err)
require.Equal(t, []string{"a", "b"}, m.SetMatches())
// Manipulate the returned slice.
matches := m.SetMatches()
matches[0] = "xxx"
matches[1] = "yyy"
// Ensure that if we call SetMatches() again we get the original one.
require.Equal(t, []string{"a", "b"}, m.SetMatches())
}
func BenchmarkFastRegexMatcher(b *testing.B) {
texts := generateRandomValues()