]> git.ipfire.org Git - thirdparty/Python/cpython.git/commitdiff
Create PyUnicode_strdup() function
authorVictor Stinner <victor.stinner@haypocalc.com>
Wed, 1 Sep 2010 23:43:53 +0000 (23:43 +0000)
committerVictor Stinner <victor.stinner@haypocalc.com>
Wed, 1 Sep 2010 23:43:53 +0000 (23:43 +0000)
Include/unicodeobject.h
Objects/unicodeobject.c

index afef5d0ff107a7de1218afd11559dccbc5621bc7..b6a7fcafb9784bef27002663f0d27d2c72768ad7 100644 (file)
@@ -220,6 +220,7 @@ typedef PY_UNICODE_TYPE Py_UNICODE;
 # define _PyUnicode_AsDefaultEncodedString _PyUnicodeUCS2_AsDefaultEncodedString
 # define _PyUnicode_Fini _PyUnicodeUCS2_Fini
 # define _PyUnicode_Init _PyUnicodeUCS2_Init
+# define PyUnicode_strdup PyUnicodeUCS2_strdup
 
 #else
 
@@ -302,7 +303,7 @@ typedef PY_UNICODE_TYPE Py_UNICODE;
 # define _PyUnicode_AsDefaultEncodedString _PyUnicodeUCS4_AsDefaultEncodedString
 # define _PyUnicode_Fini _PyUnicodeUCS4_Fini
 # define _PyUnicode_Init _PyUnicodeUCS4_Init
-
+# define PyUnicode_strdup PyUnicodeUCS4_strdup
 
 #endif
 
@@ -1602,6 +1603,14 @@ PyAPI_FUNC(Py_UNICODE*) Py_UNICODE_strrchr(
     Py_UNICODE c
     );
 
+/* Create a copy of a unicode string ending with a nul character. Return NULL
+   and raise a MemoryError exception on memory allocation failure, otherwise
+   return a new allocated buffer (use PyMem_Free() to free the buffer). */
+
+PyAPI_FUNC(Py_UNICODE*) PyUnicode_strdup(
+    PyObject *unicode
+    );
+
 #ifdef __cplusplus
 }
 #endif
index 95823ad827a0b3b6a6a0204e87169f612b6fbc91..80e2e63fce28f0cb3e04558360936885e5af81e6 100644 (file)
@@ -10014,6 +10014,28 @@ Py_UNICODE_strrchr(const Py_UNICODE *s, Py_UNICODE c)
     return NULL;
 }
 
+Py_UNICODE*
+PyUnicode_strdup(PyObject *object)
+{
+    PyUnicodeObject *unicode = (PyUnicodeObject *)object;
+    Py_UNICODE *copy;
+    Py_ssize_t size;
+
+    /* Ensure we won't overflow the size. */
+    if (PyUnicode_GET_SIZE(unicode) > ((PY_SSIZE_T_MAX / sizeof(Py_UNICODE)) - 1)) {
+        PyErr_NoMemory();
+        return NULL;
+    }
+    size = PyUnicode_GET_SIZE(unicode) + 1; /* copy the nul character */
+    size *= sizeof(Py_UNICODE);
+    copy = PyMem_Malloc(size);
+    if (copy == NULL) {
+        PyErr_NoMemory();
+        return NULL;
+    }
+    memcpy(copy, PyUnicode_AS_UNICODE(unicode), size);
+    return copy;
+}
 
 #ifdef __cplusplus
 }