__lt__()
__eq__()
memcmp()
bytes
Objects/bytesobject.c
C extension
#include <Python.h>
static PyObject* cmp(PyObject* self, PyObject* args) {
PyObject *a = 0, *b = 0;
if (!PyArg_UnpackTuple(args, "cmp", 2, 2, &a, &b))
return 0;
if (!PyBytes_Check(a) || !PyBytes_Check(b)) {
PyErr_SetString(PyExc_TypeError, "only bytes() strings supported");
return 0;
}
Py_ssize_t n = PyBytes_GET_SIZE(a), m = PyBytes_GET_SIZE(b);
char *s = PyBytes_AsString(a), *t = PyBytes_AsString(b);
int r = 0;
if (n == m) {
r = memcmp(s, t, n);
} else if (n < m) {
r = memcmp(s, t, n);
if (!r)
r = -1;
} else {
r = memcmp(s, t, m);
if (!r)
r = 1;
}
return PyLong_FromLong(r);
}
static PyMethodDef bytes_util_methods[] = {
{ "cmp", cmp, METH_VARARGS, "Three way compare 2 bytes() objects." },
{0,0,0,0} };
static struct PyModuleDef bytes_util_def = {
PyModuleDef_HEAD_INIT, "bytes_util", "Three way comparison for strings.",
-1, bytes_util_methods };
PyMODINIT_FUNC PyInit_bytes_util(void) {
Py_Initialize();
return PyModule_Create(&bytes_util_def);
}
gcc -Wall -O3 -fPIC -shared bytes_util.c -o bytes_util.so -I/usr/include/python3.6m
>>> import bytes_util
>>> bytes_util.cmp(b'foo', b'barx')
265725
memcmp
ctypes