Skip to content

Commit

Permalink
Use defer and remove ReaderWithEOFContext
Browse files Browse the repository at this point in the history
  • Loading branch information
MarcoPolo committed Mar 10, 2022
1 parent 4343a5f commit 22488b2
Show file tree
Hide file tree
Showing 7 changed files with 139 additions and 134 deletions.
1 change: 0 additions & 1 deletion cbor_cid.go
Original file line number Diff line number Diff line change
Expand Up @@ -13,7 +13,6 @@ func (c CborCid) MarshalCBOR(w io.Writer) error {
}

func (c *CborCid) UnmarshalCBOR(r io.Reader) error {
r = NewReaderWithEOFContext(r)
oc, err := ReadCid(r)
if err != nil {
return err
Expand Down
22 changes: 18 additions & 4 deletions gen.go
Original file line number Diff line number Diff line change
Expand Up @@ -1032,17 +1032,24 @@ func emitCborUnmarshalSliceField(w io.Writer, f Field) error {

func emitCborUnmarshalStructTuple(w io.Writer, gti *GenTypeInfo) error {
err := doTemplate(w, gti, `
func (t *{{ .Name}}) UnmarshalCBOR(r io.Reader) error {
r = cbg.NewReaderWithEOFContext(r)
func (t *{{ .Name}}) UnmarshalCBOR(r io.Reader) (err error) {
*t = {{.Name}}{}
br := cbg.GetPeeker(r)
scratch := make([]byte, 8)
hasReadOnce := false
defer func() {
if err == io.EOF && hasReadOnce {
err = io.ErrUnexpectedEOF
}
}()
maj, extra, err := {{ ReadHeader "br" }}
if err != nil {
return err
}
hasReadOnce = true
if maj != cbg.MajArray {
return fmt.Errorf("cbor input should be of type array")
}
Expand Down Expand Up @@ -1191,17 +1198,24 @@ func emitCborMarshalStructMap(w io.Writer, gti *GenTypeInfo) error {

func emitCborUnmarshalStructMap(w io.Writer, gti *GenTypeInfo) error {
err := doTemplate(w, gti, `
func (t *{{ .Name}}) UnmarshalCBOR(r io.Reader) error {
r = cbg.NewReaderWithEOFContext(r)
func (t *{{ .Name}}) UnmarshalCBOR(r io.Reader) (err error) {
*t = {{.Name}}{}
br := cbg.GetPeeker(r)
scratch := make([]byte, 8)
hasReadOnce := false
defer func() {
if err == io.EOF && hasReadOnce {
err = io.ErrUnexpectedEOF
}
}()
maj, extra, err := {{ ReadHeader "br" }}
if err != nil {
return err
}
hasReadOnce = true
if maj != cbg.MajMap {
return fmt.Errorf("cbor input should be of type map")
}
Expand Down
5 changes: 0 additions & 5 deletions peeker.go
Original file line number Diff line number Diff line change
Expand Up @@ -12,11 +12,6 @@ type BytePeeker interface {
}

func GetPeeker(r io.Reader) BytePeeker {
if r, ok := r.(*ReaderWithEOFContext); ok {
if r, ok := r.R.(BytePeeker); ok {
return r
}
}
if r, ok := r.(BytePeeker); ok {
return r
}
Expand Down
66 changes: 54 additions & 12 deletions testing/cbor_gen.go

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

55 changes: 45 additions & 10 deletions testing/cbor_map_gen.go

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

Loading

0 comments on commit 22488b2

Please sign in to comment.