Thanks to visit codestin.com
Credit goes to github.com

Skip to content

Commit 81c39a8

Browse files
committed
get_sourcefile(): use PyUnicode_READ() to avoid the creation of a temporary
Py_UCS4 buffer
1 parent ca439ee commit 81c39a8

1 file changed

Lines changed: 11 additions & 12 deletions

File tree

Python/import.c

Lines changed: 11 additions & 12 deletions
Original file line numberDiff line numberDiff line change
@@ -1008,23 +1008,25 @@ static PyObject *
10081008
get_sourcefile(PyObject *filename)
10091009
{
10101010
Py_ssize_t len;
1011-
Py_UCS4 *fileuni;
10121011
PyObject *py;
10131012
struct stat statbuf;
10141013
int err;
1014+
void *data;
1015+
unsigned int kind;
10151016

10161017
len = PyUnicode_GET_LENGTH(filename);
10171018
if (len == 0)
10181019
Py_RETURN_NONE;
10191020

10201021
/* don't match *.pyc or *.pyo? */
1021-
fileuni = PyUnicode_AsUCS4Copy(filename);
1022-
if (!fileuni)
1023-
return NULL;
1022+
data = PyUnicode_DATA(filename);
1023+
kind = PyUnicode_KIND(filename);
10241024
if (len < 5
1025-
|| fileuni[len-4] != '.'
1026-
|| (fileuni[len-3] != 'p' && fileuni[len-3] != 'P')
1027-
|| (fileuni[len-2] != 'y' && fileuni[len-2] != 'Y'))
1025+
|| PyUnicode_READ(kind, data, len-4) != '.'
1026+
|| (PyUnicode_READ(kind, data, len-3) != 'p'
1027+
&& PyUnicode_READ(kind, data, len-3) != 'P')
1028+
|| (PyUnicode_READ(kind, data, len-2) != 'y'
1029+
&& PyUnicode_READ(kind, data, len-2) != 'Y'))
10281030
goto unchanged;
10291031

10301032
/* Start by trying to turn PEP 3147 path into source path. If that
@@ -1034,25 +1036,22 @@ get_sourcefile(PyObject *filename)
10341036
py = make_source_pathname(filename);
10351037
if (py == NULL) {
10361038
PyErr_Clear();
1037-
py = PyUnicode_FromKindAndData(PyUnicode_4BYTE_KIND, fileuni, len - 1);
1039+
py = PyUnicode_Substring(filename, 0, len - 1);
10381040
}
10391041
if (py == NULL)
10401042
goto error;
10411043

10421044
err = _Py_stat(py, &statbuf);
10431045
if (err == -2)
10441046
goto error;
1045-
if (err == 0 && S_ISREG(statbuf.st_mode)) {
1046-
PyMem_Free(fileuni);
1047+
if (err == 0 && S_ISREG(statbuf.st_mode))
10471048
return py;
1048-
}
10491049
Py_DECREF(py);
10501050
goto unchanged;
10511051

10521052
error:
10531053
PyErr_Clear();
10541054
unchanged:
1055-
PyMem_Free(fileuni);
10561055
Py_INCREF(filename);
10571056
return filename;
10581057
}

0 commit comments

Comments
 (0)