crc.cc
Go to the documentation of this file.
1 /**************************************************************************/ /**
2  * @brief Utility functions.
3  * @file
4  ******************************************************************************/
5 
6 #include <cstddef> // For offsetof()
7 
9 
10 namespace {
11 
12 /******************************************************************************/
13 const uint32_t* GetCRCTable() {
14  // Note: This is the CRC-32 polynomial.
15  static constexpr uint32_t polynomial = 0xEDB88320;
16 
17  static bool is_initialized = false;
18  static uint32_t crc_table[256];
19 
20  if (!is_initialized) {
21  for (uint32_t i = 0; i < 256; i++) {
22  uint32_t c = i;
23  for (size_t j = 0; j < 8; j++) {
24  if (c & 1) {
25  c = polynomial ^ (c >> 1);
26  } else {
27  c >>= 1;
28  }
29  }
30  crc_table[i] = c;
31  }
32 
33  is_initialized = true;
34  }
35 
36  return crc_table;
37 }
38 } // namespace
39 
40 namespace point_one {
41 namespace fusion_engine {
42 namespace messages {
43 
44 /******************************************************************************/
45 uint32_t CalculateCRC(const void* buffer, size_t length,
46  uint32_t initial_value) {
47  static const uint32_t* crc_table = ::GetCRCTable();
48  uint32_t c = initial_value ^ 0xFFFFFFFF;
49  const uint8_t* u = static_cast<const uint8_t*>(buffer);
50  for (size_t i = 0; i < length; ++i) {
51  c = crc_table[(c ^ u[i]) & 0xFF] ^ (c >> 8);
52  }
53  return c ^ 0xFFFFFFFF;
54 }
55 
56 /******************************************************************************/
57 uint32_t CalculateCRC(const void* buffer) {
58  static constexpr size_t offset = offsetof(MessageHeader, protocol_version);
59  const MessageHeader& header = *static_cast<const MessageHeader*>(buffer);
60  size_t size_bytes =
61  (sizeof(MessageHeader) - offset) + header.payload_size_bytes;
62  return CalculateCRC(reinterpret_cast<const uint8_t*>(&header) + offset,
63  size_bytes);
64 }
65 
66 } // namespace messages
67 } // namespace fusion_engine
68 } // namespace point_one
uint32_t CalculateCRC(const void *buffer, size_t length, uint32_t initial_value)
Calculate the CRC for the message (payload) contained in the buffer.
Definition: crc.cc:45
The header present at the beginning of every message.
Definition: defs.h:569
Message CRC support.
GNSS signal and frequency type definitions.
Definition: logging.h:38
uint32_t payload_size_bytes
The size of the serialized message (bytes).
Definition: defs.h:610