checksum.go raw
1 /*
2 * SPDX-FileCopyrightText: © Hypermode Inc. <hello@hypermode.com>
3 * SPDX-License-Identifier: Apache-2.0
4 */
5
6 package y
7
8 import (
9 stderrors "errors"
10 "hash/crc32"
11
12 "github.com/cespare/xxhash/v2"
13
14 "github.com/dgraph-io/badger/v4/pb"
15 )
16
17 // ErrChecksumMismatch is returned at checksum mismatch.
18 var ErrChecksumMismatch = stderrors.New("checksum mismatch")
19
20 // CalculateChecksum calculates checksum for data using ct checksum type.
21 func CalculateChecksum(data []byte, ct pb.Checksum_Algorithm) uint64 {
22 switch ct {
23 case pb.Checksum_CRC32C:
24 return uint64(crc32.Checksum(data, CastagnoliCrcTable))
25 case pb.Checksum_XXHash64:
26 return xxhash.Sum64(data)
27 default:
28 panic("checksum type not supported")
29 }
30 }
31
32 // VerifyChecksum validates the checksum for the data against the given expected checksum.
33 func VerifyChecksum(data []byte, expected *pb.Checksum) error {
34 actual := CalculateChecksum(data, expected.Algo)
35 if actual != expected.Sum {
36 return Wrapf(ErrChecksumMismatch, "actual: %d, expected: %d", actual, expected.Sum)
37 }
38 return nil
39 }
40