| 1 |
#include "Python.h" |
| 2 |
|
| 3 |
#if PY_MAJOR_VERSION >= 3 |
| 4 |
#define PyInt_CheckExact PyLong_CheckExact |
| 5 |
#endif |
| 6 |
|
| 7 |
typedef struct CmpObject { |
| 8 |
PyObject_HEAD |
| 9 |
} CmpObject; |
| 10 |
|
| 11 |
|
| 12 |
static PyObject* cmp_richcmp(PyObject *self, PyObject *other, int opid) { |
| 13 |
long val; |
| 14 |
if ((opid != Py_EQ && opid != Py_NE) || !PyInt_CheckExact(other)) { |
| 15 |
Py_INCREF(Py_NotImplemented); |
| 16 |
return Py_NotImplemented; |
| 17 |
} |
| 18 |
val = PyLong_AsLong(other); |
| 19 |
if (opid == Py_EQ) { |
| 20 |
return PyBool_FromLong(val == 3); |
| 21 |
} |
| 22 |
else if (opid == Py_NE) { |
| 23 |
return PyBool_FromLong(val != 3); |
| 24 |
} |
| 25 |
return Py_NotImplemented; |
| 26 |
} |
| 27 |
|
| 28 |
static long cmp_hashfunc(PyObject *self) { |
| 29 |
return 3; |
| 30 |
} |
| 31 |
|
| 32 |
|
| 33 |
PyTypeObject CmpType = { |
| 34 |
PyVarObject_HEAD_INIT(NULL, 0) |
| 35 |
"comparisons.CmpType", |
| 36 |
sizeof(CmpObject), |
| 37 |
0, |
| 38 |
0, |
| 39 |
0, |
| 40 |
0, |
| 41 |
0, |
| 42 |
0, |
| 43 |
0, |
| 44 |
0, |
| 45 |
0, |
| 46 |
0, |
| 47 |
cmp_hashfunc, |
| 48 |
0, |
| 49 |
0, |
| 50 |
0, |
| 51 |
0, |
| 52 |
0, |
| 53 |
Py_TPFLAGS_DEFAULT|Py_TPFLAGS_BASETYPE, |
| 54 |
0, |
| 55 |
(traverseproc)0, |
| 56 |
0, |
| 57 |
(richcmpfunc)cmp_richcmp, |
| 58 |
0, |
| 59 |
0, |
| 60 |
0, |
| 61 |
0, |
| 62 |
0, |
| 63 |
0, |
| 64 |
0, |
| 65 |
0, |
| 66 |
0, |
| 67 |
0, |
| 68 |
0, |
| 69 |
0, |
| 70 |
0, |
| 71 |
PyType_GenericNew, |
| 72 |
0 |
| 73 |
}; |
| 74 |
|
| 75 |
|
| 76 |
static struct PyModuleDef moduledef = { |
| 77 |
PyModuleDef_HEAD_INIT, |
| 78 |
"comparisons", |
| 79 |
"Module Doc", |
| 80 |
-1, |
| 81 |
NULL |
| 82 |
}; |
| 83 |
|
| 84 |
|
| 85 |
PyMODINIT_FUNC |
| 86 |
PyInit_comparisons(void) |
| 87 |
{ |
| 88 |
PyObject *m, *d; |
| 89 |
|
| 90 |
if (PyType_Ready(&CmpType) < 0) |
| 91 |
return NULL; |
| 92 |
m = PyModule_Create(&moduledef); |
| 93 |
if (m == NULL) |
| 94 |
return NULL; |
| 95 |
d = PyModule_GetDict(m); |
| 96 |
if (d == NULL) |
| 97 |
return NULL; |
| 98 |
if (PyDict_SetItemString(d, "CmpType", (PyObject *)&CmpType) < 0) |
| 99 |
return NULL; |
| 100 |
return m; |
| 101 |
} |