From 83e90462f43d824d4323243166da0d3da230b761 Mon Sep 17 00:00:00 2001 From: Baicheng Yu Date: Fri, 6 Dec 2024 14:09:29 +0100 Subject: [PATCH] Packer Unpacker: generate length prefix with encoded data --- field/packer_unpacker.go | 2 +- field/packer_unpacker_test.go | 21 +++++++++++++++++++++ 2 files changed, 22 insertions(+), 1 deletion(-) diff --git a/field/packer_unpacker.go b/field/packer_unpacker.go index 35408c8..089718e 100644 --- a/field/packer_unpacker.go +++ b/field/packer_unpacker.go @@ -20,7 +20,7 @@ func (p defaultPacker) Pack(value []byte, spec *Spec) ([]byte, error) { } // encode the length - lengthPrefix, err := spec.Pref.EncodeLength(spec.Length, len(value)) + lengthPrefix, err := spec.Pref.EncodeLength(spec.Length, len(encodedValue)) if err != nil { return nil, fmt.Errorf("failed to encode length: %w", err) } diff --git a/field/packer_unpacker_test.go b/field/packer_unpacker_test.go index 565c8af..2f24e1e 100644 --- a/field/packer_unpacker_test.go +++ b/field/packer_unpacker_test.go @@ -184,3 +184,24 @@ func TestTrack2Packer(t *testing.T) { }) } } + +func TestPackerandUnpackerWithVariantDataLength(t *testing.T) { + spec := &field.Spec{ + Length: 5, + Description: "Field", + Enc: encoding.EBCDIC1047, + Pref: prefix.EBCDIC1047.L, + } + + data := []byte{0xc2, 0xa0, 0x31} + str := field.NewString(spec) + str.SetBytes(data) + + packed, err := str.Pack() + require.NoError(t, err) + require.Equal(t, 0xf2, packed[0]) + + _, err = str.Unpack(packed) + require.NoError(t, err) + require.Equal(t, data, str.Bytes()) +}