Debian Codegraph @

modes_crc.c

raw symbols SCIP
1 /*
2 * Part of mlat-client - an ADS-B multilateration client.
3 * Copyright 2015, Oliver Jowett <[email protected]>
4 *
5 * This program is free software: you can redistribute it and/or modify
6 * it under the terms of the GNU General Public License as published by
7 * the Free Software Foundation, either version 3 of the License, or
8 * (at your option) any later version.
9 *
10 * This program is distributed in the hope that it will be useful,
11 * but WITHOUT ANY WARRANTY; without even the implied warranty of
12 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
13 * GNU General Public License for more details.
14 *
15 * You should have received a copy of the GNU General Public License
16 * along with this program. If not, see <http://www.gnu.org/licenses/>.
17 */
18
19 #include "_modes.h"
20
21
22 /********** CRC ****************/
23
24 /* Generator polynomial for the Mode S CRC */
25 #define MODES_GENERATOR_POLY 0xfff409U
26
27 /* CRC values for all single-byte messages; used to speed up CRC calculation. */
28 static uint32_t crc_table[256];
29
30 int modescrc_module_init(PyObject *m)
31 {
32 int i;
33
34 for (i = 0; i < 256; ++i) {
35 uint32_t c = i << 16;
36 int j;
37 for (j = 0; j < 8; ++j) {
38 if (c & 0x800000)
39 c = (c<<1) ^ MODES_GENERATOR_POLY;
40 else
41 c = (c<<1);
42 }
43
44 crc_table[i] = c & 0x00ffffff;
45 }
46
47 return 0;
48 }
49
50 void modescrc_module_free(PyObject *m)
51 {
52 }
53
54 uint32_t modescrc_buffer_crc(uint8_t *buf, Py_ssize_t len)
55 {
56 uint32_t rem;
57 Py_ssize_t i;
58 for (rem = 0, i = len; i > 0; --i) {
59 rem = ((rem & 0x00ffff) << 8) ^ crc_table[*buf++ ^ ((rem & 0xff0000) >> 16)];
60 }
61
62 return rem;
63 }
64
65 PyObject *modescrc_crc(PyObject *self, PyObject *args)
66 {
67 Py_buffer buffer;
68 PyObject *rv = NULL;
69
70 if (!PyArg_ParseTuple(args, "s*", &buffer))
71 return NULL;
72
73 if (buffer.itemsize != 1) {
74 PyErr_SetString(PyExc_ValueError, "buffer itemsize is not 1");
75 goto out;
76 }
77
78 if (!PyBuffer_IsContiguous(&buffer, 'C')) {
79 PyErr_SetString(PyExc_ValueError, "buffer is not contiguous");
80 goto out;
81 }
82
83 rv = PyLong_FromLong(modescrc_buffer_crc(buffer.buf, buffer.len));
84
85 out:
86 PyBuffer_Release(&buffer);
87 return rv;
88 }