Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

support for cborgen struct field tags #58

Merged
merged 1 commit into from
Nov 10, 2021
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
12 changes: 10 additions & 2 deletions gen.go
Original file line number Diff line number Diff line change
Expand Up @@ -75,6 +75,7 @@ var _ = sort.Sort

type Field struct {
Name string
MapKey string
Pointer bool
Type reflect.Type
Pkg string
Expand Down Expand Up @@ -194,8 +195,15 @@ func ParseTypeInfo(i interface{}) (*GenTypeInfo, error) {
pointer = true
}

mapk := f.Name
tagval := f.Tag.Get("cborgen")
if tagval != "" {
mapk = tagval
}

out.Fields = append(out.Fields, Field{
Name: f.Name,
MapKey: mapk,
Pointer: pointer,
Type: ft,
Pkg: pkg,
Expand Down Expand Up @@ -1129,7 +1137,7 @@ func emitCborMarshalStructMap(w io.Writer, gti *GenTypeInfo) error {
fmt.Fprintf(w, "\n\t// t.%s (%s) (%s)", f.Name, f.Type, f.Type.Kind())

if err := emitCborMarshalStringField(w, Field{
Name: `"` + f.Name + `"`,
Name: `"` + f.MapKey + `"`,
}); err != nil {
return err
}
Expand Down Expand Up @@ -1224,7 +1232,7 @@ func (t *{{ .Name}}) UnmarshalCBOR(r io.Reader) error {
fmt.Fprintf(w, "// t.%s (%s) (%s)", f.Name, f.Type, f.Type.Kind())

err := doTemplate(w, f, `
case "{{ .Name }}":
case "{{ .MapKey }}":
`)
if err != nil {
return err
Expand Down
1 change: 1 addition & 0 deletions testgen/main.go
Original file line number Diff line number Diff line change
Expand Up @@ -22,6 +22,7 @@ func main() {
types.NeedScratchForMap{},
types.SimpleStructV1{},
types.SimpleStructV2{},
types.RenamedFields{},
); err != nil {
panic(err)
}
Expand Down
137 changes: 137 additions & 0 deletions testing/cbor_map_gen.go

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

17 changes: 11 additions & 6 deletions testing/types.go
Original file line number Diff line number Diff line change
Expand Up @@ -45,12 +45,12 @@ type SimpleTypeTree struct {
}

type SimpleStructV1 struct {
OldStr string
OldBytes []byte
OldNum uint64
OldPtr *cid.Cid
OldMap map[string]SimpleTypeOne
OldArray []SimpleTypeOne
OldStr string
OldBytes []byte
OldNum uint64
OldPtr *cid.Cid
OldMap map[string]SimpleTypeOne
OldArray []SimpleTypeOne
OldStruct SimpleTypeOne
}

Expand Down Expand Up @@ -99,3 +99,8 @@ type ThingWithSomeTime struct {
type NeedScratchForMap struct {
Thing bool
}

type RenamedFields struct {
Foo int64 `cborgen:"foo"`
Bar string `cborgen:"beep"`
}