Skip to content

Commit

Permalink
kmsg: add TextMarshaler/TextUnmarshaler to enums
Browse files Browse the repository at this point in the history
  • Loading branch information
twmb committed Mar 10, 2022
1 parent a8d2d7b commit 806cf53
Show file tree
Hide file tree
Showing 3 changed files with 150 additions and 0 deletions.
16 changes: 16 additions & 0 deletions generate/gen.go
Original file line number Diff line number Diff line change
Expand Up @@ -799,6 +799,22 @@ func (e Enum) WriteParseFunc(l *LineWriter) {
l.Write("}")
}

func (e Enum) WriteUnmarshalTextFunc(l *LineWriter) {
l.Write("// UnmarshalText implements encoding.TextUnmarshaler.")
l.Write("func (e *%s) UnmarshalText(text []byte) error {", e.Name)
l.Write("v, err := Parse%s(string(text))", e.Name)
l.Write("*e = v")
l.Write("return err")
l.Write("}")
}

func (e Enum) WriteMarshalTextFunc(l *LineWriter) {
l.Write("// MarshalText implements encoding.TextMarshaler.")
l.Write("func (e %s) MarshalText() (text []byte, err error) {", e.Name)
l.Write("return []byte(e.String()), nil")
l.Write("}")
}

func strnorm(s string) string {
s = strings.ReplaceAll(s, ".", "")
s = strings.ReplaceAll(s, "_", "")
Expand Down
2 changes: 2 additions & 0 deletions generate/main.go
Original file line number Diff line number Diff line change
Expand Up @@ -529,6 +529,8 @@ func main() {
e.WriteStringsFunc(l)
e.WriteParseFunc(l)
e.WriteConsts(l)
e.WriteMarshalTextFunc(l)
e.WriteUnmarshalTextFunc(l)
}

writeStrnorm(l)
Expand Down
132 changes: 132 additions & 0 deletions pkg/kmsg/generated.go

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

0 comments on commit 806cf53

Please sign in to comment.