packet_crcs.go 828 B

123456789101112131415161718192021222324252627282930313233343536373839404142434445
  1. package protocol
  2. import (
  3. "encoding/binary"
  4. "hash/crc32"
  5. )
  6. type crc32Encoder struct {
  7. startOffset int
  8. }
  9. func (c *crc32Encoder) saveOffset(in int) {
  10. c.startOffset = in
  11. }
  12. func (c *crc32Encoder) reserveLength() int {
  13. return 4
  14. }
  15. func (c *crc32Encoder) run(curOffset int, buf []byte) {
  16. crc := crc32.ChecksumIEEE(buf[c.startOffset+4 : curOffset])
  17. binary.BigEndian.PutUint32(buf[c.startOffset:], crc)
  18. }
  19. type crc32Decoder struct {
  20. startOffset int
  21. }
  22. func (c *crc32Decoder) saveOffset(in int) {
  23. c.startOffset = in
  24. }
  25. func (c *crc32Decoder) reserveLength() int {
  26. return 4
  27. }
  28. func (c *crc32Decoder) check(curOffset int, buf []byte) error {
  29. crc := crc32.ChecksumIEEE(buf[c.startOffset+4 : curOffset])
  30. if crc != binary.BigEndian.Uint32(buf[c.startOffset:]) {
  31. return DecodingError("CRC did not match.")
  32. }
  33. return nil
  34. }