@@ -221,10 +221,15 @@ unicode_copycharacters(PyObject *self, PyObject *args)
221221}
222222
223223static PyObject *
224- unicode_case_operation (PyObject * str , int (* function )(Py_UCS4 , Py_UCS4 * , int ), const char * name )
224+ unicode_case_operation (PyObject * str , int (* function )(Py_UCS4 , Py_UCS4 * , int ))
225225{
226+ if (!PyUnicode_Check (str )) {
227+ PyErr_Format (PyExc_TypeError , "expect str type, got %T" , str );
228+ return NULL ;
229+ }
230+
226231 if (PyUnicode_GET_LENGTH (str ) != 1 ) {
227- PyErr_Format (PyExc_ValueError , "%s only accepts 1-character strings" , name );
232+ PyErr_SetString (PyExc_ValueError , "expecting 1-character strings only" );
228233 return NULL ;
229234 }
230235
@@ -233,48 +238,39 @@ unicode_case_operation(PyObject *str, int (*function)(Py_UCS4, Py_UCS4 *, int),
233238 Py_UCS4 buf [3 ];
234239 int chars = function (c , buf , Py_ARRAY_LENGTH (buf ));
235240 if (chars <= 0 ) {
236- PyErr_BadInternalCall ();
237241 return NULL ;
238242 }
239243
240- PyUnicodeWriter * writer = PyUnicodeWriter_Create (1 );
241- if (writer == NULL ) {
242- return NULL ;
243- }
244- if (PyUnicodeWriter_WriteUCS4 (writer , buf , chars ) < 0 ) {
245- PyUnicodeWriter_Discard (writer );
246- return NULL ;
247- }
248- return PyUnicodeWriter_Finish (writer );
244+ return PyUnicode_FromKindAndData (PyUnicode_4BYTE_KIND , buf , chars );
249245}
250246
251247/* Test PyUnicode_ToLower() */
252248static PyObject *
253249unicode_tolower (PyObject * self , PyObject * arg )
254250{
255- return unicode_case_operation (arg , PyUnicode_ToLower , "unicode_tolower" );
251+ return unicode_case_operation (arg , PyUnicode_ToLower );
256252}
257253
258254/* Test PyUnicode_ToUpper() */
259255static PyObject *
260256unicode_toupper (PyObject * self , PyObject * arg )
261257{
262- return unicode_case_operation (arg , PyUnicode_ToUpper , "unicode_toupper" );
258+ return unicode_case_operation (arg , PyUnicode_ToUpper );
263259}
264260
265261
266262/* Test PyUnicode_ToLower() */
267263static PyObject *
268264unicode_totitle (PyObject * self , PyObject * arg )
269265{
270- return unicode_case_operation (arg , PyUnicode_ToTitle , "unicode_totitle" );
266+ return unicode_case_operation (arg , PyUnicode_ToTitle );
271267}
272268
273269/* Test PyUnicode_ToLower() */
274270static PyObject *
275271unicode_tofolded (PyObject * self , PyObject * arg )
276272{
277- return unicode_case_operation (arg , PyUnicode_ToFolded , "unicode_tofolded" );
273+ return unicode_case_operation (arg , PyUnicode_ToFolded );
278274}
279275
280276
0 commit comments