wchar_t *wchar;
char *bytes;
PyObject *bytes_obj;
+ size_t error_pos;
wchar = PyUnicode_AsWideCharString(unicode, NULL);
if (wchar == NULL)
return NULL;
- bytes = _Py_wchar2char(wchar);
- PyMem_Free(wchar);
- if (bytes == NULL)
+ bytes = _Py_wchar2char(wchar, &error_pos);
+ if (bytes == NULL) {
+ if (error_pos != (size_t)-1) {
+ char *errmsg = strerror(errno);
+ PyObject *exc = NULL;
+ if (errmsg == NULL)
+ errmsg = "Py_wchar2char() failed";
+ raise_encode_exception(&exc,
+ "filesystemencoding",
+ PyUnicode_AS_UNICODE(unicode), PyUnicode_GET_SIZE(unicode),
+ error_pos, error_pos+1,
+ errmsg);
+ Py_XDECREF(exc);
+ }
+ else
+ PyErr_NoMemory();
+ PyMem_Free(wchar);
return NULL;
+ }
+ PyMem_Free(wchar);
bytes_obj = PyBytes_FromString(bytes);
PyMem_Free(bytes);
This function is the reverse of _Py_char2wchar().
Return a pointer to a newly allocated byte string (use PyMem_Free() to free
- the memory), or NULL on error (conversion error or memory error). */
+ the memory), or NULL on conversion or memory allocation error.
+
+ If error_pos is not NULL: *error_pos is the index of the invalid character
+ on conversion error, or (size_t)-1 otherwise. */
char*
-_Py_wchar2char(const wchar_t *text)
+_Py_wchar2char(const wchar_t *text, size_t *error_pos)
{
const size_t len = wcslen(text);
char *result = NULL, *bytes = NULL;
size_t i, size, converted;
wchar_t c, buf[2];
+ if (error_pos != NULL)
+ *error_pos = (size_t)-1;
+
/* The function works in two steps:
1. compute the length of the output buffer in bytes (size)
2. outputs the bytes */
if (converted == (size_t)-1) {
if (result != NULL)
PyMem_Free(result);
+ if (error_pos != NULL)
+ *error_pos = i;
return NULL;
}
if (bytes != NULL) {
{
int err;
char *fname;
- fname = _Py_wchar2char(path);
+ fname = _Py_wchar2char(path, NULL);
if (fname == NULL) {
errno = EINVAL;
return -1;
errno = EINVAL;
return NULL;
}
- cpath = _Py_wchar2char(path);
+ cpath = _Py_wchar2char(path, NULL);
if (cpath == NULL)
return NULL;
f = fopen(cpath, cmode);
int res;
size_t r1;
- cpath = _Py_wchar2char(path);
+ cpath = _Py_wchar2char(path, NULL);
if (cpath == NULL) {
errno = EINVAL;
return -1;
wchar_t *wresolved_path;
char *res;
size_t r;
- cpath = _Py_wchar2char(path);
+ cpath = _Py_wchar2char(path, NULL);
if (cpath == NULL) {
errno = EINVAL;
return NULL;