checksum.go 1.0 KB

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