github.com/cockroachdb/pebble@v0.0.0-20231214172447-ab4952c5f87b/internal/crc/crc.go (about) 1 // Copyright 2011 The LevelDB-Go and Pebble Authors. All rights reserved. Use 2 // of this source code is governed by a BSD-style license that can be found in 3 // the LICENSE file. 4 5 // Package crc implements the checksum algorithm used throughout pebble. 6 // 7 // The algorithm is CRC-32 with Castagnoli's polynomial, followed by a bit 8 // rotation and an additional delta. The additional processing is to lessen the 9 // probability of arbitrary key/value data coincidentally containing bytes that 10 // look like a checksum. 11 // 12 // To calculate the uint32 checksum of some data: 13 // 14 // var u uint32 = crc.New(data).Value() 15 // 16 // In pebble, the uint32 value is then stored in little-endian format. 17 package crc // import "github.com/cockroachdb/pebble/internal/crc" 18 19 import "hash/crc32" 20 21 var table = crc32.MakeTable(crc32.Castagnoli) 22 23 // CRC is a small convenience wrapper for computing the CRC32 checksum used by 24 // pebble. This is the same algorithm as used by RocksDB. 25 type CRC uint32 26 27 // New returns the result of adding the bytes to the zero-value CRC. 28 func New(b []byte) CRC { 29 return CRC(0).Update(b) 30 } 31 32 // Update returns the result of adding the bytes to the CRC. 33 func (c CRC) Update(b []byte) CRC { 34 return CRC(crc32.Update(uint32(c), table, b)) 35 } 36 37 // Value returns the cooked CRC value. The additional processing is to lessen 38 // the probability of arbitrary key/value data coincidentally containing bytes 39 // that look like a checksum. 40 func (c CRC) Value() uint32 { 41 return uint32(c>>15|c<<17) + 0xa282ead8 42 }