payload.go 1.3 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243
  1. package mqtt
  2. import (
  3. "bytes"
  4. "io"
  5. )
  6. // Payload is the interface for Publish payloads. Typically the BytesPayload
  7. // implementation will be sufficient for small payloads whose full contents
  8. // will exist in memory. However, other implementations can read or write
  9. // payloads requiring them holding their complete contents in memory.
  10. type Payload interface {
  11. // Size returns the number of bytes that WritePayload will write.
  12. Size() int
  13. // WritePayload writes the payload data to w. Implementations must write
  14. // Size() bytes of data, but it is *not* required to do so prior to
  15. // returning. Size() bytes must have been written to w prior to another
  16. // message being encoded to the underlying connection.
  17. WritePayload(b *bytes.Buffer) error
  18. // ReadPayload reads the payload data from r (r will EOF at the end of the
  19. // payload). It is *not* required for r to have been consumed prior to this
  20. // returning. r must have been consumed completely prior to another message
  21. // being decoded from the underlying connection.
  22. ReadPayload(r io.Reader, n int) error
  23. }
  24. type BytesPayload []byte
  25. func (p BytesPayload) Size() int {
  26. return len(p)
  27. }
  28. func (p BytesPayload) WritePayload(b *bytes.Buffer) error {
  29. _, err := b.Write(p)
  30. return err
  31. }
  32. func (p BytesPayload) ReadPayload(r io.Reader, n int) error {
  33. _, err := io.ReadFull(r, p)
  34. return err
  35. }