From 6353047ed0548bf112873bdfa082625d532096f7 Mon Sep 17 00:00:00 2001 From: Pavel Gabriel Date: Tue, 25 Jul 2023 11:05:35 +0200 Subject: [PATCH] do not pack fields that represent bitmap indicators --- message.go | 8 +++++++- message_test.go | 41 +++++++++++++++++++++++++++++++++++++++++ 2 files changed, 48 insertions(+), 1 deletion(-) diff --git a/message.go b/message.go index 130a2f5..1ad2f5a 100644 --- a/message.go +++ b/message.go @@ -149,7 +149,8 @@ func (m *Message) pack() ([]byte, error) { for _, id := range ids { // indexes 0 and 1 are for mti and bitmap // regular field number startd from index 2 - if id < 2 { + // do not pack presence bits as well + if id < 2 || m.Bitmap().IsBitmapPresenceBit(id) { continue } m.Bitmap().Set(id) @@ -157,6 +158,11 @@ func (m *Message) pack() ([]byte, error) { // pack fields for _, i := range ids { + // do not pack presence bits other than the first one as it's the bitmap itself + if i != 1 && m.Bitmap().IsBitmapPresenceBit(i) { + continue + } + field, ok := m.fields[i] if !ok { return nil, fmt.Errorf("failed to pack field %d: no specification found", i) diff --git a/message_test.go b/message_test.go index 4ca0a5f..2989d4c 100644 --- a/message_test.go +++ b/message_test.go @@ -71,6 +71,16 @@ func TestMessage(t *testing.T) { Pref: prefix.ASCII.Fixed, Pad: padding.Left('0'), }), + + // this field will be ignored when packing and + // unpacking, as bit 65 is a bitmap presence indicator + 65: field.NewString(&field.Spec{ + Length: 1, + Description: "Settlement Code", + Enc: encoding.ASCII, + Pref: prefix.ASCII.Fixed, + }), + // this is a field of the third bitmap 130: field.NewString(&field.Spec{ Length: 1, Description: "Additional Data", @@ -115,6 +125,37 @@ func TestMessage(t *testing.T) { require.Equal(t, "100", s) }) + t.Run("Do not pack fields that match the bitmap presence indicator", func(t *testing.T) { + message := NewMessage(spec) + message.MTI("0100") + require.NoError(t, message.Field(65, "1")) + require.NoError(t, message.Field(130, "1")) // field of third bitmap + + got, err := message.Pack() + + want := "01008000000000000000800000000000000040000000000000001" + require.NoError(t, err) + require.NotNil(t, got) + require.Equal(t, want, string(got)) + + message = NewMessage(spec) + + err = message.Unpack([]byte(want)) + require.NoError(t, err) + + s, err := message.GetMTI() + require.NoError(t, err) + require.Equal(t, "0100", s) + + s, err = message.GetString(65) + require.NoError(t, err) + require.Equal(t, "", s) + + s, err = message.GetString(130) + require.NoError(t, err) + require.Equal(t, "1", s) + }) + t.Run("Does not fail when packing and unpacking message with three bitmaps", func(t *testing.T) { message := NewMessage(spec) message.MTI("0100")