Skip to content

Commit 71133ff

Browse files
author
Victor Stinner
committed
Create PyUnicode_strdup() function
1 parent c4eb765 commit 71133ff

2 files changed

Lines changed: 32 additions & 1 deletion

File tree

Include/unicodeobject.h

Lines changed: 10 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -220,6 +220,7 @@ typedef PY_UNICODE_TYPE Py_UNICODE;
220220
# define _PyUnicode_AsDefaultEncodedString _PyUnicodeUCS2_AsDefaultEncodedString
221221
# define _PyUnicode_Fini _PyUnicodeUCS2_Fini
222222
# define _PyUnicode_Init _PyUnicodeUCS2_Init
223+
# define PyUnicode_strdup PyUnicodeUCS2_strdup
223224

224225
#else
225226

@@ -302,7 +303,7 @@ typedef PY_UNICODE_TYPE Py_UNICODE;
302303
# define _PyUnicode_AsDefaultEncodedString _PyUnicodeUCS4_AsDefaultEncodedString
303304
# define _PyUnicode_Fini _PyUnicodeUCS4_Fini
304305
# define _PyUnicode_Init _PyUnicodeUCS4_Init
305-
306+
# define PyUnicode_strdup PyUnicodeUCS4_strdup
306307

307308
#endif
308309

@@ -1602,6 +1603,14 @@ PyAPI_FUNC(Py_UNICODE*) Py_UNICODE_strrchr(
16021603
Py_UNICODE c
16031604
);
16041605

1606+
/* Create a copy of a unicode string ending with a nul character. Return NULL
1607+
and raise a MemoryError exception on memory allocation failure, otherwise
1608+
return a new allocated buffer (use PyMem_Free() to free the buffer). */
1609+
1610+
PyAPI_FUNC(Py_UNICODE*) PyUnicode_strdup(
1611+
PyObject *unicode
1612+
);
1613+
16051614
#ifdef __cplusplus
16061615
}
16071616
#endif

Objects/unicodeobject.c

Lines changed: 22 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -10014,6 +10014,28 @@ Py_UNICODE_strrchr(const Py_UNICODE *s, Py_UNICODE c)
1001410014
return NULL;
1001510015
}
1001610016

10017+
Py_UNICODE*
10018+
PyUnicode_strdup(PyObject *object)
10019+
{
10020+
PyUnicodeObject *unicode = (PyUnicodeObject *)object;
10021+
Py_UNICODE *copy;
10022+
Py_ssize_t size;
10023+
10024+
/* Ensure we won't overflow the size. */
10025+
if (PyUnicode_GET_SIZE(unicode) > ((PY_SSIZE_T_MAX / sizeof(Py_UNICODE)) - 1)) {
10026+
PyErr_NoMemory();
10027+
return NULL;
10028+
}
10029+
size = PyUnicode_GET_SIZE(unicode) + 1; /* copy the nul character */
10030+
size *= sizeof(Py_UNICODE);
10031+
copy = PyMem_Malloc(size);
10032+
if (copy == NULL) {
10033+
PyErr_NoMemory();
10034+
return NULL;
10035+
}
10036+
memcpy(copy, PyUnicode_AS_UNICODE(unicode), size);
10037+
return copy;
10038+
}
1001710039

1001810040
#ifdef __cplusplus
1001910041
}

0 commit comments

Comments
 (0)