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