-
Notifications
You must be signed in to change notification settings - Fork 178
/
checksum.go
67 lines (53 loc) · 1.17 KB
/
checksum.go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
package wal
import (
"fmt"
"hash"
"hash/crc32"
"io"
)
var crc32Table = crc32.MakeTable(crc32.Castagnoli)
type Crc32Writer struct {
hash hash.Hash32
Writer io.Writer
}
func NewCRC32Writer(writer io.Writer) *Crc32Writer {
return &Crc32Writer{
hash: crc32.New(crc32Table),
Writer: writer,
}
}
func (c *Crc32Writer) Write(p []byte) (n int, err error) {
// hash.Write never fails, but who knows
n, err = c.hash.Write(p)
if err != nil {
return n, fmt.Errorf("error while calculating crc32: %w", err)
}
return c.Writer.Write(p)
}
func (c *Crc32Writer) Crc32() uint32 {
return c.hash.Sum32()
}
type Crc32Reader struct {
hash hash.Hash32
reader io.Reader
}
func NewCRC32Reader(reader io.Reader) *Crc32Reader {
return &Crc32Reader{
hash: crc32.New(crc32Table),
reader: reader,
}
}
func (c *Crc32Reader) Read(p []byte) (int, error) {
read, err := c.reader.Read(p)
if err != nil {
return read, fmt.Errorf("error while reading for crc32 sum: %w", err)
}
_, err = c.hash.Write(p[:read])
if err != nil {
return 0, fmt.Errorf("error while calculating crc32: %w", err)
}
return read, err
}
func (c *Crc32Reader) Crc32() uint32 {
return c.hash.Sum32()
}