@@ -939,6 +939,79 @@ PyThreadState_GetUnchecked(void)
939939}
940940#endif
941941
942+ // gh-110289 added PyUnicode_EqualToUTF8() and PyUnicode_EqualToUTF8AndSize()
943+ // to Python 3.13.0a1
944+ #if PY_VERSION_HEX < 0x030D00A1
945+ static inline int
946+ PyUnicode_EqualToUTF8AndSize (PyObject *unicode, const char *str, Py_ssize_t str_len)
947+ {
948+ Py_ssize_t len;
949+ const void *utf8;
950+ PyObject *exc_type, *exc_value, *exc_tb;
951+ int res;
952+
953+ // API cannot report errors so save/restore the exception
954+ PyErr_Fetch (&exc_type, &exc_value, &exc_tb);
955+
956+ // Python 3.3.0a1 added PyUnicode_AsUTF8AndSize()
957+ #if PY_VERSION_HEX >= 0x030300A1
958+ if (PyUnicode_IS_ASCII (unicode)) {
959+ utf8 = PyUnicode_DATA (unicode);
960+ len = PyUnicode_GET_LENGTH (unicode);
961+ }
962+ else {
963+ utf8 = PyUnicode_AsUTF8AndSize (unicode, &len);
964+ if (utf8 == NULL ) {
965+ // Memory allocation failure. The API cannot report error,
966+ // so ignore the exception and return 0.
967+ res = 0 ;
968+ goto done;
969+ }
970+ }
971+
972+ if (len != str_len) {
973+ res = 0 ;
974+ goto done;
975+ }
976+ res = (memcmp (utf8, str, (size_t )len) == 0 );
977+ #else
978+ PyObject *bytes = PyUnicode_AsUTF8String (unicode);
979+ if (bytes == NULL ) {
980+ // Memory allocation failure. The API cannot report error,
981+ // so ignore the exception and return 0.
982+ res = 0 ;
983+ goto done;
984+ }
985+
986+ #if PY_VERSION_HEX >= 0x03000000
987+ len = PyBytes_GET_SIZE (bytes);
988+ utf8 = PyBytes_AS_STRING (bytes);
989+ #else
990+ len = PyString_GET_SIZE (bytes);
991+ utf8 = PyString_AS_STRING (bytes);
992+ #endif
993+ if (len != str_len) {
994+ Py_DECREF (bytes);
995+ res = 0 ;
996+ goto done;
997+ }
998+
999+ res = (memcmp (utf8, str, (size_t )len) == 0 );
1000+ Py_DECREF (bytes);
1001+ #endif
1002+
1003+ done:
1004+ PyErr_Restore (exc_type, exc_value, exc_tb);
1005+ return res;
1006+ }
1007+
1008+ static inline int
1009+ PyUnicode_EqualToUTF8 (PyObject *unicode, const char *str)
1010+ {
1011+ return PyUnicode_EqualToUTF8AndSize (unicode, str, (Py_ssize_t)strlen (str));
1012+ }
1013+ #endif
1014+
9421015
9431016#ifdef __cplusplus
9441017}
0 commit comments