crc.go 895 B

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354
  1. package needle
  2. import (
  3. "fmt"
  4. "io"
  5. "github.com/klauspost/crc32"
  6. "github.com/chrislusf/seaweedfs/weed/util"
  7. )
  8. var table = crc32.MakeTable(crc32.Castagnoli)
  9. type CRC uint32
  10. func NewCRC(b []byte) CRC {
  11. return CRC(0).Update(b)
  12. }
  13. func (c CRC) Update(b []byte) CRC {
  14. return CRC(crc32.Update(uint32(c), table, b))
  15. }
  16. func (c CRC) Value() uint32 {
  17. return uint32(c>>15|c<<17) + 0xa282ead8
  18. }
  19. func (n *Needle) Etag() string {
  20. bits := make([]byte, 4)
  21. util.Uint32toBytes(bits, uint32(n.Checksum))
  22. return fmt.Sprintf("%x", bits)
  23. }
  24. func NewCRCwriter(w io.Writer) *CRCwriter {
  25. return &CRCwriter{
  26. crc: CRC(0),
  27. w: w,
  28. }
  29. }
  30. type CRCwriter struct {
  31. crc CRC
  32. w io.Writer
  33. }
  34. func (c *CRCwriter) Write(p []byte) (n int, err error) {
  35. n, err = c.w.Write(p) // with each write ...
  36. c.crc = c.crc.Update(p)
  37. return
  38. }
  39. func (c *CRCwriter) Sum() uint32 { return c.crc.Value() } // final hash