From d28035fc68d1c66b6aa7e05bf2b997f820dfbdc0 Mon Sep 17 00:00:00 2001 From: Peter Klijn Date: Fri, 28 Oct 2022 10:43:28 +0200 Subject: [PATCH] Fix NPE bugs in sync.Regexp (#143) --- sync/sync.go | 12 ++++++------ sync/sync_test.go | 12 ++++++++++++ 2 files changed, 18 insertions(+), 6 deletions(-) diff --git a/sync/sync.go b/sync/sync.go index c90d79db..f064651a 100644 --- a/sync/sync.go +++ b/sync/sync.go @@ -330,9 +330,7 @@ func (r *Regexp) Set(value *regexp.Regexp) { // MarshalJSON returns the JSON encoding of the value. func (r *Regexp) MarshalJSON() ([]byte, error) { - r.rw.RLock() - defer r.rw.RUnlock() - return json.Marshal(r.value.String()) + return json.Marshal(r.String()) } // UnmarshalJSON returns the JSON encoding of the value. @@ -354,9 +352,11 @@ func (r *Regexp) UnmarshalJSON(d []byte) error { // String returns a string representation of the value. func (r *Regexp) String() string { - r.rw.RLock() - defer r.rw.RUnlock() - return r.value.String() + regex := r.Get() + if regex == nil { + return "" + } + return regex.String() } // diff --git a/sync/sync_test.go b/sync/sync_test.go index bb5a16a3..692f9afd 100644 --- a/sync/sync_test.go +++ b/sync/sync_test.go @@ -267,6 +267,18 @@ func TestRegexp_SetString(t *testing.T) { } } +func TestRegexp_String(t *testing.T) { + sr := Regexp{} + assert.Equal(t, "", sr.String()) +} + +func TestRegexp_MarshalJSON(t *testing.T) { + sr := Regexp{} + json, err := sr.MarshalJSON() + assert.Equal(t, []byte(`""`), json) + assert.NoError(t, err) +} + func TestStringMap(t *testing.T) { var sm StringMap ch := make(chan struct{})