Skip to content

Commit 313ce55

Browse files
flimzygopherbot
authored andcommitted
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 <[email protected]> TryBot-Result: Gopher Robot <[email protected]> Reviewed-by: David Chase <[email protected]> Reviewed-by: Ian Lance Taylor <[email protected]> Auto-Submit: Ian Lance Taylor <[email protected]> Run-TryBot: Ian Lance Taylor <[email protected]>
1 parent da2755b commit 313ce55

File tree

3 files changed

+49
-0
lines changed

3 files changed

+49
-0
lines changed

api/next/46159.txt

+2
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,2 @@
1+
pkg regexp, method (*Regexp) MarshalText() ([]uint8, error) #46159
2+
pkg regexp, method (*Regexp) UnmarshalText([]uint8) error #46159

src/regexp/all_test.go

+26
Original file line numberDiff line numberDiff line change
@@ -947,3 +947,29 @@ func TestMinInputLen(t *testing.T) {
947947
}
948948
}
949949
}
950+
951+
func TestUnmarshalText(t *testing.T) {
952+
unmarshaled := new(Regexp)
953+
for i := range goodRe {
954+
re := compileTest(t, goodRe[i], "")
955+
marshaled, err := re.MarshalText()
956+
if err != nil {
957+
t.Errorf("regexp %#q failed to marshal: %s", re, err)
958+
continue
959+
}
960+
if err := unmarshaled.UnmarshalText(marshaled); err != nil {
961+
t.Errorf("regexp %#q failed to unmarshal: %s", re, err)
962+
continue
963+
}
964+
if unmarshaled.String() != goodRe[i] {
965+
t.Errorf("UnmarshalText returned unexpected value: %s", unmarshaled.String())
966+
}
967+
}
968+
t.Run("invalid pattern", func(t *testing.T) {
969+
re := new(Regexp)
970+
err := re.UnmarshalText([]byte(`\`))
971+
if err == nil {
972+
t.Error("unexpected success")
973+
}
974+
})
975+
}

src/regexp/regexp.go

+21
Original file line numberDiff line numberDiff line change
@@ -1283,3 +1283,24 @@ func (re *Regexp) Split(s string, n int) []string {
12831283

12841284
return strings
12851285
}
1286+
1287+
// MarshalText implements the encoding.TextMarshaler interface. The output
1288+
// matches that of calling the [Regexp.String] method.
1289+
//
1290+
// Note that the output is lossy in some cases: This method does not indicate
1291+
// POSIX regular expressions (i.e. those compiled by calling CompilePOSIX), or
1292+
// those for which the [Regexp.Longest] method has been called.
1293+
func (re *Regexp) MarshalText() ([]byte, error) {
1294+
return []byte(re.String()), nil
1295+
}
1296+
1297+
// MarshalText implements the encoding.TextUnmarshaler interface by calling
1298+
// Compile on the encoded value.
1299+
func (re *Regexp) UnmarshalText(text []byte) error {
1300+
newRE, err := Compile(string(text))
1301+
if err != nil {
1302+
return err
1303+
}
1304+
*re = *newRE
1305+
return nil
1306+
}

0 commit comments

Comments
 (0)