summaryrefslogtreecommitdiffstats
path: root/Modules/_tkinter.c
diff options
context:
space:
mode:
Diffstat (limited to 'Modules/_tkinter.c')
-rw-r--r--Modules/_tkinter.c40
1 files changed, 33 insertions, 7 deletions
diff --git a/Modules/_tkinter.c b/Modules/_tkinter.c
index 8fe2c5b..cd3722f 100644
--- a/Modules/_tkinter.c
+++ b/Modules/_tkinter.c
@@ -512,7 +512,7 @@ unicodeFromTclObj(TkappObject *tkapp, Tcl_Obj *value)
else
Py_UNREACHABLE();
}
-#endif
+#endif /* USE_TCL_UNICODE */
const char *s = Tcl_GetStringFromObj(value, &len);
return unicodeFromTclStringAndSize(s, len);
}
@@ -1018,7 +1018,9 @@ AsObj(PyObject *value)
PyErr_SetString(PyExc_OverflowError, "string is too long");
return NULL;
}
- if (PyUnicode_IS_ASCII(value)) {
+ if (PyUnicode_IS_ASCII(value) &&
+ strlen(PyUnicode_DATA(value)) == (size_t)PyUnicode_GET_LENGTH(value))
+ {
return Tcl_NewStringObj((const char *)PyUnicode_DATA(value),
(int)size);
}
@@ -1033,9 +1035,6 @@ AsObj(PyObject *value)
"surrogatepass", NATIVE_BYTEORDER);
else
Py_UNREACHABLE();
-#else
- encoded = _PyUnicode_AsUTF8String(value, "surrogateescape");
-#endif
if (!encoded) {
return NULL;
}
@@ -1045,12 +1044,39 @@ AsObj(PyObject *value)
PyErr_SetString(PyExc_OverflowError, "string is too long");
return NULL;
}
-#if USE_TCL_UNICODE
result = Tcl_NewUnicodeObj((const Tcl_UniChar *)PyBytes_AS_STRING(encoded),
(int)(size / sizeof(Tcl_UniChar)));
#else
+ encoded = _PyUnicode_AsUTF8String(value, "surrogateescape");
+ if (!encoded) {
+ return NULL;
+ }
+ size = PyBytes_GET_SIZE(encoded);
+ if (strlen(PyBytes_AS_STRING(encoded)) != (size_t)size) {
+ /* The string contains embedded null characters.
+ * Tcl needs a null character to be represented as \xc0\x80 in
+ * the Modified UTF-8 encoding. Otherwise the string can be
+ * truncated in some internal operations.
+ *
+ * NOTE: stringlib_replace() could be used here, but optimizing
+ * this obscure case isn't worth it unless stringlib_replace()
+ * was already exposed in the C API for other reasons. */
+ Py_SETREF(encoded,
+ PyObject_CallMethod(encoded, "replace", "y#y#",
+ "\0", (Py_ssize_t)1,
+ "\xc0\x80", (Py_ssize_t)2));
+ if (!encoded) {
+ return NULL;
+ }
+ size = PyBytes_GET_SIZE(encoded);
+ }
+ if (size > INT_MAX) {
+ Py_DECREF(encoded);
+ PyErr_SetString(PyExc_OverflowError, "string is too long");
+ return NULL;
+ }
result = Tcl_NewStringObj(PyBytes_AS_STRING(encoded), (int)size);
-#endif
+#endif /* USE_TCL_UNICODE */
Py_DECREF(encoded);
return result;
}