Gregory P. Smith | e3f6393 | 2015-04-26 00:41:00 +0000 | [diff] [blame] | 1 | /* bytes to hex implementation */ |
| 2 | |
| 3 | #include "Python.h" |
| 4 | |
Benjamin Peterson | e502451 | 2018-09-12 12:06:42 -0700 | [diff] [blame] | 5 | #include "pystrhex.h" |
| 6 | |
Gregory P. Smith | e3f6393 | 2015-04-26 00:41:00 +0000 | [diff] [blame] | 7 | static PyObject *_Py_strhex_impl(const char* argbuf, const Py_ssize_t arglen, |
| 8 | int return_bytes) |
| 9 | { |
| 10 | PyObject *retval; |
| 11 | Py_UCS1* retbuf; |
| 12 | Py_ssize_t i, j; |
| 13 | |
| 14 | assert(arglen >= 0); |
| 15 | if (arglen > PY_SSIZE_T_MAX / 2) |
| 16 | return PyErr_NoMemory(); |
| 17 | |
| 18 | if (return_bytes) { |
| 19 | /* If _PyBytes_FromSize() were public we could avoid malloc+copy. */ |
| 20 | retbuf = (Py_UCS1*) PyMem_Malloc(arglen*2); |
Serhiy Storchaka | 598ceae | 2017-11-28 17:56:10 +0200 | [diff] [blame] | 21 | if (!retbuf) |
| 22 | return PyErr_NoMemory(); |
Gregory P. Smith | f789465 | 2015-04-25 23:51:39 -0700 | [diff] [blame] | 23 | retval = NULL; /* silence a compiler warning, assigned later. */ |
Gregory P. Smith | e3f6393 | 2015-04-26 00:41:00 +0000 | [diff] [blame] | 24 | } else { |
Serhiy Storchaka | 598ceae | 2017-11-28 17:56:10 +0200 | [diff] [blame] | 25 | retval = PyUnicode_New(arglen*2, 127); |
| 26 | if (!retval) |
| 27 | return NULL; |
| 28 | retbuf = PyUnicode_1BYTE_DATA(retval); |
Gregory P. Smith | e3f6393 | 2015-04-26 00:41:00 +0000 | [diff] [blame] | 29 | } |
| 30 | |
| 31 | /* make hex version of string, taken from shamodule.c */ |
| 32 | for (i=j=0; i < arglen; i++) { |
| 33 | unsigned char c; |
| 34 | c = (argbuf[i] >> 4) & 0xf; |
| 35 | retbuf[j++] = Py_hexdigits[c]; |
| 36 | c = argbuf[i] & 0xf; |
| 37 | retbuf[j++] = Py_hexdigits[c]; |
| 38 | } |
| 39 | |
| 40 | if (return_bytes) { |
| 41 | retval = PyBytes_FromStringAndSize((const char *)retbuf, arglen*2); |
| 42 | PyMem_Free(retbuf); |
| 43 | } |
| 44 | #ifdef Py_DEBUG |
| 45 | else { |
| 46 | assert(_PyUnicode_CheckConsistency(retval, 1)); |
| 47 | } |
| 48 | #endif |
| 49 | |
| 50 | return retval; |
| 51 | } |
| 52 | |
Benjamin Peterson | e502451 | 2018-09-12 12:06:42 -0700 | [diff] [blame] | 53 | PyObject * _Py_strhex(const char* argbuf, const Py_ssize_t arglen) |
Gregory P. Smith | e3f6393 | 2015-04-26 00:41:00 +0000 | [diff] [blame] | 54 | { |
| 55 | return _Py_strhex_impl(argbuf, arglen, 0); |
| 56 | } |
| 57 | |
| 58 | /* Same as above but returns a bytes() instead of str() to avoid the |
| 59 | * need to decode the str() when bytes are needed. */ |
Benjamin Peterson | e502451 | 2018-09-12 12:06:42 -0700 | [diff] [blame] | 60 | PyObject * _Py_strhex_bytes(const char* argbuf, const Py_ssize_t arglen) |
Gregory P. Smith | e3f6393 | 2015-04-26 00:41:00 +0000 | [diff] [blame] | 61 | { |
| 62 | return _Py_strhex_impl(argbuf, arglen, 1); |
| 63 | } |