From 668df8b70a0eda2bac238819bcfed808ec44d581 Mon Sep 17 00:00:00 2001 From: Aadhavan Srinivasan Date: Mon, 10 Feb 2025 12:30:48 -0500 Subject: [PATCH] Wrote MarshalText() and UnmarshalText() to implement TextMarshaler and TextUnmarshaler --- regex/compile.go | 16 ++++++++++++++++ 1 file changed, 16 insertions(+) diff --git a/regex/compile.go b/regex/compile.go index d9bef70..0ae3d6b 100644 --- a/regex/compile.go +++ b/regex/compile.go @@ -31,6 +31,22 @@ func (re Reg) String() string { return re.str } +// MarshalText implements [encoding.TextMarshaler]. The output is equivalent to that of [Reg.String]. +// Any flags passed as arguments (including calling [Reg.Longest]) are lost. +func (re *Reg) MarshalText() ([]byte, error) { + return []byte(re.String()), nil +} + +// UnmarshalText implements [encoding.TextUnmarshaler]. It calls [Reg.Compile] on the given byte-slice. If it returns successfully, +// then the result of the compilation is stored in re. The result of [Reg.Compile] is returned. +func (re *Reg) UnmarshalText(text []byte) error { + newReg, err := Compile(string(text)) + if err == nil { + *re = newReg + } + return err +} + func (re *Reg) Longest() { re.preferLongest = true }