Skip to content

Commit 03e7a88

Browse files
authored
gh-129813: Use PyBytesWriter in binascii (#162259)
1 parent 3edcc34 commit 03e7a88

1 file changed

Lines changed: 8 additions & 20 deletions

File tree

‎Modules/binascii.c‎

Lines changed: 8 additions & 20 deletions
Original file line numberDiff line numberDiff line change
@@ -2390,10 +2390,8 @@ binascii_a2b_qp_impl(PyObject *module, Py_buffer *data, int header,
23902390
Py_ssize_t in, out;
23912391
char ch;
23922392
const unsigned char *ascii_data;
2393-
unsigned char *odata;
23942393
unsigned char *stripped = NULL;
23952394
Py_ssize_t datalen = 0;
2396-
PyObject *rv;
23972395

23982396
ascii_data = data->buf;
23992397
datalen = data->len;
@@ -2443,14 +2441,12 @@ binascii_a2b_qp_impl(PyObject *module, Py_buffer *data, int header,
24432441
}
24442442
}
24452443

2446-
/* We allocate the output same size as input, this is overkill.
2447-
*/
2448-
odata = (unsigned char *) PyMem_Calloc(1, datalen);
2449-
if (odata == NULL) {
2444+
PyBytesWriter *writer = PyBytesWriter_Create(datalen);
2445+
if (writer == NULL) {
24502446
PyMem_Free(stripped);
2451-
PyErr_NoMemory();
24522447
return NULL;
24532448
}
2449+
unsigned char *odata = PyBytesWriter_GetData(writer);
24542450

24552451
in = out = 0;
24562452
while (in < datalen) {
@@ -2492,10 +2488,8 @@ binascii_a2b_qp_impl(PyObject *module, Py_buffer *data, int header,
24922488
out++;
24932489
}
24942490
}
2495-
rv = PyBytes_FromStringAndSize((char *)odata, out);
2496-
PyMem_Free(odata);
24972491
PyMem_Free(stripped);
2498-
return rv;
2492+
return PyBytesWriter_FinishWithSize(writer, out);
24992493
}
25002494

25012495
static int
@@ -2535,9 +2529,7 @@ binascii_b2a_qp_impl(PyObject *module, Py_buffer *data, int quotetabs,
25352529
{
25362530
Py_ssize_t in, out;
25372531
const unsigned char *databuf;
2538-
unsigned char *odata;
25392532
Py_ssize_t datalen = 0, odatalen = 0;
2540-
PyObject *rv;
25412533
unsigned int linelen = 0;
25422534
unsigned char ch;
25432535
int crlf = 0;
@@ -2622,13 +2614,11 @@ binascii_b2a_qp_impl(PyObject *module, Py_buffer *data, int quotetabs,
26222614
odatalen += delta;
26232615
}
26242616

2625-
/* We allocate the output same size as input, this is overkill.
2626-
*/
2627-
odata = (unsigned char *) PyMem_Calloc(1, odatalen);
2628-
if (odata == NULL) {
2629-
PyErr_NoMemory();
2617+
PyBytesWriter *writer = PyBytesWriter_Create(odatalen);
2618+
if (writer == NULL) {
26302619
return NULL;
26312620
}
2621+
unsigned char *odata = PyBytesWriter_GetData(writer);
26322622

26332623
in = out = linelen = 0;
26342624
while (in < datalen) {
@@ -2698,9 +2688,7 @@ binascii_b2a_qp_impl(PyObject *module, Py_buffer *data, int quotetabs,
26982688
}
26992689
}
27002690
}
2701-
rv = PyBytes_FromStringAndSize((char *)odata, out);
2702-
PyMem_Free(odata);
2703-
return rv;
2691+
return PyBytesWriter_FinishWithSize(writer, out);
27042692
}
27052693

27062694
/* List of functions defined in the module */

0 commit comments

Comments
 (0)