Skip to content

Commit

Permalink
Refactor stringer (#61)
Browse files Browse the repository at this point in the history
  • Loading branch information
at-wat authored Dec 28, 2019
1 parent 050cb69 commit b40f475
Show file tree
Hide file tree
Showing 3 changed files with 41 additions and 40 deletions.
21 changes: 10 additions & 11 deletions mqtt.go
Original file line number Diff line number Diff line change
Expand Up @@ -84,17 +84,16 @@ const (
StateDisconnected // connection is expectedly closed
)

var connStateString = map[ConnState]string{
StateNew: "New",
StateActive: "Active",
StateClosed: "Closed",
StateDisconnected: "Disconnected",
}

func (s ConnState) String() string {
switch s {
case StateNew:
return "New"
case StateActive:
return "Active"
case StateClosed:
return "Closed"
case StateDisconnected:
return "Disconnected"
default:
return "Unknown"
if str, ok := connStateString[s]; ok {
return str
}
return "Unknown"
}
48 changes: 19 additions & 29 deletions packet.go
Original file line number Diff line number Diff line change
Expand Up @@ -52,36 +52,26 @@ func (t packetType) b() byte {
return byte(t)
}

var packetTypeString = map[packetType]string{
packetConnect: "CONNECT",
packetConnAck: "CONNACK",
packetPublish: "PUBLISH",
packetPubAck: "PUBACK",
packetPubRec: "PUBREC",
packetPubRel: "PUBREL",
packetPubComp: "PUBCOMP",
packetSubscribe: "SUBSCRIBE",
packetSubAck: "SUBACK",
packetUnsubscribe: "UNSUBSCRIBE",
packetUnsubAck: "UNSUBACK",
packetPingReq: "PINGREQ",
packetPingResp: "PINGRESP",
packetDisconnect: "DISCONNECT",
}

func (t packetType) String() string {
switch t {
case packetConnect:
return "CONNECT"
case packetConnAck:
return "CONNACK"
case packetPublish:
return "PUBLISH"
case packetPubAck:
return "PUBACK"
case packetPubRec:
return "PUBREC"
case packetPubRel:
return "PUBREL"
case packetPubComp:
return "PUBCOMP"
case packetSubscribe:
return "SUBSCRIBE"
case packetSubAck:
return "SUBACK"
case packetUnsubscribe:
return "UNSUBSCRIBE"
case packetUnsubAck:
return "UNSUBACK"
case packetPingReq:
return "PINGREQ"
case packetPingResp:
return "PINGRESP"
case packetDisconnect:
return "DISCONNECT"
if s, ok := packetTypeString[t]; ok {
return s
}
return fmt.Sprintf("Unknown packet type %x", int(t))
}
Expand Down
12 changes: 12 additions & 0 deletions packet_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -16,6 +16,7 @@ package mqtt

import (
"bytes"
"strings"
"testing"
)

Expand All @@ -37,3 +38,14 @@ func TestRemainingLength(t *testing.T) {
}
}
}

func TestPacketType(t *testing.T) {
if packetConnect.String() != "CONNECT" {
t.Errorf("Expected packetConnect.String(): CONNECT, got: %s", packetConnect.String())
}
if !strings.HasPrefix(packetType(0xFF).String(), "Unknown") {
t.Errorf("Expected invlidPacketType.String(): Unknown..., got: %s",
packetType(0xFF).String(),
)
}
}

0 comments on commit b40f475

Please sign in to comment.