diff options
author | Jonathan Hall <flimzy@flimzy.com> | 2023-03-27 13:23:36 +0200 |
---|---|---|
committer | Gopher Robot <gobot@golang.org> | 2023-04-12 20:03:09 +0000 |
commit | 313ce55a866b20f22ea68d6b4359ebd0c4489ada (patch) | |
tree | 4d4668bc7e8af1989951853dc653e6194697e9ae /src/regexp | |
parent | da2755b4721bc8f0361690401e4436fec2bbe984 (diff) | |
download | go-313ce55a866b20f22ea68d6b4359ebd0c4489ada.tar.gz go-313ce55a866b20f22ea68d6b4359ebd0c4489ada.zip |
regexp: add Regexp.TextMarshaler/TextUnmarshaler
Fixes #46159
Change-Id: I51dc4e9e8915ab5a73f053690fb2395edbeb1151
Reviewed-on: https://go-review.googlesource.com/c/go/+/479401
Run-TryBot: Ian Lance Taylor <iant@golang.org>
TryBot-Result: Gopher Robot <gobot@golang.org>
Reviewed-by: David Chase <drchase@google.com>
Reviewed-by: Ian Lance Taylor <iant@google.com>
Auto-Submit: Ian Lance Taylor <iant@google.com>
Run-TryBot: Ian Lance Taylor <iant@google.com>
Diffstat (limited to 'src/regexp')
-rw-r--r-- | src/regexp/all_test.go | 26 | ||||
-rw-r--r-- | src/regexp/regexp.go | 21 |
2 files changed, 47 insertions, 0 deletions
diff --git a/src/regexp/all_test.go b/src/regexp/all_test.go index 52de3fef83..124313d1af 100644 --- a/src/regexp/all_test.go +++ b/src/regexp/all_test.go @@ -947,3 +947,29 @@ func TestMinInputLen(t *testing.T) { } } } + +func TestUnmarshalText(t *testing.T) { + unmarshaled := new(Regexp) + for i := range goodRe { + re := compileTest(t, goodRe[i], "") + marshaled, err := re.MarshalText() + if err != nil { + t.Errorf("regexp %#q failed to marshal: %s", re, err) + continue + } + if err := unmarshaled.UnmarshalText(marshaled); err != nil { + t.Errorf("regexp %#q failed to unmarshal: %s", re, err) + continue + } + if unmarshaled.String() != goodRe[i] { + t.Errorf("UnmarshalText returned unexpected value: %s", unmarshaled.String()) + } + } + t.Run("invalid pattern", func(t *testing.T) { + re := new(Regexp) + err := re.UnmarshalText([]byte(`\`)) + if err == nil { + t.Error("unexpected success") + } + }) +} diff --git a/src/regexp/regexp.go b/src/regexp/regexp.go index 990c06e891..82023868ec 100644 --- a/src/regexp/regexp.go +++ b/src/regexp/regexp.go @@ -1283,3 +1283,24 @@ func (re *Regexp) Split(s string, n int) []string { return strings } + +// MarshalText implements the encoding.TextMarshaler interface. The output +// matches that of calling the [Regexp.String] method. +// +// Note that the output is lossy in some cases: This method does not indicate +// POSIX regular expressions (i.e. those compiled by calling CompilePOSIX), or +// those for which the [Regexp.Longest] method has been called. +func (re *Regexp) MarshalText() ([]byte, error) { + return []byte(re.String()), nil +} + +// MarshalText implements the encoding.TextUnmarshaler interface by calling +// Compile on the encoded value. +func (re *Regexp) UnmarshalText(text []byte) error { + newRE, err := Compile(string(text)) + if err != nil { + return err + } + *re = *newRE + return nil +} |