Skip to content

Commit

Permalink
Add a mechanism to allow converting from a raw string to an enum type. (
Browse files Browse the repository at this point in the history
  • Loading branch information
MrJoy authored and actgardner committed Nov 21, 2019
1 parent 71c0d46 commit 0bf463c
Show file tree
Hide file tree
Showing 3 changed files with 26 additions and 0 deletions.
4 changes: 4 additions & 0 deletions schema/enum.go
Original file line number Diff line number Diff line change
Expand Up @@ -64,6 +64,10 @@ func (e *EnumDefinition) SerializerMethod() string {
return "write" + e.GoType()
}

func (e *EnumDefinition) FromStringMethod() string {
return "New" + e.GoType() + "Value"
}

func (e *EnumDefinition) filename() string {
return generator.ToSnake(e.GoType()) + ".go"
}
Expand Down
12 changes: 12 additions & 0 deletions schema/templates/enum.go
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,7 @@ package templates

const EnumTemplate = `
import (
"fmt"
"io"
"github.com/actgardner/gogen-avro/vm"
Expand Down Expand Up @@ -31,4 +32,15 @@ func (e {{ .GoType }}) String() string {
func {{ .SerializerMethod }}(r {{ .GoType }}, w io.Writer) error {
return vm.WriteInt(int32(r), w)
}
func {{ .FromStringMethod }}(raw string) (r {{ .GoType }}, err error) {
switch raw {
{{ range $i, $symbol := .Symbols }}
case {{ printf "%q" $symbol }}:
return {{ $.SymbolName $symbol }}, nil
{{ end }}
}
return -1, fmt.Errorf("invalid value for {{ $.GoType }}: '%s'", raw)
}
`
10 changes: 10 additions & 0 deletions test/enum/schema_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -47,6 +47,10 @@ func TestEnumFixture(t *testing.T) {
recordVal, ok := record["EnumField"]
assert.Equal(t, true, ok)
assert.Equal(t, recordVal, f.EnumField.String())

enumified, err := NewTestEnumTypeValue(f.EnumField.String())
assert.Nil(t, err)
assert.Equal(t, f.EnumField, enumified)
}
}

Expand All @@ -66,3 +70,9 @@ func TestRoundTrip(t *testing.T) {
assert.Equal(t, *datum, f)
}
}

func TestInvalidStringConversion(t *testing.T) {
enumified, err := NewTestEnumTypeValue("bogus")
assert.Error(t, err)
assert.Equal(t, TestEnumType(-1), enumified)
}

0 comments on commit 0bf463c

Please sign in to comment.