record.go 2.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113
  1. package sarama
  2. import (
  3. "encoding/binary"
  4. "time"
  5. )
  6. const (
  7. controlMask = 0x20
  8. maximumRecordOverhead = 5*binary.MaxVarintLen32 + binary.MaxVarintLen64 + 1
  9. )
  10. type RecordHeader struct {
  11. Key []byte
  12. Value []byte
  13. }
  14. func (h *RecordHeader) encode(pe packetEncoder) error {
  15. if err := pe.putVarintBytes(h.Key); err != nil {
  16. return err
  17. }
  18. return pe.putVarintBytes(h.Value)
  19. }
  20. func (h *RecordHeader) decode(pd packetDecoder) (err error) {
  21. if h.Key, err = pd.getVarintBytes(); err != nil {
  22. return err
  23. }
  24. if h.Value, err = pd.getVarintBytes(); err != nil {
  25. return err
  26. }
  27. return nil
  28. }
  29. type Record struct {
  30. Attributes int8
  31. TimestampDelta time.Duration
  32. OffsetDelta int64
  33. Key []byte
  34. Value []byte
  35. Headers []*RecordHeader
  36. length varintLengthField
  37. }
  38. func (r *Record) encode(pe packetEncoder) error {
  39. pe.push(&r.length)
  40. pe.putInt8(r.Attributes)
  41. pe.putVarint(int64(r.TimestampDelta / time.Millisecond))
  42. pe.putVarint(r.OffsetDelta)
  43. if err := pe.putVarintBytes(r.Key); err != nil {
  44. return err
  45. }
  46. if err := pe.putVarintBytes(r.Value); err != nil {
  47. return err
  48. }
  49. pe.putVarint(int64(len(r.Headers)))
  50. for _, h := range r.Headers {
  51. if err := h.encode(pe); err != nil {
  52. return err
  53. }
  54. }
  55. return pe.pop()
  56. }
  57. func (r *Record) decode(pd packetDecoder) (err error) {
  58. if err = pd.push(&r.length); err != nil {
  59. return err
  60. }
  61. if r.Attributes, err = pd.getInt8(); err != nil {
  62. return err
  63. }
  64. timestamp, err := pd.getVarint()
  65. if err != nil {
  66. return err
  67. }
  68. r.TimestampDelta = time.Duration(timestamp) * time.Millisecond
  69. if r.OffsetDelta, err = pd.getVarint(); err != nil {
  70. return err
  71. }
  72. if r.Key, err = pd.getVarintBytes(); err != nil {
  73. return err
  74. }
  75. if r.Value, err = pd.getVarintBytes(); err != nil {
  76. return err
  77. }
  78. numHeaders, err := pd.getVarint()
  79. if err != nil {
  80. return err
  81. }
  82. if numHeaders >= 0 {
  83. r.Headers = make([]*RecordHeader, numHeaders)
  84. }
  85. for i := int64(0); i < numHeaders; i++ {
  86. hdr := new(RecordHeader)
  87. if err := hdr.decode(pd); err != nil {
  88. return err
  89. }
  90. r.Headers[i] = hdr
  91. }
  92. return pd.pop()
  93. }