Skip to content

Commit

Permalink
Added parsing of values from inner fields of the structure. Close #7
Browse files Browse the repository at this point in the history
  • Loading branch information
ghostiam committed Apr 3, 2024
1 parent 54308c8 commit 82103a4
Show file tree
Hide file tree
Showing 2 changed files with 28 additions and 2 deletions.
16 changes: 16 additions & 0 deletions binstruct_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -901,3 +901,19 @@ func Test_sliceSkipWithoutPanic(t *testing.T) {
require.NoError(t, err)
require.Equal(t, int32(0x02030405), v.I)
}

func Test_InnerSubField(t *testing.T) {
type child struct {
Len int8
}

var v struct {
Child child
S []byte `bin:"len:Child.Len"`
}

err := UnmarshalBE([]byte{0x05, 0x01, 0x02, 0x03, 0x04, 0x05}, &v)
require.NoError(t, err)
require.Equal(t, int8(5), v.Child.Len)
require.Equal(t, []byte{0x01, 0x02, 0x03, 0x04, 0x05}, v.S)
}
14 changes: 12 additions & 2 deletions tag.go
Original file line number Diff line number Diff line change
Expand Up @@ -198,14 +198,24 @@ func parseValue(structValue reflect.Value, v string) (int64, error) {
// parse value or get from field
l, err := strconv.ParseInt(v, 10, 0)
if err != nil {
lenVal := structValue.FieldByName(v)
sv := structValue

split := strings.Split(v, ".")
for _, s := range split {
sv = sv.FieldByName(s)
if sv.Kind() != reflect.Struct {
break
}
}

lenVal := sv
switch lenVal.Kind() {
case reflect.Int, reflect.Int8, reflect.Int16, reflect.Int32, reflect.Int64:
l = lenVal.Int()
case reflect.Uint, reflect.Uint8, reflect.Uint16, reflect.Uint32, reflect.Uint64, reflect.Uintptr:
l = int64(lenVal.Uint())
default:
return 0, errors.New("can't get field len from " + v + " field")
return 0, errors.New("can't get field len from \"" + v + "\" field")
}
}
return l, nil
Expand Down

0 comments on commit 82103a4

Please sign in to comment.