summaryrefslogtreecommitdiff
path: root/lib/btrfs/btrfssum/csum.go
blob: 6df9efd3dd260e951156c50f42ae1feb50eff108 (plain)
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
// Copyright (C) 2022-2023  Luke Shumaker <lukeshu@lukeshu.com>
//
// SPDX-License-Identifier: GPL-2.0-or-later

package btrfssum

import (
	"encoding"
	"encoding/binary"
	"encoding/hex"
	"fmt"
	"hash/crc32"

	"git.lukeshu.com/btrfs-progs-ng/lib/fmtutil"
)

type CSum [0x20]byte

var (
	_ fmt.Stringer             = CSum{}
	_ fmt.Formatter            = CSum{}
	_ encoding.TextMarshaler   = CSum{}
	_ encoding.TextUnmarshaler = (*CSum)(nil)
)

func (csum CSum) String() string {
	return hex.EncodeToString(csum[:])
}

func (csum CSum) MarshalText() ([]byte, error) {
	var ret [len(csum) * 2]byte
	hex.Encode(ret[:], csum[:])
	return ret[:], nil
}

func (csum *CSum) UnmarshalText(text []byte) error {
	*csum = CSum{}
	_, err := hex.Decode(csum[:], text)
	return err
}

func (csum CSum) Fmt(typ CSumType) string {
	return hex.EncodeToString(csum[:typ.Size()])
}

func (csum CSum) Format(f fmt.State, verb rune) {
	fmtutil.FormatByteArrayStringer(csum, csum[:], f, verb)
}

type CSumType uint16

const (
	TYPE_CRC32 = CSumType(iota)
	TYPE_XXHASH
	TYPE_SHA256
	TYPE_BLAKE2
)

func (typ CSumType) String() string {
	names := map[CSumType]string{
		TYPE_CRC32:  "crc32c",
		TYPE_XXHASH: "xxhash64",
		TYPE_SHA256: "sha256",
		TYPE_BLAKE2: "blake2",
	}
	if name, ok := names[typ]; ok {
		return name
	}
	return fmt.Sprintf("%d", typ)
}

func (typ CSumType) Size() int {
	//nolint:gomnd // This is where we define the magic numbers.
	sizes := map[CSumType]int{
		TYPE_CRC32:  4,
		TYPE_XXHASH: 8,
		TYPE_SHA256: 32,
		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 TYPE_CRC32:
		crc := crc32.Update(0, crc32.MakeTable(crc32.Castagnoli), data)

		var ret CSum
		binary.LittleEndian.PutUint32(ret[:], crc)
		return ret, nil
	case TYPE_XXHASH:
		panic("TODO: XXHASH not yet implemented")
	case TYPE_SHA256:
		panic("TODO: SHA256 not yet implemented")
	case TYPE_BLAKE2:
		panic("TODO: BLAKE2 not yet implemented")
	default:
		return CSum{}, fmt.Errorf("unknown checksum type: %v", typ)
	}
}