ยปCore Development>Code coverage>Python/pystrhex.c

Python code coverage for Python/pystrhex.c

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