length_field.go 1.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869
  1. package sarama
  2. import "encoding/binary"
  3. // LengthField implements the PushEncoder and PushDecoder interfaces for calculating 4-byte lengths.
  4. type lengthField struct {
  5. startOffset int
  6. }
  7. func (l *lengthField) saveOffset(in int) {
  8. l.startOffset = in
  9. }
  10. func (l *lengthField) reserveLength() int {
  11. return 4
  12. }
  13. func (l *lengthField) run(curOffset int, buf []byte) error {
  14. binary.BigEndian.PutUint32(buf[l.startOffset:], uint32(curOffset-l.startOffset-4))
  15. return nil
  16. }
  17. func (l *lengthField) check(curOffset int, buf []byte) error {
  18. if uint32(curOffset-l.startOffset-4) != binary.BigEndian.Uint32(buf[l.startOffset:]) {
  19. return PacketDecodingError{"length field invalid"}
  20. }
  21. return nil
  22. }
  23. type varintLengthField struct {
  24. startOffset int
  25. length int64
  26. }
  27. func (l *varintLengthField) decode(pd packetDecoder) error {
  28. var err error
  29. l.length, err = pd.getVarint()
  30. return err
  31. }
  32. func (l *varintLengthField) saveOffset(in int) {
  33. l.startOffset = in
  34. }
  35. func (l *varintLengthField) adjustLength(currOffset int) int {
  36. oldFieldSize := l.reserveLength()
  37. l.length = int64(currOffset - l.startOffset - oldFieldSize)
  38. return l.reserveLength() - oldFieldSize
  39. }
  40. func (l *varintLengthField) reserveLength() int {
  41. var tmp [binary.MaxVarintLen64]byte
  42. return binary.PutVarint(tmp[:], l.length)
  43. }
  44. func (l *varintLengthField) run(curOffset int, buf []byte) error {
  45. binary.PutVarint(buf[l.startOffset:], l.length)
  46. return nil
  47. }
  48. func (l *varintLengthField) check(curOffset int, buf []byte) error {
  49. if int64(curOffset-l.startOffset-l.reserveLength()) != l.length {
  50. return PacketDecodingError{"length field invalid"}
  51. }
  52. return nil
  53. }