From 848a7a7e41ad493e5a4aeb168b3c36c4ec1b3177 Mon Sep 17 00:00:00 2001 From: Daichi Tomaru Date: Thu, 27 Jul 2023 23:00:58 +0900 Subject: [PATCH 1/2] handling 0 Packet Identifier in MIDs --- paho/message_ids.go | 8 ++++++++ 1 file changed, 8 insertions(+) diff --git a/paho/message_ids.go b/paho/message_ids.go index 49792a4..ad287b5 100644 --- a/paho/message_ids.go +++ b/paho/message_ids.go @@ -82,6 +82,10 @@ func (m *MIDs) Request(c *CPContext) (uint16, error) { // Get is the library provided MIDService's implementation of // the required interface function() func (m *MIDs) Get(i uint16) *CPContext { + // 0 Packet Identifier is invalid but just in case handled with returning nil to avoid panic. + if i == 0 { + return nil + } m.Lock() defer m.Unlock() return m.index[i-1] @@ -90,6 +94,10 @@ func (m *MIDs) Get(i uint16) *CPContext { // Free is the library provided MIDService's implementation of // the required interface function() func (m *MIDs) Free(i uint16) { + // 0 Packet Identifier is invalid but just in case handled to avoid panic. + if i == 0 { + return + } m.Lock() m.index[i-1] = nil m.Unlock() From 22afd860c96d4ec335de3a6d1ac36d5b96be55e3 Mon Sep 17 00:00:00 2001 From: Daichi Tomaru Date: Sun, 30 Jul 2023 12:29:09 +0900 Subject: [PATCH 2/2] Add test for MIDs.Get() and Free() --- paho/message_ids_test.go | 40 ++++++++++++++++++++++++++++++++++++++++ 1 file changed, 40 insertions(+) diff --git a/paho/message_ids_test.go b/paho/message_ids_test.go index a499d91..3bd8166 100644 --- a/paho/message_ids_test.go +++ b/paho/message_ids_test.go @@ -121,6 +121,46 @@ func TestUsingFullBandOfMID(t *testing.T){ } } +func TestMIDsGetAllIDs(t *testing.T) { + m := &MIDs{index: make([]*CPContext, midMax)} + for i := uint16(0); i < midMax; i++ { + cp := &CPContext{} + m.index[i] = cp + } + + for i := uint16(0); i < midMax; i++ { + assert.NotNil(t, m.Get(i+1)) + } +} + +// Expecting MIDs.Get(0) returns always nil, because 0 identifier is invalid and cannot be retained in MIDs. +func TestMIDsGetZeroID(t *testing.T) { + m := &MIDs{index: make([]*CPContext, midMax)} + assert.NotPanics(t, func(){ m.Get(0) }) +} + +func TestMIDsFreeAllIDs(t *testing.T) { + m := &MIDs{index: make([]*CPContext, midMax)} + for i := uint16(0); i < midMax; i++ { + cp := &CPContext{} + m.index[i] = cp + } + + for i := uint16(0); i < midMax; i++ { + m.Free(i+1) + } + + for i := uint16(0); i < midMax; i++ { + assert.Nil(t, m.index[i]) + } +} + +// Expecting MIDs.Free(0) always do nothing (no panic), because 0 identifier is invalid and ignored. +func TestMIDsFreeZeroID(t *testing.T) { + m := &MIDs{index: make([]*CPContext, midMax)} + assert.NotPanics(t, func(){ m.Free(0) }) +} + func BenchmarkRequestMID(b *testing.B) { m := &MIDs{index: make([]*CPContext, 65535)} cp := &CPContext{}