crc32.go 1010 B

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455
  1. package kafka
  2. import (
  3. "encoding/binary"
  4. "hash/crc32"
  5. )
  6. type crc32Writer struct {
  7. table *crc32.Table
  8. buffer [8]byte
  9. crc32 uint32
  10. }
  11. func (w *crc32Writer) update(b []byte) {
  12. w.crc32 = crc32.Update(w.crc32, w.table, b)
  13. }
  14. func (w *crc32Writer) writeInt8(i int8) {
  15. w.buffer[0] = byte(i)
  16. w.update(w.buffer[:1])
  17. }
  18. func (w *crc32Writer) writeInt16(i int16) {
  19. binary.BigEndian.PutUint16(w.buffer[:2], uint16(i))
  20. w.update(w.buffer[:2])
  21. }
  22. func (w *crc32Writer) writeInt32(i int32) {
  23. binary.BigEndian.PutUint32(w.buffer[:4], uint32(i))
  24. w.update(w.buffer[:4])
  25. }
  26. func (w *crc32Writer) writeInt64(i int64) {
  27. binary.BigEndian.PutUint64(w.buffer[:8], uint64(i))
  28. w.update(w.buffer[:8])
  29. }
  30. func (w *crc32Writer) writeBytes(b []byte) {
  31. n := len(b)
  32. if b == nil {
  33. n = -1
  34. }
  35. w.writeInt32(int32(n))
  36. w.update(b)
  37. }
  38. func (w *crc32Writer) Write(b []byte) (int, error) {
  39. w.update(b)
  40. return len(b), nil
  41. }
  42. func (w *crc32Writer) WriteString(s string) (int, error) {
  43. w.update([]byte(s))
  44. return len(s), nil
  45. }