Skip to content

Commit a4a7595

Browse files
author
Victor Stinner
committed
_Py_stat() and _Py_fopen(): avoid PyUnicode_AsWideCharString() on Windows
On Windows, Py_UNICODE is wchar_t, so we can avoid the expensive Py_UNICODE* => wchar_t* conversion.
1 parent b306d75 commit a4a7595

2 files changed

Lines changed: 8 additions & 20 deletions

File tree

Include/fileutils.h

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -19,7 +19,7 @@ PyAPI_FUNC(int) _Py_wstat(
1919

2020
#ifdef HAVE_STAT
2121
PyAPI_FUNC(int) _Py_stat(
22-
PyObject *unicode,
22+
PyObject *path,
2323
struct stat *statbuf);
2424
#endif
2525

@@ -28,7 +28,7 @@ PyAPI_FUNC(FILE *) _Py_wfopen(
2828
const wchar_t *mode);
2929

3030
PyAPI_FUNC(FILE*) _Py_fopen(
31-
PyObject *unicode,
31+
PyObject *path,
3232
const char *mode);
3333

3434
#ifdef HAVE_READLINK

Python/fileutils.c

Lines changed: 6 additions & 18 deletions
Original file line numberDiff line numberDiff line change
@@ -215,24 +215,19 @@ _Py_wstat(const wchar_t* path, struct stat *buf)
215215
PyErr_Occurred()) unicode error. */
216216

217217
int
218-
_Py_stat(PyObject *unicode, struct stat *statbuf)
218+
_Py_stat(PyObject *path, struct stat *statbuf)
219219
{
220220
#ifdef MS_WINDOWS
221-
wchar_t *path;
222221
int err;
223222
struct _stat wstatbuf;
224223

225-
path = PyUnicode_AsWideCharString(unicode, NULL);
226-
if (path == NULL)
227-
return -1;
228-
err = _wstat(path, &wstatbuf);
229-
PyMem_Free(path);
224+
err = _wstat(PyUnicode_AS_UNICODE(path), &wstatbuf);
230225
if (!err)
231226
statbuf->st_mode = wstatbuf.st_mode;
232227
return err;
233228
#else
234229
int ret;
235-
PyObject *bytes = PyUnicode_EncodeFSDefault(unicode);
230+
PyObject *bytes = PyUnicode_EncodeFSDefault(path);
236231
if (bytes == NULL)
237232
return -1;
238233
ret = stat(PyBytes_AS_STRING(bytes), statbuf);
@@ -270,27 +265,20 @@ _Py_wfopen(const wchar_t *path, const wchar_t *mode)
270265
PyErr_Occurred()) on unicode error */
271266

272267
FILE*
273-
_Py_fopen(PyObject *unicode, const char *mode)
268+
_Py_fopen(PyObject *path, const char *mode)
274269
{
275270
#ifdef MS_WINDOWS
276-
wchar_t *path;
277271
wchar_t wmode[10];
278272
int usize;
279-
FILE *f;
280273

281274
usize = MultiByteToWideChar(CP_ACP, 0, mode, -1, wmode, sizeof(wmode));
282275
if (usize == 0)
283276
return NULL;
284277

285-
path = PyUnicode_AsWideCharString(unicode, NULL);
286-
if (path == NULL)
287-
return NULL;
288-
f = _wfopen(path, wmode);
289-
PyMem_Free(path);
290-
return f;
278+
return _wfopen(PyUnicode_AS_UNICODE(path), wmode);
291279
#else
292280
FILE *f;
293-
PyObject *bytes = PyUnicode_EncodeFSDefault(unicode);
281+
PyObject *bytes = PyUnicode_EncodeFSDefault(path);
294282
if (bytes == NULL)
295283
return NULL;
296284
f = fopen(PyBytes_AS_STRING(bytes), mode);

0 commit comments

Comments
 (0)