Skip to content

Commit bb743b6

Browse files
authored
gh-129813, PEP 782: Use PyBytesWriter in socket and mmap (#138831)
Replace PyBytes_FromStringAndSize(NULL, size) and _PyBytes_Resize() with the new public PyBytesWriter API.
1 parent 06b7891 commit bb743b6

File tree

2 files changed

+14
-13
lines changed

2 files changed

+14
-13
lines changed

Modules/mmapmodule.c

Lines changed: 8 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -448,7 +448,8 @@ _safe_PyBytes_ReverseFind(Py_ssize_t *out, mmap_object *self,
448448
}
449449

450450
PyObject *
451-
_safe_PyBytes_FromStringAndSize(char *start, size_t num_bytes) {
451+
_safe_PyBytes_FromStringAndSize(char *start, size_t num_bytes)
452+
{
452453
if (num_bytes == 1) {
453454
char dest;
454455
if (safe_byte_copy(&dest, start) < 0) {
@@ -459,14 +460,15 @@ _safe_PyBytes_FromStringAndSize(char *start, size_t num_bytes) {
459460
}
460461
}
461462
else {
462-
PyObject *result = PyBytes_FromStringAndSize(NULL, num_bytes);
463-
if (result == NULL) {
463+
PyBytesWriter *writer = PyBytesWriter_Create(num_bytes);
464+
if (writer == NULL) {
464465
return NULL;
465466
}
466-
if (safe_memcpy(PyBytes_AS_STRING(result), start, num_bytes) < 0) {
467-
Py_CLEAR(result);
467+
if (safe_memcpy(PyBytesWriter_GetData(writer), start, num_bytes) < 0) {
468+
PyBytesWriter_Discard(writer);
469+
return NULL;
468470
}
469-
return result;
471+
return PyBytesWriter_Finish(writer);
470472
}
471473
}
472474

Modules/socketmodule.c

Lines changed: 6 additions & 7 deletions
Original file line numberDiff line numberDiff line change
@@ -3467,7 +3467,6 @@ sock_getsockopt(PyObject *self, PyObject *args)
34673467
int level;
34683468
int optname;
34693469
int res;
3470-
PyObject *buf;
34713470
socklen_t buflen = 0;
34723471
int flag = 0;
34733472
socklen_t flagsize;
@@ -3512,17 +3511,17 @@ sock_getsockopt(PyObject *self, PyObject *args)
35123511
"getsockopt buflen out of range");
35133512
return NULL;
35143513
}
3515-
buf = PyBytes_FromStringAndSize((char *)NULL, buflen);
3516-
if (buf == NULL)
3514+
PyBytesWriter *writer = PyBytesWriter_Create(buflen);
3515+
if (writer == NULL) {
35173516
return NULL;
3517+
}
35183518
res = getsockopt(get_sock_fd(s), level, optname,
3519-
(void *)PyBytes_AS_STRING(buf), &buflen);
3519+
PyBytesWriter_GetData(writer), &buflen);
35203520
if (res < 0) {
3521-
Py_DECREF(buf);
3521+
PyBytesWriter_Discard(writer);
35223522
return s->errorhandler();
35233523
}
3524-
_PyBytes_Resize(&buf, buflen);
3525-
return buf;
3524+
return PyBytesWriter_FinishWithSize(writer, buflen);
35263525
}
35273526

35283527
PyDoc_STRVAR(getsockopt_doc,

0 commit comments

Comments
 (0)