blob: 028f187c707cdd58da21daa649751cd2ef0776bb [file] [log] [blame]
Gregory P. Smithe3f63932015-04-26 00:41:00 +00001/* bytes to hex implementation */
2
3#include "Python.h"
4
Benjamin Petersone5024512018-09-12 12:06:42 -07005#include "pystrhex.h"
6
Gregory P. Smithe3f63932015-04-26 00:41:00 +00007static 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 Storchaka598ceae2017-11-28 17:56:10 +020021 if (!retbuf)
22 return PyErr_NoMemory();
Gregory P. Smithf7894652015-04-25 23:51:39 -070023 retval = NULL; /* silence a compiler warning, assigned later. */
Gregory P. Smithe3f63932015-04-26 00:41:00 +000024 } else {
Serhiy Storchaka598ceae2017-11-28 17:56:10 +020025 retval = PyUnicode_New(arglen*2, 127);
26 if (!retval)
27 return NULL;
28 retbuf = PyUnicode_1BYTE_DATA(retval);
Gregory P. Smithe3f63932015-04-26 00:41:00 +000029 }
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 Petersone5024512018-09-12 12:06:42 -070053PyObject * _Py_strhex(const char* argbuf, const Py_ssize_t arglen)
Gregory P. Smithe3f63932015-04-26 00:41:00 +000054{
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 Petersone5024512018-09-12 12:06:42 -070060PyObject * _Py_strhex_bytes(const char* argbuf, const Py_ssize_t arglen)
Gregory P. Smithe3f63932015-04-26 00:41:00 +000061{
62 return _Py_strhex_impl(argbuf, arglen, 1);
63}