You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

73 lines
1.8 KiB

  1. package packet
  2. import (
  3. "bytes"
  4. "io"
  5. )
  6. // base holds the fields and methods which are common
  7. // among the MQTT Control Packets.
  8. type base struct {
  9. // fixedHeader represents the fixed header of the Packet.
  10. fixedHeader FixedHeader
  11. // VariableHeader represents the variable header of the Packet.
  12. variableHeader []byte
  13. // Payload represents the payload of the Packet.
  14. payload []byte
  15. }
  16. // WriteTo writes the Packet data to the writer.
  17. func (b *base) WriteTo(w io.Writer) (int64, error) {
  18. // Create a byte buffer.
  19. var bf bytes.Buffer
  20. // Write the Packet data to the buffer.
  21. bf.Write(b.fixedHeader)
  22. bf.Write(b.variableHeader)
  23. bf.Write(b.payload)
  24. // Write the buffered data to the writer.
  25. n, err := w.Write(bf.Bytes())
  26. // Return the result.
  27. return int64(n), err
  28. }
  29. // Type extracts the MQTT Control Packet type from
  30. // the fixed header and returns it.
  31. func (b *base) Type() (byte, error) {
  32. return b.fixedHeader.ptype()
  33. }
  34. // appendRemainingLength appends the Remaining Length
  35. // to the fixed header.
  36. func (b *base) appendRemainingLength() {
  37. // Calculate and encode the Remaining Length.
  38. rl := encodeLength(uint32(len(b.variableHeader) + len(b.payload)))
  39. // Append the Remaining Length to the fixed header.
  40. b.fixedHeader = appendRemainingLength(b.fixedHeader, rl)
  41. }
  42. // appendRemainingLength appends the Remaining Length
  43. // to the slice and returns it.
  44. func appendRemainingLength(b []byte, rl uint32) []byte {
  45. // Append the Remaining Length to the slice.
  46. switch {
  47. case rl&0xFF000000 > 0:
  48. b = append(b, byte((rl&0xFF000000)>>24))
  49. fallthrough
  50. case rl&0x00FF0000 > 0:
  51. b = append(b, byte((rl&0x00FF0000)>>16))
  52. fallthrough
  53. case rl&0x0000FF00 > 0:
  54. b = append(b, byte((rl&0x0000FF00)>>8))
  55. fallthrough
  56. default:
  57. b = append(b, byte(rl&0x000000FF))
  58. }
  59. // Return the slice.
  60. return b
  61. }