seaweedfs/weed/storage/needle/crc.go

56 lines
932 B
Go
Raw Normal View History

2019-04-19 12:43:36 +08:00
package needle
2012-09-26 06:37:13 +08:00
import (
2018-11-23 16:26:15 +08:00
"fmt"
"hash"
"io"
2018-11-23 16:26:15 +08:00
"github.com/klauspost/crc32"
"github.com/chrislusf/seaweedfs/weed/util"
2012-09-26 06:37:13 +08:00
)
var table = crc32.MakeTable(crc32.Castagnoli)
type CRC uint32
func NewCRC(b []byte) CRC {
return CRC(0).Update(b)
}
func (c CRC) Update(b []byte) CRC {
return CRC(crc32.Update(uint32(c), table, b))
}
func (c CRC) Value() uint32 {
return uint32(c>>15|c<<17) + 0xa282ead8
}
2014-07-22 15:24:50 +08:00
func (n *Needle) Etag() string {
bits := make([]byte, 4)
util.Uint32toBytes(bits, uint32(n.Checksum))
2018-09-10 07:25:43 +08:00
return fmt.Sprintf("%x", bits)
2014-07-22 15:24:50 +08:00
}
func NewCRCwriter(w io.Writer) *CRCwriter {
return &CRCwriter{
h: crc32.New(table),
w: w,
}
}
type CRCwriter struct {
h hash.Hash32
w io.Writer
}
func (c *CRCwriter) Write(p []byte) (n int, err error) {
n, err = c.w.Write(p) // with each write ...
c.h.Write(p) // ... update the hash
return
}
func (c *CRCwriter) Sum() uint32 { return c.h.Sum32() } // final hash