File tree 3 files changed +49
-0
lines changed
3 files changed +49
-0
lines changed Original file line number Diff line number Diff line change
1
+ pkg regexp, method (*Regexp) MarshalText() ([]uint8, error) #46159
2
+ pkg regexp, method (*Regexp) UnmarshalText([]uint8) error #46159
Original file line number Diff line number Diff line change @@ -947,3 +947,29 @@ func TestMinInputLen(t *testing.T) {
947
947
}
948
948
}
949
949
}
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
+ }
Original file line number Diff line number Diff line change @@ -1283,3 +1283,24 @@ func (re *Regexp) Split(s string, n int) []string {
1283
1283
1284
1284
return strings
1285
1285
}
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
+ }
You can’t perform that action at this time.
0 commit comments