]> Cypherpunks.ru repositories - gostls13.git/blobdiff - src/regexp/regexp.go
regexp: add Regexp.TextMarshaler/TextUnmarshaler
[gostls13.git] / src / regexp / regexp.go
index 990c06e89132b00771aa563067be464e4ea38878..82023868ec125af59d0eb5e13e9e7b28be15aa5c 100644 (file)
@@ -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
+}