File: metacube2.cpp

package info (click to toggle)
cubemap 1.3.2-1
  • links: PTS, VCS
  • area: main
  • in suites: stretch
  • size: 428 kB
  • sloc: cpp: 4,431; sh: 114; perl: 102; makefile: 60
file content (59 lines) | stat: -rw-r--r-- 1,458 bytes parent folder | download | duplicates (4)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
/*
 * Implementation of Metacube2 utility functions.
 *
 * Note: This file is meant to compile as both C and C++, for easier inclusion
 * in other projects.
 */

#include "metacube2.h"

#include <arpa/inet.h>

/*
 * https://www.ece.cmu.edu/~koopman/pubs/KoopmanCRCWebinar9May2012.pdf
 * recommends this for messages as short as ours (see table at page 34).
 */
#define METACUBE2_CRC_POLYNOMIAL 0x8FDB

/* Semi-random starting value to make sure all-zero won't pass. */
#define METACUBE2_CRC_START 0x1234

/* This code is based on code generated by pycrc. */
uint16_t metacube2_compute_crc(const struct metacube2_block_header *hdr)
{
	static const int data_len = sizeof(hdr->size) + sizeof(hdr->flags);
	const uint8_t *data = (uint8_t *)&hdr->size;
	uint16_t crc = METACUBE2_CRC_START;
	int i, j;

	for (i = 0; i < data_len; ++i) {
		uint8_t c = data[i];
		for (j = 0; j < 8; j++) {
			int bit = crc & 0x8000;
			crc = (crc << 1) | ((c >> (7 - j)) & 0x01);
			if (bit) {
				crc ^= METACUBE2_CRC_POLYNOMIAL;
			}
		}
	}

	/* Finalize. */
	for (i = 0; i < 16; i++) {
		int bit = crc & 0x8000;
		crc = crc << 1;
		if (bit) {
			crc ^= METACUBE2_CRC_POLYNOMIAL;
		}
	}

	/*
	 * Invert the checksum for metadata packets, so that clients that
	 * don't understand metadata will ignore it as broken. There will
	 * probably be logging, but apart from that, it's harmless.
	 */
	if (ntohs(hdr->flags) & METACUBE_FLAGS_METADATA) {
		crc ^= 0xffff;
	}

	return crc;
}