| 1 |
#include "pycurl.h" |
| 2 |
|
| 3 |
/************************************************************************* |
| 4 |
// python utility functions |
| 5 |
**************************************************************************/ |
| 6 |
|
| 7 |
PYCURL_INTERNAL int |
| 8 |
PyText_AsStringAndSize(PyObject *obj, char **buffer, Py_ssize_t *length, PyObject **encoded_obj) |
| 9 |
{ |
| 10 |
if (PyBytes_Check(obj)) { |
| 11 |
*encoded_obj = NULL; |
| 12 |
return PyBytes_AsStringAndSize(obj, buffer, length); |
| 13 |
} else { |
| 14 |
int rv; |
| 15 |
assert(PyUnicode_Check(obj)); |
| 16 |
*encoded_obj = PyUnicode_AsEncodedString(obj, "ascii", "strict"); |
| 17 |
if (*encoded_obj == NULL) { |
| 18 |
return -1; |
| 19 |
} |
| 20 |
rv = PyBytes_AsStringAndSize(*encoded_obj, buffer, length); |
| 21 |
if (rv != 0) { |
| 22 |
/* If we free the object, pointer must be reset to NULL */ |
| 23 |
Py_CLEAR(*encoded_obj); |
| 24 |
} |
| 25 |
return rv; |
| 26 |
} |
| 27 |
} |
| 28 |
|
| 29 |
|
| 30 |
/* Like PyBytes_AsString(), but set an exception if the string contains |
| 31 |
* embedded NULs. |
| 32 |
*/ |
| 33 |
|
| 34 |
PYCURL_INTERNAL char * |
| 35 |
PyText_AsString_NoNUL(PyObject *obj, PyObject **encoded_obj) |
| 36 |
{ |
| 37 |
char *s = NULL; |
| 38 |
Py_ssize_t r; |
| 39 |
r = PyText_AsStringAndSize(obj, &s, NULL, encoded_obj); |
| 40 |
if (r != 0) |
| 41 |
return NULL; /* exception already set */ |
| 42 |
assert(s != NULL); |
| 43 |
return s; |
| 44 |
} |
| 45 |
|
| 46 |
|
| 47 |
/* Returns true if the object is of a type that can be given to |
| 48 |
* curl_easy_setopt and such - either a byte string or a Unicode string |
| 49 |
* with ASCII code points only. |
| 50 |
*/ |
| 51 |
PYCURL_INTERNAL int |
| 52 |
PyText_Check(PyObject *o) |
| 53 |
{ |
| 54 |
return PyUnicode_Check(o) || PyBytes_Check(o); |
| 55 |
} |
| 56 |
|
| 57 |
PYCURL_INTERNAL PyObject * |
| 58 |
PyText_FromString_Ignore(const char *string) |
| 59 |
{ |
| 60 |
PyObject *v; |
| 61 |
PyObject *u; |
| 62 |
|
| 63 |
v = Py_BuildValue("y", string); |
| 64 |
if (v == NULL) { |
| 65 |
return NULL; |
| 66 |
} |
| 67 |
|
| 68 |
u = PyUnicode_FromEncodedObject(v, NULL, "replace"); |
| 69 |
Py_DECREF(v); |
| 70 |
return u; |
| 71 |
} |