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