Skip to content
This repository has been archived by the owner on Jan 3, 2023. It is now read-only.

Commit

Permalink
support fixed length strings
Browse files Browse the repository at this point in the history
  • Loading branch information
the729 committed Dec 15, 2019
1 parent 5c35bbf commit 78712d4
Show file tree
Hide file tree
Showing 3 changed files with 18 additions and 5 deletions.
19 changes: 16 additions & 3 deletions codec_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -252,32 +252,45 @@ func TestBasicStruct(t *testing.T) {

func TestStructWithFixedLenMember(t *testing.T) {
type MyStruct struct {
Str string `lcs:"len=2"`
Bytes []byte `lcs:"len=4"`
OptionalBytes []byte `lcs:"len=4,optional"`
}

runTest(t, []*testCase{
{
v: MyStruct{
Str: "12",
Bytes: []byte{0x11, 0x22},
},
errMarshal: errors.New("actual len not equal to fixed len"),
name: "struct with wrong fixed len",
name: "struct with wrong fixed len (bytes)",
skipUnmarshal: true,
},
{
v: MyStruct{
Str: "",
Bytes: []byte{0x11, 0x22, 0x33, 0x44},
},
b: hexMustDecode("11223344 00"),
errMarshal: errors.New("actual len not equal to fixed len"),
name: "struct with wrong fixed len (string)",
skipUnmarshal: true,
},
{
v: MyStruct{
Str: "12",
Bytes: []byte{0x11, 0x22, 0x33, 0x44},
},
b: hexMustDecode("31 32 11223344 00"),
name: "struct with fixed len",
},
{
v: MyStruct{
Str: "12",
Bytes: []byte{0x11, 0x22, 0x33, 0x44},
OptionalBytes: []byte{0x55, 0x66, 0x77, 0x88},
},
b: hexMustDecode("11223344 01 55667788"),
b: hexMustDecode("3132 11223344 01 55667788"),
name: "struct with optional fixed len",
},
})
Expand Down
2 changes: 1 addition & 1 deletion decode.go
Original file line number Diff line number Diff line change
Expand Up @@ -285,7 +285,7 @@ func (d *Decoder) decodeStruct(rv reflect.Value) (err error) {
}
}
fixedLen := 0
if fixedLenStr, ok := tag["len"]; ok && fv.Kind() == reflect.Slice {
if fixedLenStr, ok := tag["len"]; ok && (fv.Kind() == reflect.Slice || fv.Kind() == reflect.String) {
fixedLen, err = strconv.Atoi(fixedLenStr)
if err != nil {
return errors.New("tag len parse error: " + err.Error())
Expand Down
2 changes: 1 addition & 1 deletion encode.go
Original file line number Diff line number Diff line change
Expand Up @@ -137,7 +137,7 @@ func (e *Encoder) encodeStruct(rv reflect.Value) (err error) {
}
}
fixedLen := 0
if fixedLenStr, ok := tag["len"]; ok && fv.Kind() == reflect.Slice {
if fixedLenStr, ok := tag["len"]; ok && (fv.Kind() == reflect.Slice || fv.Kind() == reflect.String) {
fixedLen, err = strconv.Atoi(fixedLenStr)
if err != nil {
return errors.New("tag len parse error: " + err.Error())
Expand Down

0 comments on commit 78712d4

Please sign in to comment.