Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

handling 0 Packet Identifier in MIDs #147

Merged
merged 2 commits into from
Aug 8, 2023
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
8 changes: 8 additions & 0 deletions paho/message_ids.go
Original file line number Diff line number Diff line change
Expand Up @@ -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]
Expand All @@ -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()
Expand Down
40 changes: 40 additions & 0 deletions paho/message_ids_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -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{}
Expand Down