Skip to content

Commit

Permalink
regexp: add Regexp.TextMarshaler/TextUnmarshaler
Browse files Browse the repository at this point in the history
Fixes golang#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>
  • Loading branch information
flimzy authored and gopherbot committed Apr 12, 2023
1 parent da2755b commit 313ce55
Show file tree
Hide file tree
Showing 3 changed files with 49 additions and 0 deletions.
2 changes: 2 additions & 0 deletions api/next/46159.txt
Original file line number Diff line number Diff line change
@@ -0,0 +1,2 @@
pkg regexp, method (*Regexp) MarshalText() ([]uint8, error) #46159
pkg regexp, method (*Regexp) UnmarshalText([]uint8) error #46159
26 changes: 26 additions & 0 deletions src/regexp/all_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -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")
}
})
}
21 changes: 21 additions & 0 deletions src/regexp/regexp.go
Original file line number Diff line number Diff line change
Expand Up @@ -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
}

0 comments on commit 313ce55

Please sign in to comment.