Skip to content

Commit 243d599

Browse files
authored
gh-129813, PEP 782: Use PyBytesWriter in _sqlite (#138956)
Replace PyBytes_FromStringAndSize(NULL, size) with the new public PyBytesWriter API.
1 parent 6504f20 commit 243d599

File tree

1 file changed

+19
-14
lines changed

1 file changed

+19
-14
lines changed

Modules/_sqlite/blob.c

Lines changed: 19 additions & 14 deletions
Original file line numberDiff line numberDiff line change
@@ -143,23 +143,23 @@ read_multiple(pysqlite_Blob *self, Py_ssize_t length, Py_ssize_t offset)
143143
assert(length <= sqlite3_blob_bytes(self->blob));
144144
assert(offset < sqlite3_blob_bytes(self->blob));
145145

146-
PyObject *buffer = PyBytes_FromStringAndSize(NULL, length);
147-
if (buffer == NULL) {
146+
PyBytesWriter *writer = PyBytesWriter_Create(length);
147+
if (writer == NULL) {
148148
return NULL;
149149
}
150+
char *raw_buffer = PyBytesWriter_GetData(writer);
150151

151-
char *raw_buffer = PyBytes_AS_STRING(buffer);
152152
int rc;
153153
Py_BEGIN_ALLOW_THREADS
154154
rc = sqlite3_blob_read(self->blob, raw_buffer, (int)length, (int)offset);
155155
Py_END_ALLOW_THREADS
156156

157157
if (rc != SQLITE_OK) {
158-
Py_DECREF(buffer);
158+
PyBytesWriter_Discard(writer);
159159
blob_seterror(self, rc);
160160
return NULL;
161161
}
162-
return buffer;
162+
return PyBytesWriter_Finish(writer);
163163
}
164164

165165

@@ -196,7 +196,7 @@ blob_read_impl(pysqlite_Blob *self, int length)
196196

197197
assert(length >= 0);
198198
if (length == 0) {
199-
return PyBytes_FromStringAndSize(NULL, 0);
199+
return Py_GetConstant(Py_CONSTANT_EMPTY_BYTES);
200200
}
201201

202202
PyObject *buffer = read_multiple(self, length, self->offset);
@@ -440,20 +440,25 @@ subscript_slice(pysqlite_Blob *self, PyObject *item)
440440
if (step == 1) {
441441
return read_multiple(self, len, start);
442442
}
443+
443444
PyObject *blob = read_multiple(self, stop - start, start);
444445
if (blob == NULL) {
445446
return NULL;
446447
}
447-
PyObject *result = PyBytes_FromStringAndSize(NULL, len);
448-
if (result != NULL) {
449-
char *blob_buf = PyBytes_AS_STRING(blob);
450-
char *res_buf = PyBytes_AS_STRING(result);
451-
for (Py_ssize_t i = 0, j = 0; i < len; i++, j += step) {
452-
res_buf[i] = blob_buf[j];
453-
}
448+
449+
PyBytesWriter *writer = PyBytesWriter_Create(len);
450+
if (writer == NULL) {
454451
Py_DECREF(blob);
452+
return NULL;
453+
}
454+
char *res_buf = PyBytesWriter_GetData(writer);
455+
456+
char *blob_buf = PyBytes_AS_STRING(blob);
457+
for (Py_ssize_t i = 0, j = 0; i < len; i++, j += step) {
458+
res_buf[i] = blob_buf[j];
455459
}
456-
return result;
460+
Py_DECREF(blob);
461+
return PyBytesWriter_Finish(writer);
457462
}
458463

459464
static PyObject *

0 commit comments

Comments
 (0)