summaryrefslogtreecommitdiff
diff options
context:
space:
mode:
authorSerhiy Storchaka <storchaka@gmail.com>2019-01-12 09:22:29 +0200
committerGitHub <noreply@github.com>2019-01-12 09:22:29 +0200
commit44cc4822bb3799858201e61294c5863f93ec12e2 (patch)
treef7d25e8a7403e81d86893c8a2f7f5402297bd903
parentd0d3e99120b19a4b800f0f381b2807c93aeecf0e (diff)
downloadcpython-git-44cc4822bb3799858201e61294c5863f93ec12e2.tar.gz
bpo-33817: Fix _PyBytes_Resize() for empty bytes object. (GH-11516)
Add also tests for PyUnicode_FromFormat() and PyBytes_FromFormat() with empty result.
-rw-r--r--Lib/test/test_bytes.py6
-rw-r--r--Lib/test/test_unicode.py6
-rw-r--r--Misc/NEWS.d/next/C API/2019-01-11-11-16-16.bpo-33817.nJ4yIj.rst1
-rw-r--r--Objects/bytesobject.c13
4 files changed, 26 insertions, 0 deletions
diff --git a/Lib/test/test_bytes.py b/Lib/test/test_bytes.py
index cc433217ce..f7454d9b36 100644
--- a/Lib/test/test_bytes.py
+++ b/Lib/test/test_bytes.py
@@ -1001,6 +1001,12 @@ class BytesTest(BaseBytesTest, unittest.TestCase):
self.assertRaises(OverflowError,
PyBytes_FromFormat, b'%c', c_int(256))
+ # Issue #33817: empty strings
+ self.assertEqual(PyBytes_FromFormat(b''),
+ b'')
+ self.assertEqual(PyBytes_FromFormat(b'%s', b''),
+ b'')
+
def test_bytes_blocking(self):
class IterationBlocked(list):
__bytes__ = None
diff --git a/Lib/test/test_unicode.py b/Lib/test/test_unicode.py
index fb7bb2d523..c277e705b9 100644
--- a/Lib/test/test_unicode.py
+++ b/Lib/test/test_unicode.py
@@ -2680,6 +2680,12 @@ class CAPITest(unittest.TestCase):
check_format('%.%s',
b'%.%s', b'abc')
+ # Issue #33817: empty strings
+ check_format('',
+ b'')
+ check_format('',
+ b'%s', b'')
+
# Test PyUnicode_AsWideChar()
@support.cpython_only
def test_aswidechar(self):
diff --git a/Misc/NEWS.d/next/C API/2019-01-11-11-16-16.bpo-33817.nJ4yIj.rst b/Misc/NEWS.d/next/C API/2019-01-11-11-16-16.bpo-33817.nJ4yIj.rst
new file mode 100644
index 0000000000..ca4ccb26d3
--- /dev/null
+++ b/Misc/NEWS.d/next/C API/2019-01-11-11-16-16.bpo-33817.nJ4yIj.rst
@@ -0,0 +1 @@
+Fixed :c:func:`_PyBytes_Resize` for empty bytes objects.
diff --git a/Objects/bytesobject.c b/Objects/bytesobject.c
index adf0cff5f3..40ef47144e 100644
--- a/Objects/bytesobject.c
+++ b/Objects/bytesobject.c
@@ -2991,9 +2991,22 @@ _PyBytes_Resize(PyObject **pv, Py_ssize_t newsize)
/* return early if newsize equals to v->ob_size */
return 0;
}
+ if (Py_SIZE(v) == 0) {
+ if (newsize == 0) {
+ return 0;
+ }
+ *pv = _PyBytes_FromSize(newsize, 0);
+ Py_DECREF(v);
+ return (*pv == NULL) ? -1 : 0;
+ }
if (Py_REFCNT(v) != 1) {
goto error;
}
+ if (newsize == 0) {
+ *pv = _PyBytes_FromSize(0, 0);
+ Py_DECREF(v);
+ return (*pv == NULL) ? -1 : 0;
+ }
/* XXX UNREF/NEWREF interface should be more symmetrical */
_Py_DEC_REFTOTAL;
_Py_ForgetReference(v);