Skip to content

Commit 7974427

Browse files
committed
gh-128509: Use bytes singleton in marshal
Replace soft deprecated PyBytes_FromStringAndSize(NULL, n) with PyBytes_FromStringAndSize(str, n) so marshal can get bytes singleton.
1 parent 58cdff7 commit 7974427

2 files changed

Lines changed: 9 additions & 6 deletions

File tree

Lib/test/test_marshal.py

Lines changed: 7 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -116,6 +116,13 @@ 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 sample in [b"", b"x"]:
122+
new = marshal.loads(marshal.dumps(sample))
123+
self.assertIs(new, sample)
124+
125+
119126
class ExceptionTestCase(unittest.TestCase):
120127
def test_exceptions(self):
121128
new = marshal.loads(marshal.dumps(StopIteration))

Python/marshal.c

Lines changed: 2 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -1388,16 +1388,12 @@ r_object(RFILE *p)
13881388
}
13891389
break;
13901390
}
1391-
v = PyBytes_FromStringAndSize((char *)NULL, n);
1392-
if (v == NULL)
1393-
break;
13941391
ptr = r_string(n, p);
13951392
if (ptr == NULL) {
1396-
Py_DECREF(v);
13971393
break;
13981394
}
1399-
memcpy(PyBytes_AS_STRING(v), ptr, n);
1400-
retval = v;
1395+
// Get a singleton for 1-byte string
1396+
retval = PyBytes_FromStringAndSize(ptr, n); // can be NULL
14011397
R_REF(retval);
14021398
break;
14031399
}

0 commit comments

Comments
 (0)