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() 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{}