crc32_field.go 836 B

12345678910111213141516171819202122232425262728293031323334353637
  1. package sarama
  2. import (
  3. "encoding/binary"
  4. "fmt"
  5. "hash/crc32"
  6. )
  7. // crc32Field implements the pushEncoder and pushDecoder interfaces for calculating CRC32s.
  8. type crc32Field struct {
  9. startOffset int
  10. }
  11. func (c *crc32Field) saveOffset(in int) {
  12. c.startOffset = in
  13. }
  14. func (c *crc32Field) reserveLength() int {
  15. return 4
  16. }
  17. func (c *crc32Field) run(curOffset int, buf []byte) error {
  18. crc := crc32.ChecksumIEEE(buf[c.startOffset+4 : curOffset])
  19. binary.BigEndian.PutUint32(buf[c.startOffset:], crc)
  20. return nil
  21. }
  22. func (c *crc32Field) check(curOffset int, buf []byte) error {
  23. crc := crc32.ChecksumIEEE(buf[c.startOffset+4 : curOffset])
  24. expected := binary.BigEndian.Uint32(buf[c.startOffset:])
  25. if crc != expected {
  26. return PacketDecodingError{fmt.Sprintf("CRC didn't match expected %#x got %#x", expected, crc)}
  27. }
  28. return nil
  29. }