real_encoder.go 1.8 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100
  1. package sarama
  2. import "encoding/binary"
  3. type realEncoder struct {
  4. raw []byte
  5. off int
  6. stack []pushEncoder
  7. }
  8. // primitives
  9. func (re *realEncoder) putInt8(in int8) {
  10. re.raw[re.off] = byte(in)
  11. re.off += 1
  12. }
  13. func (re *realEncoder) putInt16(in int16) {
  14. binary.BigEndian.PutUint16(re.raw[re.off:], uint16(in))
  15. re.off += 2
  16. }
  17. func (re *realEncoder) putInt32(in int32) {
  18. binary.BigEndian.PutUint32(re.raw[re.off:], uint32(in))
  19. re.off += 4
  20. }
  21. func (re *realEncoder) putInt64(in int64) {
  22. binary.BigEndian.PutUint64(re.raw[re.off:], uint64(in))
  23. re.off += 8
  24. }
  25. func (re *realEncoder) putArrayLength(in int) error {
  26. re.putInt32(int32(in))
  27. return nil
  28. }
  29. // collection
  30. func (re *realEncoder) putRawBytes(in []byte) error {
  31. copy(re.raw[re.off:], in)
  32. re.off += len(in)
  33. return nil
  34. }
  35. func (re *realEncoder) putBytes(in []byte) error {
  36. if in == nil {
  37. re.putInt32(-1)
  38. return nil
  39. }
  40. re.putInt32(int32(len(in)))
  41. copy(re.raw[re.off:], in)
  42. re.off += len(in)
  43. return nil
  44. }
  45. func (re *realEncoder) putString(in string) error {
  46. re.putInt16(int16(len(in)))
  47. copy(re.raw[re.off:], in)
  48. re.off += len(in)
  49. return nil
  50. }
  51. func (re *realEncoder) putInt32Array(in []int32) error {
  52. err := re.putArrayLength(len(in))
  53. if err != nil {
  54. return err
  55. }
  56. for _, val := range in {
  57. re.putInt32(val)
  58. }
  59. return nil
  60. }
  61. func (re *realEncoder) putInt64Array(in []int64) error {
  62. err := re.putArrayLength(len(in))
  63. if err != nil {
  64. return err
  65. }
  66. for _, val := range in {
  67. re.putInt64(val)
  68. }
  69. return nil
  70. }
  71. // stacks
  72. func (re *realEncoder) push(in pushEncoder) {
  73. in.saveOffset(re.off)
  74. re.off += in.reserveLength()
  75. re.stack = append(re.stack, in)
  76. }
  77. func (re *realEncoder) pop() error {
  78. // this is go's ugly pop pattern (the inverse of append)
  79. in := re.stack[len(re.stack)-1]
  80. re.stack = re.stack[:len(re.stack)-1]
  81. return in.run(re.off, re.raw)
  82. }