Skip to content

Commit cba3eee

Browse files
authored
fix: capture field count early for "optional" length check (#112)
1 parent 2e0074a commit cba3eee

File tree

4 files changed

+28
-40
lines changed

4 files changed

+28
-40
lines changed

gen.go

Lines changed: 3 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1623,6 +1623,8 @@ func (t *{{ .Name}}) UnmarshalCBOR(r io.Reader) (err error) {
16231623
if extra < {{ .MandatoryFieldCount }} {
16241624
return fmt.Errorf("cbor input has too few fields %d < {{ .MandatoryFieldCount }}", extra)
16251625
}
1626+
1627+
fieldCount := extra
16261628
{{ end }}
16271629
16281630
`)
@@ -1641,7 +1643,7 @@ func (t *{{ .Name}}) UnmarshalCBOR(r io.Reader) (err error) {
16411643
fmt.Fprintf(w, "\t// %s (%s) (%s)\n", f.Name, f.Type, f.Type.Kind())
16421644

16431645
if f.Optional {
1644-
fmt.Fprintf(w, "\tif extra < %d {\n\t\treturn nil\n\t}\n", fieldIndex+1)
1646+
fmt.Fprintf(w, "\tif fieldCount < %d {\n\t\treturn nil\n\t}\n", fieldIndex+1)
16451647
}
16461648

16471649
switch f.Type.Kind() {

testing/cbor_gen.go

Lines changed: 15 additions & 29 deletions
Some generated files are not rendered by default. Learn more about customizing how changed files appear on GitHub.

testing/optional_test.go

Lines changed: 6 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -22,10 +22,10 @@ func TestOptionalFields(t *testing.T) {
2222
// Pre-fill with garbage. We want optional fields to be reset to their
2323
// defaults.
2424
out := TupleWithOptionalFields{
25-
Int1: 0xf1,
26-
Int2: 0xf2,
27-
Int3: 0xf3,
28-
Int4: 0xf4,
25+
Int1: 0xf1,
26+
Uint2: 0xf2,
27+
Int3: 0xf3,
28+
Int4: 0xf4,
2929
}
3030
err := out.UnmarshalCBOR(&buf)
3131
switch count {
@@ -40,8 +40,8 @@ func TestOptionalFields(t *testing.T) {
4040
}
4141
fallthrough
4242
case 2:
43-
if out.Int2 != ints[1] {
44-
t.Errorf("field 2 should be %d, was %d", ints[1], out.Int2)
43+
if out.Uint2 != uint64(ints[1]) {
44+
t.Errorf("field 2 should be %d, was %d", ints[1], out.Uint2)
4545
}
4646
if out.Int1 != ints[0] {
4747
t.Errorf("field 1 should be %d, was %d", ints[0], out.Int1)

testing/types.go

Lines changed: 4 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -212,8 +212,8 @@ type StringPtrSlices struct {
212212
}
213213

214214
type TupleWithOptionalFields struct {
215-
Int1 int64
216-
Int2 int64
217-
Int3 int64 `cborgen:"optional"`
218-
Int4 int64 `cborgen:"optional"`
215+
Int1 int64
216+
Uint2 uint64
217+
Int3 int64 `cborgen:"optional"`
218+
Int4 int64 `cborgen:"optional"`
219219
}

0 commit comments

Comments
 (0)