checksum.go 1.5 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950
  1. /*
  2. * Copyright 2019 Dgraph Labs, Inc. and Contributors
  3. *
  4. * Licensed under the Apache License, Version 2.0 (the "License");
  5. * you may not use this file except in compliance with the License.
  6. * You may obtain a copy of the License at
  7. *
  8. * http://www.apache.org/licenses/LICENSE-2.0
  9. *
  10. * Unless required by applicable law or agreed to in writing, software
  11. * distributed under the License is distributed on an "AS IS" BASIS,
  12. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  13. * See the License for the specific language governing permissions and
  14. * limitations under the License.
  15. */
  16. package y
  17. import (
  18. stderrors "errors"
  19. "hash/crc32"
  20. "github.com/cespare/xxhash/v2"
  21. "github.com/dgraph-io/badger/v4/pb"
  22. )
  23. // ErrChecksumMismatch is returned at checksum mismatch.
  24. var ErrChecksumMismatch = stderrors.New("checksum mismatch")
  25. // CalculateChecksum calculates checksum for data using ct checksum type.
  26. func CalculateChecksum(data []byte, ct pb.Checksum_Algorithm) uint64 {
  27. switch ct {
  28. case pb.Checksum_CRC32C:
  29. return uint64(crc32.Checksum(data, CastagnoliCrcTable))
  30. case pb.Checksum_XXHash64:
  31. return xxhash.Sum64(data)
  32. default:
  33. panic("checksum type not supported")
  34. }
  35. }
  36. // VerifyChecksum validates the checksum for the data against the given expected checksum.
  37. func VerifyChecksum(data []byte, expected *pb.Checksum) error {
  38. actual := CalculateChecksum(data, expected.Algo)
  39. if actual != expected.Sum {
  40. return Wrapf(ErrChecksumMismatch, "actual: %d, expected: %d", actual, expected.Sum)
  41. }
  42. return nil
  43. }