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
|
package btrfs
import (
"encoding/binary"
"encoding/hex"
"fmt"
"hash/crc32"
"lukeshu.com/btrfs-tools/pkg/util"
)
type CSum [0x20]byte
func (csum CSum) String() string {
return hex.EncodeToString(csum[:])
}
func (csum CSum) Fmt(typ CSumType) string {
return hex.EncodeToString(csum[:typ.Size()])
}
func (csum CSum) Format(f fmt.State, verb rune) {
util.FormatByteArrayStringer(csum, csum[:], f, verb)
}
type CSumType uint16
const (
CSUM_TYPE_CRC32 = CSumType(iota)
CSUM_TYPE_XXHASH
CSUM_TYPE_SHA256
CSUM_TYPE_BLAKE2
)
func (typ CSumType) String() string {
names := map[CSumType]string{
CSUM_TYPE_CRC32: "crc32c",
CSUM_TYPE_XXHASH: "xxhash64",
CSUM_TYPE_SHA256: "sha256",
CSUM_TYPE_BLAKE2: "blake2",
}
if name, ok := names[typ]; ok {
return name
}
return fmt.Sprintf("%d", typ)
}
func (typ CSumType) Size() int {
sizes := map[CSumType]int{
CSUM_TYPE_CRC32: 4,
CSUM_TYPE_XXHASH: 8,
CSUM_TYPE_SHA256: 32,
CSUM_TYPE_BLAKE2: 32,
}
if size, ok := sizes[typ]; ok {
return size
}
return len(CSum{})
}
func (typ CSumType) Sum(data []byte) (CSum, error) {
switch typ {
case CSUM_TYPE_CRC32:
crc := crc32.Update(0, crc32.MakeTable(crc32.Castagnoli), data)
var ret CSum
binary.LittleEndian.PutUint32(ret[:], crc)
return ret, nil
case CSUM_TYPE_XXHASH:
panic("not implemented")
case CSUM_TYPE_SHA256:
panic("not implemented")
case CSUM_TYPE_BLAKE2:
panic("not implemented")
default:
return CSum{}, fmt.Errorf("unknown checksum type: %v", typ)
}
}
|