Skip to content

Commit f640265

Browse files
committed
avoid duplicate code by adding setup_table()
1 parent 0c1418e commit f640265

File tree

1 file changed

+23
-22
lines changed

1 file changed

+23
-22
lines changed

bitarray/_util.c

Lines changed: 23 additions & 22 deletions
Original file line numberDiff line numberDiff line change
@@ -265,6 +265,25 @@ Return parity of bitarray `a`.\n\
265265
`parity(a)` is equivalent to `a.count() % 2` but more efficient.");
266266

267267

268+
static void
269+
setup_table(char *table, int le, char op)
270+
{
271+
int j, k;
272+
273+
memset(table, 0, 256);
274+
for (k = 0; k < 256; k++) {
275+
for (j = 1; j < 8; j++) {
276+
if (( le && k & 0x01 << j) || /* little endian */
277+
(!le && k & 0x80 >> j)) /* big endian */
278+
switch (op) {
279+
case 'a': table[k] += j; break;
280+
case 'x': table[k] ^= j; break;
281+
default: Py_UNREACHABLE();
282+
}
283+
}
284+
}
285+
}
286+
268287
static PyObject *
269288
add_uint64(PyObject *number, uint64_t i)
270289
{
@@ -279,7 +298,7 @@ add_uint64(PyObject *number, uint64_t i)
279298
static PyObject *
280299
sum_indices(PyObject *module, PyObject *obj)
281300
{
282-
static signed char table[256];
301+
static char table[256];
283302
static int setup = -1; /* endianness of table */
284303
PyObject *res;
285304
bitarrayobject *a;
@@ -295,16 +314,7 @@ sum_indices(PyObject *module, PyObject *obj)
295314
set_padbits(a);
296315

297316
if (setup != a->endian) {
298-
int j, k;
299-
memset(table, 0, sizeof table);
300-
for (k = 0; k < 256; k++) {
301-
for (j = 1; j < 8; j++) {
302-
if (IS_LE(a) && k & 0x01 << j) /* little endian */
303-
table[k] += j;
304-
if (IS_BE(a) && k & 0x80 >> j) /* big endian */
305-
table[k] += j;
306-
}
307-
}
317+
setup_table(table, IS_LE(a), 'a');
308318
setup = a->endian;
309319
}
310320

@@ -337,7 +347,7 @@ This is equivalent to `sum(i for i, v in enumerate(a) if v)`.");
337347
static PyObject *
338348
xor_indices(PyObject *module, PyObject *obj)
339349
{
340-
static signed char table[256];
350+
static char table[256];
341351
static int setup = -1; /* endianness of table */
342352
bitarrayobject *a;
343353
Py_ssize_t res = 0, nbytes, i;
@@ -350,16 +360,7 @@ xor_indices(PyObject *module, PyObject *obj)
350360
set_padbits(a);
351361

352362
if (setup != a->endian) {
353-
int j, k;
354-
memset(table, 0, sizeof table);
355-
for (k = 0; k < 256; k++) {
356-
for (j = 1; j < 8; j++) {
357-
if (IS_LE(a) && k & 0x01 << j) /* little endian */
358-
table[k] ^= j;
359-
if (IS_BE(a) && k & 0x80 >> j) /* big endian */
360-
table[k] ^= j;
361-
}
362-
}
363+
setup_table(table, IS_LE(a), 'x');
363364
setup = a->endian;
364365
}
365366

0 commit comments

Comments
 (0)