| 1 |
// Primitives related to librt.strings.BytesWriter that get linked statically |
| 2 |
// with compiled modules, instead of being called via a capsule. |
| 3 |
|
| 4 |
#include "byteswriter_extra_ops.h" |
| 5 |
|
| 6 |
char CPyBytesWriter_Write(PyObject *obj, PyObject *value) { |
| 7 |
BytesWriterObject *self = (BytesWriterObject *)obj; |
| 8 |
const char *data; |
| 9 |
Py_ssize_t size; |
| 10 |
if (likely(PyBytes_Check(value))) { |
| 11 |
data = PyBytes_AS_STRING(value); |
| 12 |
size = PyBytes_GET_SIZE(value); |
| 13 |
} else { |
| 14 |
data = PyByteArray_AS_STRING(value); |
| 15 |
size = PyByteArray_GET_SIZE(value); |
| 16 |
} |
| 17 |
// Write bytes content. |
| 18 |
if (!CPyBytesWriter_EnsureSize(self, size)) |
| 19 |
return CPY_NONE_ERROR; |
| 20 |
if (size < 8) { |
| 21 |
// Loop tends to be faster for small sizes |
| 22 |
char *p = self->buf + self->len; |
| 23 |
for (Py_ssize_t i = 0; i < size; i++) { |
| 24 |
p[i] = data[i]; |
| 25 |
} |
| 26 |
} else { |
| 27 |
memcpy(self->buf + self->len, data, size); |
| 28 |
} |
| 29 |
self->len += size; |
| 30 |
return CPY_NONE; |
| 31 |
} |
| 32 |
|
| 33 |
void CPyBytes_ReadError(int64_t index, Py_ssize_t size) { |
| 34 |
if (index < 0) { |
| 35 |
PyErr_SetString(PyExc_ValueError, "index must be non-negative"); |
| 36 |
} else { |
| 37 |
PyErr_Format(PyExc_IndexError, |
| 38 |
"index %lld out of range for bytes of length %zd", |
| 39 |
(long long)index, size); |
| 40 |
} |
| 41 |
} |