]> git.sesse.net Git - cubemap/blob - metacube2.cpp
Support joining multicast addresses (both ASM and SSM).
[cubemap] / metacube2.cpp
1 /*
2  * Implementation of Metacube2 utility functions.
3  *
4  * Note: This file is meant to compile as both C and C++, for easier inclusion
5  * in other projects.
6  */
7
8 #include "metacube2.h"
9
10 /*
11  * https://www.ece.cmu.edu/~koopman/pubs/KoopmanCRCWebinar9May2012.pdf
12  * recommends this for messages as short as ours (see table at page 34).
13  */
14 #define METACUBE2_CRC_POLYNOMIAL 0x8FDB
15
16 /* Semi-random starting value to make sure all-zero won't pass. */
17 #define METACUBE2_CRC_START 0x1234
18
19 /* This code is based on code generated by pycrc. */
20 uint16_t metacube2_compute_crc(const struct metacube2_block_header *hdr)
21 {
22         static const int data_len = sizeof(hdr->size) + sizeof(hdr->flags);
23         const uint8_t *data = (uint8_t *)&hdr->size;
24         uint16_t crc = METACUBE2_CRC_START;
25         int i, j;
26
27         for (i = 0; i < data_len; ++i) {        
28                 uint8_t c = data[i];
29                 for (j = 0; j < 8; j++) {
30                         int bit = crc & 0x8000;
31                         crc = (crc << 1) | ((c >> (7 - j)) & 0x01);
32                         if (bit) {
33                                 crc ^= METACUBE2_CRC_POLYNOMIAL;
34                         }
35                 }
36         }
37
38         /* Finalize. */
39         for (i = 0; i < 16; i++) {
40                 int bit = crc & 0x8000;
41                 crc = crc << 1;
42                 if (bit) {
43                         crc ^= METACUBE2_CRC_POLYNOMIAL;
44                 }
45         }
46
47         return crc;
48 }