Skip to content

Commit 1f64526

Browse files
committed
gh-155742: Use PyBytesWriter in bytes.translate()
Replace soft deprecated _PyBytes_Resize() with PyBytesWriter.
1 parent f5dd52d commit 1f64526

1 file changed

Lines changed: 9 additions & 9 deletions

File tree

Objects/bytesobject.c

Lines changed: 9 additions & 9 deletions
Original file line numberDiff line numberDiff line change
@@ -2275,7 +2275,6 @@ bytes_translate_impl(PyBytesObject *self, PyObject *table,
22752275
PyObject *input_obj = (PyObject*)self;
22762276
const char *output_start, *del_table_chars=NULL;
22772277
Py_ssize_t inlen, tablen, dellen = 0;
2278-
PyObject *result;
22792278
int trans_table[256];
22802279

22812280
if (PyBytes_Check(table)) {
@@ -2320,13 +2319,13 @@ bytes_translate_impl(PyBytesObject *self, PyObject *table,
23202319
}
23212320

23222321
inlen = PyBytes_GET_SIZE(input_obj);
2323-
result = PyBytes_FromStringAndSize((char *)NULL, inlen);
2324-
if (result == NULL) {
2322+
PyBytesWriter *writer = PyBytesWriter_Create(inlen);
2323+
if (writer == NULL) {
23252324
PyBuffer_Release(&del_table_view);
23262325
PyBuffer_Release(&table_view);
23272326
return NULL;
23282327
}
2329-
output_start = output = PyBytes_AS_STRING(result);
2328+
output_start = output = PyBytesWriter_GetData(writer);
23302329
input = PyBytes_AS_STRING(input_obj);
23312330

23322331
if (dellen == 0 && table_chars != NULL) {
@@ -2335,14 +2334,17 @@ bytes_translate_impl(PyBytesObject *self, PyObject *table,
23352334
c = Py_CHARMASK(*input++);
23362335
*output++ = table_chars[c];
23372336
}
2337+
PyObject *result = PyBytesWriter_Finish(writer);
2338+
23382339
/* Check if anything changed (for returning original object) */
23392340
/* We save this check until the end so that the compiler will */
23402341
/* unroll the loop above leading to MUCH faster code. */
2341-
if (PyBytes_CheckExact(input_obj)) {
2342+
if (result != NULL && PyBytes_CheckExact(input_obj)) {
23422343
if (memcmp(PyBytes_AS_STRING(input_obj), output_start, inlen) == 0) {
23432344
Py_SETREF(result, Py_NewRef(input_obj));
23442345
}
23452346
}
2347+
23462348
PyBuffer_Release(&del_table_view);
23472349
PyBuffer_Release(&table_view);
23482350
return result;
@@ -2369,13 +2371,11 @@ bytes_translate_impl(PyBytesObject *self, PyObject *table,
23692371
changed = 1;
23702372
}
23712373
if (!changed && PyBytes_CheckExact(input_obj)) {
2372-
Py_DECREF(result);
2374+
PyBytesWriter_Discard(writer);
23732375
return Py_NewRef(input_obj);
23742376
}
23752377
/* Fix the size of the resulting byte string */
2376-
if (inlen > 0)
2377-
_PyBytes_Resize(&result, output - output_start);
2378-
return result;
2378+
return PyBytesWriter_FinishWithPointer(writer, output);
23792379
}
23802380

23812381

0 commit comments

Comments
 (0)