message_set.go 1.8 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889
  1. package sarama
  2. type MessageBlock struct {
  3. Offset int64
  4. Msg *Message
  5. }
  6. // Messages convenience helper which returns either all the
  7. // messages that are wrapped in this block
  8. func (msb *MessageBlock) Messages() []*MessageBlock {
  9. if msb.Msg.Set != nil {
  10. return msb.Msg.Set.Messages
  11. }
  12. return []*MessageBlock{msb}
  13. }
  14. func (msb *MessageBlock) encode(pe packetEncoder) error {
  15. pe.putInt64(msb.Offset)
  16. pe.push(&lengthField{})
  17. err := msb.Msg.encode(pe)
  18. if err != nil {
  19. return err
  20. }
  21. return pe.pop()
  22. }
  23. func (msb *MessageBlock) decode(pd packetDecoder) (err error) {
  24. if msb.Offset, err = pd.getInt64(); err != nil {
  25. return err
  26. }
  27. if err = pd.push(&lengthField{}); err != nil {
  28. return err
  29. }
  30. msb.Msg = new(Message)
  31. if err = msb.Msg.decode(pd); err != nil {
  32. return err
  33. }
  34. if err = pd.pop(); err != nil {
  35. return err
  36. }
  37. return nil
  38. }
  39. type MessageSet struct {
  40. PartialTrailingMessage bool // whether the set on the wire contained an incomplete trailing MessageBlock
  41. Messages []*MessageBlock
  42. }
  43. func (ms *MessageSet) encode(pe packetEncoder) error {
  44. for i := range ms.Messages {
  45. err := ms.Messages[i].encode(pe)
  46. if err != nil {
  47. return err
  48. }
  49. }
  50. return nil
  51. }
  52. func (ms *MessageSet) decode(pd packetDecoder) (err error) {
  53. ms.Messages = nil
  54. for pd.remaining() > 0 {
  55. msb := new(MessageBlock)
  56. err = msb.decode(pd)
  57. switch err {
  58. case nil:
  59. ms.Messages = append(ms.Messages, msb)
  60. case ErrInsufficientData:
  61. // As an optimization the server is allowed to return a partial message at the
  62. // end of the message set. Clients should handle this case. So we just ignore such things.
  63. ms.PartialTrailingMessage = true
  64. return nil
  65. default:
  66. return err
  67. }
  68. }
  69. return nil
  70. }
  71. func (ms *MessageSet) addMessage(msg *Message) {
  72. block := new(MessageBlock)
  73. block.Msg = msg
  74. ms.Messages = append(ms.Messages, block)
  75. }