Skip to content

Commit

Permalink
Merge pull request #128 from rajatjindal/enum-reverse-lookup
Browse files Browse the repository at this point in the history
wit/bindgen: add mapping and String() method for enum type in generated bindings
  • Loading branch information
ydnar authored Jul 7, 2024
2 parents 9753398 + 780eb20 commit 16f9943
Showing 1 changed file with 14 additions and 1 deletion.
15 changes: 14 additions & 1 deletion wit/bindgen/generator.go
Original file line number Diff line number Diff line change
Expand Up @@ -825,7 +825,20 @@ func (g *generator) enumRep(file *gen.File, dir wit.Direction, e *wit.Enum, goNa
}
b.WriteRune('\n')
}
b.WriteString(")\n")
b.WriteString(")\n\n")

stringsName := file.DeclareName("strings" + GoName(goName, true))
stringio.Write(&b, "var ", stringsName, " = [", fmt.Sprintf("%d", len(e.Cases)), "]string {\n")
for _, c := range e.Cases {
stringio.Write(&b, `"`, c.Name, `"`, ",\n")
}

b.WriteString("}\n\n")
b.WriteString(formatDocComments("String implements [fmt.Stringer], returning the enum case name of e.", true))
stringio.Write(&b, "func (e ", goName, ") String() string {\n")
stringio.Write(&b, "return ", stringsName, "[e]\n")
b.WriteString("}\n\n")

return b.String()
}

Expand Down

0 comments on commit 16f9943

Please sign in to comment.