Skip to content

Commit

Permalink
Merge pull request #29 from Stebalien/fix/byte-array
Browse files Browse the repository at this point in the history
Fix encoding/decoding fixed byte arrays
  • Loading branch information
Jakub Sztandera committed Jul 20, 2020
2 parents 227fab5 + 2eeee43 commit 13e2891
Show file tree
Hide file tree
Showing 6 changed files with 205 additions and 12 deletions.
17 changes: 14 additions & 3 deletions gen.go
Original file line number Diff line number Diff line change
Expand Up @@ -369,6 +369,7 @@ func emitCborMarshalSliceField(w io.Writer, f Field) error {
}
e := f.Type.Elem()

// Note: this re-slices the slice to deal with arrays.
if e.Kind() == reflect.Uint8 {
return doTemplate(w, f, `
if len({{ .Name }}) > cbg.ByteArrayMaxLen {
Expand All @@ -377,7 +378,7 @@ func emitCborMarshalSliceField(w io.Writer, f Field) error {
{{ MajorType "w" "cbg.MajByteString" (print "len(" .Name ")" ) }}
if _, err := w.Write({{ .Name }}); err != nil {
if _, err := w.Write({{ .Name }}[:]); err != nil {
return err
}
`)
Expand Down Expand Up @@ -858,8 +859,18 @@ func emitCborUnmarshalSliceField(w io.Writer, f Field) error {
if maj != cbg.MajByteString {
return fmt.Errorf("expected byte array")
}
{{ .Name }} = make([]byte, extra)
if _, err := io.ReadFull(br, {{ .Name }}); err != nil {
{{if .IsArray}}
if extra != {{ .Len }} {
return fmt.Errorf("expected array to have {{ .Len }} elements")
}
{{ .Name }} = {{ .TypeName }}{}
{{else}}
if extra > 0 {
{{ .Name }} = make({{ .TypeName }}, extra)
}
{{end}}
if _, err := io.ReadFull(br, {{ .Name }}[:]); 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 @@ -11,6 +11,7 @@ func main() {
types.SimpleTypeOne{},
types.SimpleTypeTwo{},
types.DeferredContainer{},
types.FixedArrays{},
); err != nil {
panic(err)
}
Expand Down
177 changes: 171 additions & 6 deletions testing/cbor_gen.go

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

10 changes: 7 additions & 3 deletions testing/cbor_map_gen.go

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

6 changes: 6 additions & 0 deletions testing/roundtrip_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -105,3 +105,9 @@ func TestNilValueDeferredUnmarshaling(t *testing.T) {
t.Fatal("shouldnt be nil!")
}
}

func TestFixedArrays(t *testing.T) {
zero := &FixedArrays{}
recepticle := &FixedArrays{}
testValueRoundtrip(t, zero, recepticle)
}
6 changes: 6 additions & 0 deletions testing/types.go
Original file line number Diff line number Diff line change
Expand Up @@ -46,3 +46,9 @@ type DeferredContainer struct {
Deferred *cbg.Deferred
Value uint64
}

type FixedArrays struct {
Bytes [20]byte
Uint8 [20]uint8
Uint64 [20]uint64
}

0 comments on commit 13e2891

Please sign in to comment.