| 1 |
#include "bytes_extra_ops.h" |
| 2 |
|
| 3 |
PyObject *CPyBytes_Translate(PyObject *bytes, PyObject *table) { |
| 4 |
// Fast path: exact bytes object with exact bytes table |
| 5 |
if (PyBytes_CheckExact(bytes) && PyBytes_CheckExact(table)) { |
| 6 |
Py_ssize_t table_len = PyBytes_GET_SIZE(table); |
| 7 |
if (table_len != 256) { |
| 8 |
PyErr_SetString(PyExc_ValueError, |
| 9 |
"translation table must be 256 characters long"); |
| 10 |
return NULL; |
| 11 |
} |
| 12 |
|
| 13 |
Py_ssize_t len = PyBytes_GET_SIZE(bytes); |
| 14 |
const char *input = PyBytes_AS_STRING(bytes); |
| 15 |
const char *trans_table = PyBytes_AS_STRING(table); |
| 16 |
|
| 17 |
PyObject *result = PyBytes_FromStringAndSize(NULL, len); |
| 18 |
if (result == NULL) { |
| 19 |
return NULL; |
| 20 |
} |
| 21 |
|
| 22 |
char *output = PyBytes_AS_STRING(result); |
| 23 |
bool changed = false; |
| 24 |
|
| 25 |
// Without a loop unrolling hint performance can be worse than CPython |
| 26 |
CPY_UNROLL_LOOP(4) |
| 27 |
for (Py_ssize_t i = len; --i >= 0;) { |
| 28 |
char c = *input++; |
| 29 |
if ((*output++ = trans_table[(unsigned char)c]) != c) |
| 30 |
changed = true; |
| 31 |
} |
| 32 |
|
| 33 |
// If nothing changed, discard result and return the original object |
| 34 |
if (!changed) { |
| 35 |
Py_DECREF(result); |
| 36 |
Py_INCREF(bytes); |
| 37 |
return bytes; |
| 38 |
} |
| 39 |
|
| 40 |
return result; |
| 41 |
} |
| 42 |
|
| 43 |
// Fallback to Python method call for non-exact types or non-standard tables |
| 44 |
return PyObject_CallMethodOneArg(bytes, mypyc_interned_str.translate, table); |
| 45 |
} |