Skip to content

Commit e929b6b

Browse files
committed
Port _djb_hash to Python 3.
1 parent 904a3a3 commit e929b6b

2 files changed

Lines changed: 34 additions & 5 deletions

File tree

cdblib/_djb_hash.c

Lines changed: 33 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -1,6 +1,16 @@
11
#define PY_SSIZE_T_CLEAN
22
#include "Python.h"
33

4+
#if PY_MAJOR_VERSION >= 3
5+
# define MOD_RETURN(mod) return mod;
6+
# define MODINIT_NAME PyInit__djb_hash
7+
# define BUFFERLIKE_FMT "y#"
8+
#else
9+
# define MOD_RETURN(mod) return;
10+
# define MODINIT_NAME init_djb_hash
11+
# define BUFFERLIKE_FMT "t#"
12+
#endif
13+
414
/* Return a Python long instance containing the value of the DJB hash function
515
* for the given string or array. */
616
static PyObject *
@@ -10,7 +20,7 @@ djb_hash(PyObject *self, PyObject *args)
1020
unsigned int h = 5381;
1121
Py_ssize_t len;
1222

13-
if(! PyArg_ParseTuple(args, "t#", &s, &len))
23+
if(! PyArg_ParseTuple(args, BUFFERLIKE_FMT, &s, &len))
1424
return NULL;
1525

1626
while(len--)
@@ -20,15 +30,34 @@ djb_hash(PyObject *self, PyObject *args)
2030
}
2131

2232

23-
static /*const*/ PyMethodDef methods[] = {
33+
static /*const*/ PyMethodDef module_methods[] = {
2434
{"djb_hash", djb_hash, METH_VARARGS,
2535
"Return the value of DJB's hash function for the given 8-bit string."},
2636
{NULL, NULL, 0, NULL}
2737
};
2838

39+
#if PY_MAJOR_VERSION >= 3
40+
static struct PyModuleDef moduledef = {
41+
PyModuleDef_HEAD_INIT,
42+
"_djb_hash",
43+
NULL,
44+
-1,
45+
module_methods,
46+
NULL,
47+
NULL,
48+
NULL,
49+
NULL
50+
};
51+
#endif
2952

3053
PyMODINIT_FUNC
31-
init_djb_hash(void)
54+
MODINIT_NAME(void)
3255
{
33-
Py_InitModule("_djb_hash", methods);
56+
#if PY_MAJOR_VERSION >= 3
57+
PyObject *mod = PyModule_Create(&moduledef);
58+
#else
59+
PyObject *mod = Py_InitModule3("_djb_hash", module_methods, "");
60+
#endif
61+
62+
MOD_RETURN(mod);
3463
}

setup.py

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -6,7 +6,7 @@
66

77
# Opt-in to building the C extensions for Python 2 by setting the
88
# ENABLE_DJB_HASH_CEXT environment variable
9-
if (version_info[0] == 2) and environ.get('ENABLE_DJB_HASH_CEXT'):
9+
if environ.get('ENABLE_DJB_HASH_CEXT'):
1010
ext_modules = [
1111
Extension('cdblib._djb_hash', sources=['cdblib/_djb_hash.c']),
1212
]

0 commit comments

Comments
 (0)