prep_encoder.go 2.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121
  1. package sarama
  2. import (
  3. "fmt"
  4. "math"
  5. "github.com/rcrowley/go-metrics"
  6. )
  7. type prepEncoder struct {
  8. length int
  9. }
  10. // primitives
  11. func (pe *prepEncoder) putInt8(in int8) {
  12. pe.length++
  13. }
  14. func (pe *prepEncoder) putInt16(in int16) {
  15. pe.length += 2
  16. }
  17. func (pe *prepEncoder) putInt32(in int32) {
  18. pe.length += 4
  19. }
  20. func (pe *prepEncoder) putInt64(in int64) {
  21. pe.length += 8
  22. }
  23. func (pe *prepEncoder) putArrayLength(in int) error {
  24. if in > math.MaxInt32 {
  25. return PacketEncodingError{fmt.Sprintf("array too long (%d)", in)}
  26. }
  27. pe.length += 4
  28. return nil
  29. }
  30. // arrays
  31. func (pe *prepEncoder) putBytes(in []byte) error {
  32. pe.length += 4
  33. if in == nil {
  34. return nil
  35. }
  36. if len(in) > math.MaxInt32 {
  37. return PacketEncodingError{fmt.Sprintf("byteslice too long (%d)", len(in))}
  38. }
  39. pe.length += len(in)
  40. return nil
  41. }
  42. func (pe *prepEncoder) putRawBytes(in []byte) error {
  43. if len(in) > math.MaxInt32 {
  44. return PacketEncodingError{fmt.Sprintf("byteslice too long (%d)", len(in))}
  45. }
  46. pe.length += len(in)
  47. return nil
  48. }
  49. func (pe *prepEncoder) putString(in string) error {
  50. pe.length += 2
  51. if len(in) > math.MaxInt16 {
  52. return PacketEncodingError{fmt.Sprintf("string too long (%d)", len(in))}
  53. }
  54. pe.length += len(in)
  55. return nil
  56. }
  57. func (pe *prepEncoder) putStringArray(in []string) error {
  58. err := pe.putArrayLength(len(in))
  59. if err != nil {
  60. return err
  61. }
  62. for _, str := range in {
  63. if err := pe.putString(str); err != nil {
  64. return err
  65. }
  66. }
  67. return nil
  68. }
  69. func (pe *prepEncoder) putInt32Array(in []int32) error {
  70. err := pe.putArrayLength(len(in))
  71. if err != nil {
  72. return err
  73. }
  74. pe.length += 4 * len(in)
  75. return nil
  76. }
  77. func (pe *prepEncoder) putInt64Array(in []int64) error {
  78. err := pe.putArrayLength(len(in))
  79. if err != nil {
  80. return err
  81. }
  82. pe.length += 8 * len(in)
  83. return nil
  84. }
  85. func (pe *prepEncoder) offset() int {
  86. return pe.length
  87. }
  88. // stackable
  89. func (pe *prepEncoder) push(in pushEncoder) {
  90. pe.length += in.reserveLength()
  91. }
  92. func (pe *prepEncoder) pop() error {
  93. return nil
  94. }
  95. // we do not record metrics during the prep encoder pass
  96. func (pe *prepEncoder) metricRegistry() metrics.Registry {
  97. return nil
  98. }