Skip to content

Commit c863349

Browse files
authored
gh-139156: Use PyBytesWriter in the UTF-7 encoder (#139248)
Replace PyBytes_FromStringAndSize() and _PyBytes_Resize() with the PyBytesWriter API.
1 parent 92ba2c9 commit c863349

File tree

1 file changed

+16
-24
lines changed

1 file changed

+16
-24
lines changed

Objects/unicodeobject.c

Lines changed: 16 additions & 24 deletions
Original file line numberDiff line numberDiff line change
@@ -4897,33 +4897,27 @@ _PyUnicode_EncodeUTF7(PyObject *str,
48974897
int base64WhiteSpace,
48984898
const char *errors)
48994899
{
4900-
int kind;
4901-
const void *data;
4902-
Py_ssize_t len;
4903-
PyObject *v;
4904-
int inShift = 0;
4905-
Py_ssize_t i;
4906-
unsigned int base64bits = 0;
4907-
unsigned long base64buffer = 0;
4908-
char * out;
4909-
const char * start;
4910-
4911-
kind = PyUnicode_KIND(str);
4912-
data = PyUnicode_DATA(str);
4913-
len = PyUnicode_GET_LENGTH(str);
4914-
4915-
if (len == 0)
4900+
Py_ssize_t len = PyUnicode_GET_LENGTH(str);
4901+
if (len == 0) {
49164902
return Py_GetConstant(Py_CONSTANT_EMPTY_BYTES);
4903+
}
4904+
int kind = PyUnicode_KIND(str);
4905+
const void *data = PyUnicode_DATA(str);
49174906

49184907
/* It might be possible to tighten this worst case */
4919-
if (len > PY_SSIZE_T_MAX / 8)
4908+
if (len > PY_SSIZE_T_MAX / 8) {
49204909
return PyErr_NoMemory();
4921-
v = PyBytes_FromStringAndSize(NULL, len * 8);
4922-
if (v == NULL)
4910+
}
4911+
PyBytesWriter *writer = PyBytesWriter_Create(len * 8);
4912+
if (writer == NULL) {
49234913
return NULL;
4914+
}
49244915

4925-
start = out = PyBytes_AS_STRING(v);
4926-
for (i = 0; i < len; ++i) {
4916+
int inShift = 0;
4917+
unsigned int base64bits = 0;
4918+
unsigned long base64buffer = 0;
4919+
char *out = PyBytesWriter_GetData(writer);
4920+
for (Py_ssize_t i = 0; i < len; ++i) {
49274921
Py_UCS4 ch = PyUnicode_READ(kind, data, i);
49284922

49294923
if (inShift) {
@@ -4986,9 +4980,7 @@ _PyUnicode_EncodeUTF7(PyObject *str,
49864980
*out++= TO_BASE64(base64buffer << (6-base64bits) );
49874981
if (inShift)
49884982
*out++ = '-';
4989-
if (_PyBytes_Resize(&v, out - start) < 0)
4990-
return NULL;
4991-
return v;
4983+
return PyBytesWriter_FinishWithPointer(writer, out);
49924984
}
49934985

49944986
#undef IS_BASE64

0 commit comments

Comments
 (0)