[2.7] bpo-33817: Fix _PyString_Resize() and _PyUnicode_Resize() for empty strings. by serhiy-storchaka · Pull Request #11515 · python/cpython · GitHub
Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
100 changes: 99 additions & 1 deletion Lib/test/test_str.py
6 changes: 6 additions & 0 deletions Lib/test/test_unicode.py
Original file line number Diff line number Diff line change
Expand Up @@ -1824,6 +1824,12 @@ def check_format(expected, format, *args):
check_format(u'%s',
b'%.%s', b'abc')

# Issue #33817: empty strings
check_format(u'',
b'')
check_format(u'',
b'%s', b'')

@test_support.cpython_only
def test_encode_decimal(self):
from _testcapi import unicode_encodedecimal
Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,4 @@
Fixed :c:func:`_PyString_Resize` and :c:func:`_PyUnicode_Resize` for empty
strings. This fixed also :c:func:`PyString_FromFormat` and
:c:func:`PyUnicode_FromFormat` when they return an empty string (e.g.
``PyString_FromFormat("%s", "")``).
22 changes: 20 additions & 2 deletions Objects/stringobject.c
Original file line number Diff line number Diff line change
Expand Up @@ -3893,13 +3893,31 @@ _PyString_Resize(PyObject **pv, Py_ssize_t newsize)
register PyObject *v;
register PyStringObject *sv;
v = *pv;
if (!PyString_Check(v) || Py_REFCNT(v) != 1 || newsize < 0 ||
PyString_CHECK_INTERNED(v)) {
if (!PyString_Check(v) || newsize < 0) {
*pv = 0;
Py_DECREF(v);
PyErr_BadInternalCall();
return -1;
}
if (Py_SIZE(v) == 0) {
if (newsize == 0) {
return 0;
}
*pv = PyString_FromStringAndSize(NULL, newsize);
Py_DECREF(v);
return (*pv == NULL) ? -1 : 0;
}
if (Py_REFCNT(v) != 1 || PyString_CHECK_INTERNED(v)) {
*pv = 0;
Py_DECREF(v);
PyErr_BadInternalCall();
return -1;
}
if (newsize == 0) {
*pv = PyString_FromStringAndSize(NULL, 0);
Py_DECREF(v);
return (*pv == NULL) ? -1 : 0;
}
/* XXX UNREF/NEWREF interface should be more symmetrical */
_Py_DEC_REFTOTAL;
_Py_ForgetReference(v);
Expand Down
19 changes: 18 additions & 1 deletion Objects/unicodeobject.c