/
checksum.go
128 lines (103 loc) · 2.53 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
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
package store
import (
"hash/crc32"
"io"
)
// ChecksumIndexInput Extension of IndexInput, computing checksum as it goes. Callers can retrieve the checksum via getChecksum().
type ChecksumIndexInput interface {
IndexInput
// GetChecksum Returns the current checksum value
GetChecksum() uint32
}
var _ ChecksumIndexInput = &BufferedChecksumIndexInput{}
// BufferedChecksumIndexInput
// Simple implementation of ChecksumIndexInput that wraps another input and delegates calls.
type BufferedChecksumIndexInput struct {
*BaseIndexInput
input IndexInput
digest Hash
}
func NewBufferedChecksumIndexInput(in IndexInput) *BufferedChecksumIndexInput {
input := &BufferedChecksumIndexInput{
input: in,
digest: NewHash(),
}
input.BaseIndexInput = NewBaseIndexInput(input)
return input
}
type Hash interface {
Write(p []byte)
Sum() uint32
Clone() Hash
}
// 自定义
type crc32Hash struct {
crc uint32
tab *crc32.Table
}
func NewHash() Hash {
return &crc32Hash{tab: crc32.IEEETable}
}
func (c *crc32Hash) Write(p []byte) {
c.crc = crc32.Update(c.crc, c.tab, p)
}
func (c *crc32Hash) Sum() uint32 {
return c.crc
}
func (c *crc32Hash) Clone() Hash {
newTab := &crc32.Table{}
copy(newTab[:], c.tab[:])
return &crc32Hash{
crc: c.crc,
tab: newTab,
}
}
func (b *BufferedChecksumIndexInput) Slice(sliceDescription string, offset, length int64) (IndexInput, error) {
//TODO implement me
panic("implement me")
}
func (b *BufferedChecksumIndexInput) GetFilePointer() int64 {
return b.input.GetFilePointer()
}
func (b *BufferedChecksumIndexInput) Seek(pos int64, whence int) (int64, error) {
return b.input.Seek(pos, io.SeekStart)
}
func (b *BufferedChecksumIndexInput) Length() int64 {
return b.input.Length()
}
//func (b *BufferedChecksumIndexInput) ReadByte() (byte, error) {
// readByte, err := b.input.ReadByte()
// if err != nil {
// return 0, err
// }
//
// b.digest.Write([]byte{readByte})
//
// return readByte, nil
//}
func (b *BufferedChecksumIndexInput) Read(bs []byte) (int, error) {
n, err := b.input.Read(bs)
if err != nil {
return 0, err
}
b.digest.Write(bs[:n])
return n, nil
}
func (b *BufferedChecksumIndexInput) Clone() CloneReader {
indexInput, ok := b.input.Clone().(IndexInput)
if !ok {
return b
}
input := &BufferedChecksumIndexInput{
input: indexInput,
digest: b.digest.Clone(),
}
input.BaseIndexInput = NewBaseIndexInput(input)
return input
}
func (b *BufferedChecksumIndexInput) GetChecksum() uint32 {
return b.digest.Sum()
}
func (b *BufferedChecksumIndexInput) Close() error {
return b.input.Close()
}