Skip to content

Commit f255ad7

Browse files
vstinnermiss-islington
authored andcommitted
gh-128509: Use bytes singletons in marshal (GH-157398)
Replace soft deprecated PyBytes_FromStringAndSize(NULL, n) with PyBytes_FromStringAndSize(str, n) so marshal can get bytes singleton. (cherry picked from commit 658612a) Co-authored-by: Victor Stinner <vstinner@python.org>
1 parent af0798e commit f255ad7

3 files changed

Lines changed: 12 additions & 6 deletions

File tree

Lib/test/test_marshal.py

Lines changed: 8 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -116,6 +116,14 @@ def test_bytes(self):
116116
for s in [b"", b"Andr\xe8 Previn", b"abc", b" "*10000]:
117117
self.helper(s)
118118

119+
@support.cpython_only
120+
def test_bytes_singleton(self):
121+
for version in range(marshal.version + 1):
122+
for sample in [b"", b"x"]:
123+
new = marshal.loads(marshal.dumps(sample, version))
124+
self.assertIs(new, sample)
125+
126+
119127
class ExceptionTestCase(unittest.TestCase):
120128
def test_exceptions(self):
121129
new = marshal.loads(marshal.dumps(StopIteration))
Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,2 @@
1+
:func:`marshal.load` and :func:`marshal.loads` can now get 1-byte string
2+
singletons. Patch by Victor Stinner.

Python/marshal.c

Lines changed: 2 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -1294,16 +1294,12 @@ r_object(RFILE *p)
12941294
}
12951295
break;
12961296
}
1297-
v = PyBytes_FromStringAndSize((char *)NULL, n);
1298-
if (v == NULL)
1299-
break;
13001297
ptr = r_string(n, p);
13011298
if (ptr == NULL) {
1302-
Py_DECREF(v);
13031299
break;
13041300
}
1305-
memcpy(PyBytes_AS_STRING(v), ptr, n);
1306-
retval = v;
1301+
// Get a singleton for 1-byte string
1302+
retval = PyBytes_FromStringAndSize(ptr, n); // can be NULL
13071303
R_REF(retval);
13081304
break;
13091305
}

0 commit comments

Comments
 (0)