Skip to content

Commit

Permalink
Merge pull request #10 from nokute78/fix_9
Browse files Browse the repository at this point in the history
ignore _ field of struct
  • Loading branch information
nokute78 authored Aug 30, 2020
2 parents a7b69ea + adab8a1 commit 8aa1d31
Show file tree
Hide file tree
Showing 2 changed files with 37 additions and 4 deletions.
21 changes: 17 additions & 4 deletions pkg/bit/v2/decode.go
Original file line number Diff line number Diff line change
Expand Up @@ -18,6 +18,7 @@ package bit

import (
"encoding/binary"
"errors"
"fmt"
"github.com/goccy/go-reflect"
"io"
Expand All @@ -28,6 +29,8 @@ const (
tagKeyName = "bit"
)

var errCannotInterface = errors.New("CanInterface returns false")

// tagConfig represents StructTag.
// "-" : ignore the field
// "skip": ignore but offset will be updated
Expand Down Expand Up @@ -115,6 +118,16 @@ func fillData(b []byte, order binary.ByteOrder, v reflect.Value, o *Offset) erro
var err error
var val reflect.Value

if !v.CanInterface() {
// skip unexported field
var size int
sizeOfValueInBits(&size, v, false)
*o, err = o.AddOffset(Offset{Bit: uint64(size)})
if err != nil {
return err
}
return errCannotInterface
}
d := v.Interface()

switch d.(type) {
Expand Down Expand Up @@ -203,7 +216,7 @@ func fillData(b []byte, order binary.ByteOrder, v reflect.Value, o *Offset) erro
} else {
for i := 0; i < v.Len(); i++ {
err := fillData(b, order, v.Index(i), o)
if err != nil {
if err != nil && err != errCannotInterface {
return err
}
}
Expand All @@ -229,14 +242,14 @@ func fillData(b []byte, order binary.ByteOrder, v reflect.Value, o *Offset) erro
continue
} else if cnf.endian != nil {
err := fillData(b, cnf.endian, v.Field(i), o)
if err != nil {
if err != nil && err != errCannotInterface {
return err
}
continue
}
}
err := fillData(b, order, v.Field(i), o)
if err != nil {
if err != nil && err != errCannotInterface {
return err
}
}
Expand Down Expand Up @@ -281,7 +294,7 @@ func Read(r io.Reader, order binary.ByteOrder, data interface{}) error {
return fmt.Errorf("bit.Read:short read, expect=%d byte, read=%d byte", byteSize, n)
}
err = fillData(barr, order, reflect.Indirect(v), &Offset{})
if err != io.EOF {
if err != io.EOF && err != errCannotInterface {
return err
}
default:
Expand Down
20 changes: 20 additions & 0 deletions pkg/bit/v2/decode_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -339,3 +339,23 @@ func BenchmarkReadStruct(b *testing.B) {
}
}
}

func TestUnexportedField(t *testing.T) {
type S struct {
A [8]bit.Bit
_ [4]bit.Bit
B [4]bit.Bit
}

var s S
buf := bytes.NewBuffer([]byte{0xaa, 0xfb})
if err := bit.Read(buf, binary.LittleEndian, &s); err != nil {
t.Errorf("err=%s", err)
}
for i := 0; i < len(s.B); i++ {
if !s.B[i] {
t.Fatalf("val error: given=%v", s.B)

}
}
}

0 comments on commit 8aa1d31

Please sign in to comment.