1 // Copyright 2020 The Pigweed Authors
3 // Licensed under the Apache License, Version 2.0 (the "License"); you may not
4 // use this file except in compliance with the License. You may obtain a copy of
7 // https://www.apache.org/licenses/LICENSE-2.0
9 // Unless required by applicable law or agreed to in writing, software
10 // distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
11 // WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
12 // License for the specific language governing permissions and limitations under
15 // CRC-32 (CRC32) implementation with initial value 0xFFFFFFFF. This provides C
16 // functions and a C++ class. Use of the C API is discouraged; use the Crc32
17 // class whevener possible.
27 // Value of an empty CRC32. May be serve as the starting CRC32 value for
28 // pw_checksum_Crc32Append.
29 #define PW_CHECKSUM_EMPTY_CRC32 ~_PW_CHECKSUM_CRC32_INITIAL_STATE
31 // The initial state for internal CRC32 calculations. Do not use this value
33 #define _PW_CHECKSUM_CRC32_INITIAL_STATE 0xFFFFFFFFu
35 // Internal implementation function for CRC32. Do not call it directly.
36 uint32_t _pw_checksum_InternalCrc32(const void* data,
40 // Calculates the CRC32 for the provided data.
41 static inline uint32_t pw_checksum_Crc32(const void* data, size_t size_bytes) {
42 return ~_pw_checksum_InternalCrc32(
43 data, size_bytes, _PW_CHECKSUM_CRC32_INITIAL_STATE);
46 // Updates an existing CRC value. The previous_result must have been returned
47 // from a previous CRC32 call.
48 static inline uint32_t pw_checksum_Crc32Append(const void* data,
50 uint32_t previous_result) {
51 // CRC32 values are finalized by inverting the bits. The finalization step
52 // must be undone before appending to a prior CRC32 value, then redone so this
53 // function returns a usable value after each call.
54 return ~_pw_checksum_InternalCrc32(data, size_bytes, ~previous_result);
62 namespace pw::checksum {
64 // Calculates the CRC32 for all data passed to Update.
66 // This class is more efficient than the CRC32 C functions since it doesn't
67 // finalize the value each time it is appended to.
70 // Calculates the CRC32 for the provided data and returns it as a uint32_t.
71 // To update a CRC in multiple pieces, use an instance of the Crc32 class.
72 static uint32_t Calculate(std::span<const std::byte> data) {
73 return pw_checksum_Crc32(data.data(), data.size_bytes());
76 constexpr Crc32() : state_(kInitialValue) {}
78 void Update(std::span<const std::byte> data) {
79 state_ = _pw_checksum_InternalCrc32(data.data(), data.size(), state_);
82 void Update(std::byte data) { Update(std::span(&data, 1)); }
84 // Returns the value of the CRC32 for all data passed to Update.
85 uint32_t value() const { return ~state_; }
87 // Resets the CRC to the initial value.
88 void clear() { state_ = kInitialValue; }
91 static constexpr uint32_t kInitialValue = _PW_CHECKSUM_CRC32_INITIAL_STATE;
96 } // namespace pw::checksum