| 1 |
#include "pythoncapi_compat.h" |
| 2 |
|
| 3 |
#define PY_SSIZE_T_CLEAN |
| 4 |
#include <Python.h> |
| 5 |
#include <stdint.h> |
| 6 |
#include "CPy.h" |
| 7 |
#include "librt_strings.h" |
| 8 |
|
| 9 |
#define CPY_BOOL_ERROR 2 |
| 10 |
|
| 11 |
// |
| 12 |
// BytesWriter |
| 13 |
// |
| 14 |
|
| 15 |
#define _WRITE_BYTES(data, type, v) \ |
| 16 |
do { \ |
| 17 |
*(type *)(((BytesWriterObject *)data)->buf + ((BytesWriterObject *)data)->len) = v; \ |
| 18 |
((BytesWriterObject *)data)->len += sizeof(type); \ |
| 19 |
} while (0) |
| 20 |
|
| 21 |
static PyTypeObject BytesWriterType; |
| 22 |
|
| 23 |
static bool |
| 24 |
_grow_buffer(BytesWriterObject *data, Py_ssize_t n) { |
| 25 |
if (unlikely(n > PY_SSIZE_T_MAX - data->len)) { |
| 26 |
PyErr_NoMemory(); |
| 27 |
return false; |
| 28 |
} |
| 29 |
Py_ssize_t target = data->len + n; |
| 30 |
Py_ssize_t size = data->capacity; |
| 31 |
do { |
| 32 |
if (unlikely(size > PY_SSIZE_T_MAX / 2)) { |
| 33 |
PyErr_NoMemory(); |
| 34 |
return false; |
| 35 |
} |
| 36 |
size *= 2; |
| 37 |
} while (target >= size); |
| 38 |
char *new_buf; |
| 39 |
if (data->buf == data->data) { |
| 40 |
// Move from embedded buffer to heap-allocated buffer |
| 41 |
new_buf = PyMem_Malloc(size); |
| 42 |
if (new_buf != NULL) { |
| 43 |
memcpy(new_buf, data->data, data->len); |
| 44 |
} |
| 45 |
} else { |
| 46 |
new_buf = PyMem_Realloc(data->buf, size); |
| 47 |
} |
| 48 |
if (unlikely(new_buf == NULL)) { |
| 49 |
PyErr_NoMemory(); |
| 50 |
return false; |
| 51 |
} |
| 52 |
data->buf = new_buf; |
| 53 |
data->capacity = size; |
| 54 |
return true; |
| 55 |
} |
| 56 |
|
| 57 |
static inline bool |
| 58 |
ensure_bytes_writer_size(BytesWriterObject *data, Py_ssize_t n) { |
| 59 |
if (likely(data->capacity - data->len >= n)) { |
| 60 |
return true; |
| 61 |
} else { |
| 62 |
return _grow_buffer(data, n); |
| 63 |
} |
| 64 |
} |
| 65 |
|
| 66 |
static inline void |
| 67 |
BytesWriter_init_internal(BytesWriterObject *self) { |
| 68 |
self->buf = self->data; |
| 69 |
self->len = 0; |
| 70 |
self->capacity = WRITER_EMBEDDED_BUF_LEN; |
| 71 |
} |
| 72 |
|
| 73 |
static PyObject* |
| 74 |
BytesWriter_new(PyTypeObject *type, PyObject *args, PyObject *kwds) |
| 75 |
{ |
| 76 |
if (type != &BytesWriterType) { |
| 77 |
PyErr_SetString(PyExc_TypeError, "BytesWriter cannot be subclassed"); |
| 78 |
return NULL; |
| 79 |
} |
| 80 |
|
| 81 |
BytesWriterObject *self = (BytesWriterObject *)type->tp_alloc(type, 0); |
| 82 |
if (self != NULL) |
| 83 |
BytesWriter_init_internal(self); |
| 84 |
return (PyObject *)self; |
| 85 |
} |
| 86 |
|
| 87 |
static PyObject * |
| 88 |
BytesWriter_internal(void) { |
| 89 |
BytesWriterObject *self = (BytesWriterObject *)BytesWriterType.tp_alloc(&BytesWriterType, 0); |
| 90 |
if (self == NULL) |
| 91 |
return NULL; |
| 92 |
BytesWriter_init_internal(self); |
| 93 |
return (PyObject *)self; |
| 94 |
} |
| 95 |
|
| 96 |
static int |
| 97 |
BytesWriter_init(BytesWriterObject *self, PyObject *args, PyObject *kwds) |
| 98 |
{ |
| 99 |
if (!PyArg_ParseTuple(args, "")) { |
| 100 |
return -1; |
| 101 |
} |
| 102 |
|
| 103 |
if (kwds != NULL && PyDict_Size(kwds) > 0) { |
| 104 |
PyErr_SetString(PyExc_TypeError, |
| 105 |
"BytesWriter() takes no keyword arguments"); |
| 106 |
return -1; |
| 107 |
} |
| 108 |
|
| 109 |
// Soft reset: free any heap buffer so re-initialization doesn't leak. |
| 110 |
if (self->buf != self->data && self->buf != NULL) |
| 111 |
PyMem_Free(self->buf); |
| 112 |
BytesWriter_init_internal(self); |
| 113 |
return 0; |
| 114 |
} |
| 115 |
|
| 116 |
static void |
| 117 |
BytesWriter_dealloc(BytesWriterObject *self) |
| 118 |
{ |
| 119 |
if (self->buf != self->data) { |
| 120 |
PyMem_Free(self->buf); |
| 121 |
self->buf = NULL; |
| 122 |
} |
| 123 |
Py_TYPE(self)->tp_free((PyObject *)self); |
| 124 |
} |
| 125 |
|
| 126 |
static PyObject* |
| 127 |
BytesWriter_getvalue_internal(PyObject *self) |
| 128 |
{ |
| 129 |
BytesWriterObject *obj = (BytesWriterObject *)self; |
| 130 |
return PyBytes_FromStringAndSize(obj->buf, obj->len); |
| 131 |
} |
| 132 |
|
| 133 |
static PyObject* |
| 134 |
BytesWriter_repr(BytesWriterObject *self) |
| 135 |
{ |
| 136 |
PyObject *value = BytesWriter_getvalue_internal((PyObject *)self); |
| 137 |
if (value == NULL) { |
| 138 |
return NULL; |
| 139 |
} |
| 140 |
PyObject *value_repr = PyObject_Repr(value); |
| 141 |
Py_DECREF(value); |
| 142 |
if (value_repr == NULL) { |
| 143 |
return NULL; |
| 144 |
} |
| 145 |
PyObject *result = PyUnicode_FromFormat("BytesWriter(%U)", value_repr); |
| 146 |
Py_DECREF(value_repr); |
| 147 |
return result; |
| 148 |
} |
| 149 |
|
| 150 |
static PyObject* |
| 151 |
BytesWriter_getvalue(BytesWriterObject *self, PyObject *Py_UNUSED(ignored)) |
| 152 |
{ |
| 153 |
return PyBytes_FromStringAndSize(self->buf, self->len); |
| 154 |
} |
| 155 |
|
| 156 |
static Py_ssize_t |
| 157 |
BytesWriter_length(BytesWriterObject *self) |
| 158 |
{ |
| 159 |
return self->len; |
| 160 |
} |
| 161 |
|
| 162 |
static PyObject* |
| 163 |
BytesWriter_item(BytesWriterObject *self, Py_ssize_t index) |
| 164 |
{ |
| 165 |
Py_ssize_t length = self->len; |
| 166 |
|
| 167 |
// Check bounds |
| 168 |
if (index < 0 || index >= length) { |
| 169 |
PyErr_SetString(PyExc_IndexError, "BytesWriter index out of range"); |
| 170 |
return NULL; |
| 171 |
} |
| 172 |
|
| 173 |
// Return the byte at the given index as a Python int |
| 174 |
return PyLong_FromLong((unsigned char)self->buf[index]); |
| 175 |
} |
| 176 |
|
| 177 |
static int |
| 178 |
BytesWriter_ass_item(BytesWriterObject *self, Py_ssize_t index, PyObject *value) |
| 179 |
{ |
| 180 |
Py_ssize_t length = self->len; |
| 181 |
|
| 182 |
// Check bounds |
| 183 |
if (index < 0 || index >= length) { |
| 184 |
PyErr_SetString(PyExc_IndexError, "BytesWriter index out of range"); |
| 185 |
return -1; |
| 186 |
} |
| 187 |
|
| 188 |
// Check that value is not NULL (deletion not supported) |
| 189 |
if (value == NULL) { |
| 190 |
PyErr_SetString(PyExc_TypeError, "BytesWriter does not support item deletion"); |
| 191 |
return -1; |
| 192 |
} |
| 193 |
|
| 194 |
// Convert value to uint8 |
| 195 |
uint8_t byte_value = CPyLong_AsUInt8(value); |
| 196 |
if (unlikely(byte_value == CPY_LL_UINT_ERROR && PyErr_Occurred())) { |
| 197 |
CPy_TypeError("u8", value); |
| 198 |
return -1; |
| 199 |
} |
| 200 |
|
| 201 |
// Assign the byte |
| 202 |
self->buf[index] = (char)byte_value; |
| 203 |
return 0; |
| 204 |
} |
| 205 |
|
| 206 |
static PySequenceMethods BytesWriter_as_sequence = { |
| 207 |
.sq_length = (lenfunc)BytesWriter_length, |
| 208 |
.sq_item = (ssizeargfunc)BytesWriter_item, |
| 209 |
.sq_ass_item = (ssizeobjargproc)BytesWriter_ass_item, |
| 210 |
}; |
| 211 |
|
| 212 |
static PyObject* BytesWriter_append(PyObject *self, PyObject *const *args, size_t nargs); |
| 213 |
static PyObject* BytesWriter_write(PyObject *self, PyObject *const *args, size_t nargs); |
| 214 |
static PyObject* BytesWriter_truncate(PyObject *self, PyObject *const *args, size_t nargs); |
| 215 |
|
| 216 |
static PyMethodDef BytesWriter_methods[] = { |
| 217 |
{"append", (PyCFunction) BytesWriter_append, METH_FASTCALL, |
| 218 |
PyDoc_STR("Append a single byte to the buffer") |
| 219 |
}, |
| 220 |
{"write", (PyCFunction) BytesWriter_write, METH_FASTCALL, |
| 221 |
PyDoc_STR("Append bytes to the buffer") |
| 222 |
}, |
| 223 |
{"getvalue", (PyCFunction) BytesWriter_getvalue, METH_NOARGS, |
| 224 |
"Return the buffer content as bytes object" |
| 225 |
}, |
| 226 |
{"truncate", (PyCFunction) BytesWriter_truncate, METH_FASTCALL, |
| 227 |
PyDoc_STR("Truncate the buffer to the specified size") |
| 228 |
}, |
| 229 |
{NULL} /* Sentinel */ |
| 230 |
}; |
| 231 |
|
| 232 |
static PyTypeObject BytesWriterType = { |
| 233 |
.ob_base = PyVarObject_HEAD_INIT(NULL, 0) |
| 234 |
.tp_name = "BytesWriter", |
| 235 |
.tp_doc = PyDoc_STR("Memory buffer for building bytes objects from parts"), |
| 236 |
.tp_basicsize = sizeof(BytesWriterObject), |
| 237 |
.tp_itemsize = 0, |
| 238 |
.tp_flags = Py_TPFLAGS_DEFAULT, |
| 239 |
.tp_new = BytesWriter_new, |
| 240 |
.tp_init = (initproc) BytesWriter_init, |
| 241 |
.tp_dealloc = (destructor) BytesWriter_dealloc, |
| 242 |
.tp_methods = BytesWriter_methods, |
| 243 |
.tp_as_sequence = &BytesWriter_as_sequence, |
| 244 |
.tp_repr = (reprfunc)BytesWriter_repr, |
| 245 |
}; |
| 246 |
|
| 247 |
static inline bool |
| 248 |
check_bytes_writer(PyObject *data) { |
| 249 |
if (unlikely(Py_TYPE(data) != &BytesWriterType)) { |
| 250 |
PyErr_Format( |
| 251 |
PyExc_TypeError, "data must be a BytesWriter object, got %s", Py_TYPE(data)->tp_name |
| 252 |
); |
| 253 |
return false; |
| 254 |
} |
| 255 |
return true; |
| 256 |
} |
| 257 |
|
| 258 |
static char |
| 259 |
BytesWriter_write_internal(BytesWriterObject *self, PyObject *value) { |
| 260 |
const char *data; |
| 261 |
Py_ssize_t size; |
| 262 |
if (likely(PyBytes_Check(value))) { |
| 263 |
data = PyBytes_AS_STRING(value); |
| 264 |
size = PyBytes_GET_SIZE(value); |
| 265 |
} else { |
| 266 |
data = PyByteArray_AS_STRING(value); |
| 267 |
size = PyByteArray_GET_SIZE(value); |
| 268 |
} |
| 269 |
// Write bytes content. |
| 270 |
if (!ensure_bytes_writer_size(self, size)) |
| 271 |
return CPY_NONE_ERROR; |
| 272 |
memcpy(self->buf + self->len, data, size); |
| 273 |
self->len += size; |
| 274 |
return CPY_NONE; |
| 275 |
} |
| 276 |
|
| 277 |
static PyObject* |
| 278 |
BytesWriter_write(PyObject *self, PyObject *const *args, size_t nargs) { |
| 279 |
if (unlikely(nargs != 1)) { |
| 280 |
PyErr_Format(PyExc_TypeError, |
| 281 |
"write() takes exactly 1 argument (%zu given)", nargs); |
| 282 |
return NULL; |
| 283 |
} |
| 284 |
if (!check_bytes_writer(self)) { |
| 285 |
return NULL; |
| 286 |
} |
| 287 |
PyObject *value = args[0]; |
| 288 |
if (unlikely(!PyBytes_Check(value) && !PyByteArray_Check(value))) { |
| 289 |
PyErr_SetString(PyExc_TypeError, "value must be a bytes or bytearray object"); |
| 290 |
return NULL; |
| 291 |
} |
| 292 |
if (unlikely(BytesWriter_write_internal((BytesWriterObject *)self, value) == CPY_NONE_ERROR)) { |
| 293 |
return NULL; |
| 294 |
} |
| 295 |
Py_INCREF(Py_None); |
| 296 |
return Py_None; |
| 297 |
} |
| 298 |
|
| 299 |
static inline char |
| 300 |
BytesWriter_append_internal(BytesWriterObject *self, uint8_t value) { |
| 301 |
if (!ensure_bytes_writer_size(self, 1)) |
| 302 |
return CPY_NONE_ERROR; |
| 303 |
_WRITE_BYTES(self, uint8_t, value); |
| 304 |
return CPY_NONE; |
| 305 |
} |
| 306 |
|
| 307 |
static PyObject* |
| 308 |
BytesWriter_append(PyObject *self, PyObject *const *args, size_t nargs) { |
| 309 |
if (unlikely(nargs != 1)) { |
| 310 |
PyErr_Format(PyExc_TypeError, |
| 311 |
"append() takes exactly 1 argument (%zu given)", nargs); |
| 312 |
return NULL; |
| 313 |
} |
| 314 |
if (!check_bytes_writer(self)) { |
| 315 |
return NULL; |
| 316 |
} |
| 317 |
PyObject *value = args[0]; |
| 318 |
uint8_t unboxed = CPyLong_AsUInt8(value); |
| 319 |
if (unlikely(unboxed == CPY_LL_UINT_ERROR && PyErr_Occurred())) { |
| 320 |
CPy_TypeError("u8", value); |
| 321 |
return NULL; |
| 322 |
} |
| 323 |
if (unlikely(BytesWriter_append_internal((BytesWriterObject *)self, unboxed) == CPY_NONE_ERROR)) { |
| 324 |
return NULL; |
| 325 |
} |
| 326 |
Py_INCREF(Py_None); |
| 327 |
return Py_None; |
| 328 |
} |
| 329 |
|
| 330 |
static char |
| 331 |
BytesWriter_truncate_internal(PyObject *self, int64_t size) { |
| 332 |
BytesWriterObject *writer = (BytesWriterObject *)self; |
| 333 |
Py_ssize_t current_size = writer->len; |
| 334 |
|
| 335 |
// Validate size is non-negative |
| 336 |
if (size < 0) { |
| 337 |
PyErr_SetString(PyExc_ValueError, "size must be non-negative"); |
| 338 |
return CPY_NONE_ERROR; |
| 339 |
} |
| 340 |
|
| 341 |
// Validate size doesn't exceed current size |
| 342 |
if (size > current_size) { |
| 343 |
PyErr_SetString(PyExc_ValueError, "size cannot be larger than current buffer size"); |
| 344 |
return CPY_NONE_ERROR; |
| 345 |
} |
| 346 |
|
| 347 |
writer->len = size; |
| 348 |
return CPY_NONE; |
| 349 |
} |
| 350 |
|
| 351 |
static PyObject* |
| 352 |
BytesWriter_truncate(PyObject *self, PyObject *const *args, size_t nargs) { |
| 353 |
if (unlikely(nargs != 1)) { |
| 354 |
PyErr_Format(PyExc_TypeError, |
| 355 |
"truncate() takes exactly 1 argument (%zu given)", nargs); |
| 356 |
return NULL; |
| 357 |
} |
| 358 |
if (!check_bytes_writer(self)) { |
| 359 |
return NULL; |
| 360 |
} |
| 361 |
|
| 362 |
PyObject *size_obj = args[0]; |
| 363 |
int overflow; |
| 364 |
long long size = PyLong_AsLongLongAndOverflow(size_obj, &overflow); |
| 365 |
|
| 366 |
if (size == -1 && PyErr_Occurred()) { |
| 367 |
return NULL; |
| 368 |
} |
| 369 |
if (overflow != 0) { |
| 370 |
PyErr_SetString(PyExc_ValueError, "integer out of range"); |
| 371 |
return NULL; |
| 372 |
} |
| 373 |
|
| 374 |
if (unlikely(BytesWriter_truncate_internal(self, size) == CPY_NONE_ERROR)) { |
| 375 |
return NULL; |
| 376 |
} |
| 377 |
Py_INCREF(Py_None); |
| 378 |
return Py_None; |
| 379 |
} |
| 380 |
|
| 381 |
static PyTypeObject * |
| 382 |
BytesWriter_type_internal(void) { |
| 383 |
return &BytesWriterType; // Return borrowed reference |
| 384 |
}; |
| 385 |
|
| 386 |
static CPyTagged |
| 387 |
BytesWriter_len_internal(PyObject *self) { |
| 388 |
BytesWriterObject *writer = (BytesWriterObject *)self; |
| 389 |
return writer->len << 1; |
| 390 |
} |
| 391 |
|
| 392 |
// |
| 393 |
// StringWriter |
| 394 |
// |
| 395 |
|
| 396 |
static PyTypeObject StringWriterType; |
| 397 |
|
| 398 |
static void convert_string_data_in_place(char *buf, Py_ssize_t len, |
| 399 |
char old_kind, char new_kind); |
| 400 |
|
| 401 |
// Helper to grow string buffer and optionally convert to new kind |
| 402 |
// Returns true on success, false on failure (with PyErr set) |
| 403 |
// Updates self->buf, self->capacity, and self->kind |
| 404 |
static bool |
| 405 |
grow_string_buffer_helper(StringWriterObject *self, Py_ssize_t target_capacity, char new_kind) { |
| 406 |
char old_kind = self->kind; |
| 407 |
Py_ssize_t new_capacity = self->capacity; |
| 408 |
|
| 409 |
// Limit so that (new_capacity * 2) * new_kind stays within Py_ssize_t. |
| 410 |
// new_kind is always 1, 2, or 4, so use a shift instead of division. |
| 411 |
int shift = (new_kind == 4) ? 3 : (new_kind == 2 ? 2 : 1); |
| 412 |
Py_ssize_t cap_limit = PY_SSIZE_T_MAX >> shift; |
| 413 |
while (target_capacity >= new_capacity) { |
| 414 |
if (unlikely(new_capacity > cap_limit)) { |
| 415 |
PyErr_NoMemory(); |
| 416 |
return false; |
| 417 |
} |
| 418 |
new_capacity *= 2; |
| 419 |
} |
| 420 |
|
| 421 |
if (unlikely(new_capacity > cap_limit * 2)) { |
| 422 |
PyErr_NoMemory(); |
| 423 |
return false; |
| 424 |
} |
| 425 |
|
| 426 |
Py_ssize_t size_bytes = new_capacity * new_kind; |
| 427 |
char *new_buf; |
| 428 |
bool from_embedded = (self->buf == self->data); |
| 429 |
|
| 430 |
if (from_embedded) { |
| 431 |
// Move from embedded buffer to heap-allocated buffer |
| 432 |
new_buf = PyMem_Malloc(size_bytes); |
| 433 |
if (new_buf != NULL) { |
| 434 |
// Copy existing data from embedded buffer |
| 435 |
memcpy(new_buf, self->data, self->len * old_kind); |
| 436 |
} |
| 437 |
} else { |
| 438 |
// Realloc existing heap buffer |
| 439 |
new_buf = PyMem_Realloc(self->buf, size_bytes); |
| 440 |
} |
| 441 |
|
| 442 |
if (unlikely(new_buf == NULL)) { |
| 443 |
PyErr_NoMemory(); |
| 444 |
return false; |
| 445 |
} |
| 446 |
|
| 447 |
// Convert data if kind changed |
| 448 |
if (old_kind != new_kind) { |
| 449 |
convert_string_data_in_place(new_buf, self->len, old_kind, new_kind); |
| 450 |
} |
| 451 |
|
| 452 |
self->buf = new_buf; |
| 453 |
self->capacity = new_capacity; |
| 454 |
self->kind = new_kind; |
| 455 |
return true; |
| 456 |
} |
| 457 |
|
| 458 |
static bool grow_string_buffer(StringWriterObject *data, Py_ssize_t n) { |
| 459 |
if (unlikely(n > PY_SSIZE_T_MAX - data->len)) { |
| 460 |
PyErr_NoMemory(); |
| 461 |
return false; |
| 462 |
} |
| 463 |
return grow_string_buffer_helper(data, data->len + n, data->kind); |
| 464 |
} |
| 465 |
|
| 466 |
static inline bool |
| 467 |
ensure_string_writer_size(StringWriterObject *data, Py_ssize_t n) { |
| 468 |
if (likely(data->capacity - data->len >= n)) { |
| 469 |
return true; |
| 470 |
} else { |
| 471 |
// Don't inline the grow function since this is slow path and we |
| 472 |
// want to keep this as short as possible for better inlining |
| 473 |
return grow_string_buffer(data, n); |
| 474 |
} |
| 475 |
} |
| 476 |
|
| 477 |
static inline void |
| 478 |
StringWriter_init_internal(StringWriterObject *self) { |
| 479 |
self->buf = self->data; |
| 480 |
self->kind = 1; |
| 481 |
self->len = 0; |
| 482 |
self->capacity = WRITER_EMBEDDED_BUF_LEN; |
| 483 |
} |
| 484 |
|
| 485 |
static PyObject* |
| 486 |
StringWriter_new(PyTypeObject *type, PyObject *args, PyObject *kwds) |
| 487 |
{ |
| 488 |
if (type != &StringWriterType) { |
| 489 |
PyErr_SetString(PyExc_TypeError, "StringWriter cannot be subclassed"); |
| 490 |
return NULL; |
| 491 |
} |
| 492 |
|
| 493 |
StringWriterObject *self = (StringWriterObject *)type->tp_alloc(type, 0); |
| 494 |
if (self != NULL) |
| 495 |
StringWriter_init_internal(self); |
| 496 |
return (PyObject *)self; |
| 497 |
} |
| 498 |
|
| 499 |
static PyObject * |
| 500 |
StringWriter_internal(void) { |
| 501 |
StringWriterObject *self = (StringWriterObject *)StringWriterType.tp_alloc(&StringWriterType, 0); |
| 502 |
if (self == NULL) |
| 503 |
return NULL; |
| 504 |
StringWriter_init_internal(self); |
| 505 |
return (PyObject *)self; |
| 506 |
} |
| 507 |
|
| 508 |
static int |
| 509 |
StringWriter_init(StringWriterObject *self, PyObject *args, PyObject *kwds) |
| 510 |
{ |
| 511 |
if (!PyArg_ParseTuple(args, "")) { |
| 512 |
return -1; |
| 513 |
} |
| 514 |
|
| 515 |
if (kwds != NULL && PyDict_Size(kwds) > 0) { |
| 516 |
PyErr_SetString(PyExc_TypeError, |
| 517 |
"StringWriter() takes no keyword arguments"); |
| 518 |
return -1; |
| 519 |
} |
| 520 |
|
| 521 |
// Soft reset: free any heap buffer so re-initialization doesn't leak. |
| 522 |
if (self->buf != self->data && self->buf != NULL) |
| 523 |
PyMem_Free(self->buf); |
| 524 |
StringWriter_init_internal(self); |
| 525 |
return 0; |
| 526 |
} |
| 527 |
|
| 528 |
static void |
| 529 |
StringWriter_dealloc(StringWriterObject *self) |
| 530 |
{ |
| 531 |
if (self->buf != self->data) { |
| 532 |
PyMem_Free(self->buf); |
| 533 |
self->buf = NULL; |
| 534 |
} |
| 535 |
Py_TYPE(self)->tp_free((PyObject *)self); |
| 536 |
} |
| 537 |
|
| 538 |
static PyObject* |
| 539 |
StringWriter_getvalue_internal(PyObject *self) |
| 540 |
{ |
| 541 |
StringWriterObject *obj = (StringWriterObject *)self; |
| 542 |
return PyUnicode_FromKindAndData(obj->kind, obj->buf, obj->len); |
| 543 |
} |
| 544 |
|
| 545 |
static PyObject* |
| 546 |
StringWriter_repr(StringWriterObject *self) |
| 547 |
{ |
| 548 |
PyObject *value = StringWriter_getvalue_internal((PyObject *)self); |
| 549 |
if (value == NULL) { |
| 550 |
return NULL; |
| 551 |
} |
| 552 |
PyObject *value_repr = PyObject_Repr(value); |
| 553 |
Py_DECREF(value); |
| 554 |
if (value_repr == NULL) { |
| 555 |
return NULL; |
| 556 |
} |
| 557 |
PyObject *result = PyUnicode_FromFormat("StringWriter(%U)", value_repr); |
| 558 |
Py_DECREF(value_repr); |
| 559 |
return result; |
| 560 |
} |
| 561 |
|
| 562 |
static PyObject* |
| 563 |
StringWriter_getvalue(StringWriterObject *self, PyObject *Py_UNUSED(ignored)) |
| 564 |
{ |
| 565 |
return PyUnicode_FromKindAndData(self->kind, self->buf, self->len); |
| 566 |
} |
| 567 |
|
| 568 |
static Py_ssize_t |
| 569 |
StringWriter_length(StringWriterObject *self) |
| 570 |
{ |
| 571 |
return self->len; |
| 572 |
} |
| 573 |
|
| 574 |
static PyObject* |
| 575 |
StringWriter_item(StringWriterObject *self, Py_ssize_t index) |
| 576 |
{ |
| 577 |
Py_ssize_t length = self->len; |
| 578 |
|
| 579 |
// Check bounds |
| 580 |
if (index < 0 || index >= length) { |
| 581 |
PyErr_SetString(PyExc_IndexError, "StringWriter index out of range"); |
| 582 |
return NULL; |
| 583 |
} |
| 584 |
|
| 585 |
// Read the character at the given index based on kind using memcpy |
| 586 |
uint32_t value; |
| 587 |
if (self->kind == 1) { |
| 588 |
uint8_t val; |
| 589 |
memcpy(&val, self->buf + index, 1); |
| 590 |
value = val; |
| 591 |
} else if (self->kind == 2) { |
| 592 |
uint16_t val; |
| 593 |
memcpy(&val, self->buf + index * 2, 2); |
| 594 |
value = val; |
| 595 |
} else { |
| 596 |
memcpy(&value, self->buf + index * 4, 4); |
| 597 |
} |
| 598 |
return PyLong_FromLong(value); |
| 599 |
} |
| 600 |
|
| 601 |
static PySequenceMethods StringWriter_as_sequence = { |
| 602 |
.sq_length = (lenfunc)StringWriter_length, |
| 603 |
.sq_item = (ssizeargfunc)StringWriter_item, |
| 604 |
}; |
| 605 |
|
| 606 |
static PyObject* StringWriter_append(PyObject *self, PyObject *const *args, size_t nargs); |
| 607 |
static PyObject* StringWriter_write(PyObject *self, PyObject *const *args, size_t nargs); |
| 608 |
|
| 609 |
static PyMethodDef StringWriter_methods[] = { |
| 610 |
{"append", (PyCFunction) StringWriter_append, METH_FASTCALL, |
| 611 |
PyDoc_STR("Append a single character (as int codepoint) to the buffer") |
| 612 |
}, |
| 613 |
{"write", (PyCFunction) StringWriter_write, METH_FASTCALL, |
| 614 |
PyDoc_STR("Append a string to the buffer") |
| 615 |
}, |
| 616 |
{"getvalue", (PyCFunction) StringWriter_getvalue, METH_NOARGS, |
| 617 |
"Return the buffer content as str object" |
| 618 |
}, |
| 619 |
{NULL} /* Sentinel */ |
| 620 |
}; |
| 621 |
|
| 622 |
static PyTypeObject StringWriterType = { |
| 623 |
.ob_base = PyVarObject_HEAD_INIT(NULL, 0) |
| 624 |
.tp_name = "StringWriter", |
| 625 |
.tp_doc = PyDoc_STR("Memory buffer for building string objects from parts"), |
| 626 |
.tp_basicsize = sizeof(StringWriterObject), |
| 627 |
.tp_itemsize = 0, |
| 628 |
.tp_flags = Py_TPFLAGS_DEFAULT, |
| 629 |
.tp_new = StringWriter_new, |
| 630 |
.tp_init = (initproc) StringWriter_init, |
| 631 |
.tp_dealloc = (destructor) StringWriter_dealloc, |
| 632 |
.tp_methods = StringWriter_methods, |
| 633 |
.tp_as_sequence = &StringWriter_as_sequence, |
| 634 |
.tp_repr = (reprfunc)StringWriter_repr, |
| 635 |
}; |
| 636 |
|
| 637 |
static inline bool |
| 638 |
check_string_writer(PyObject *data) { |
| 639 |
if (unlikely(Py_TYPE(data) != &StringWriterType)) { |
| 640 |
PyErr_Format( |
| 641 |
PyExc_TypeError, "data must be a StringWriter object, got %s", Py_TYPE(data)->tp_name |
| 642 |
); |
| 643 |
return false; |
| 644 |
} |
| 645 |
return true; |
| 646 |
} |
| 647 |
|
| 648 |
static char string_writer_switch_kind(StringWriterObject *self, int32_t value); |
| 649 |
|
| 650 |
static char |
| 651 |
StringWriter_write_internal(PyObject *obj, PyObject *value) { |
| 652 |
StringWriterObject *self = (StringWriterObject *)obj; |
| 653 |
Py_ssize_t str_len = PyUnicode_GET_LENGTH(value); |
| 654 |
if (str_len == 0) { |
| 655 |
return CPY_NONE; |
| 656 |
} |
| 657 |
|
| 658 |
int src_kind = PyUnicode_KIND(value); |
| 659 |
void *src_data = PyUnicode_DATA(value); |
| 660 |
int self_kind = self->kind; |
| 661 |
|
| 662 |
// Switch kind if source requires wider characters |
| 663 |
if (src_kind > self_kind) { |
| 664 |
// Use value in the source kind range to trigger proper kind switch |
| 665 |
int32_t codepoint = (src_kind == 2) ? 0x100 : 0x10000; |
| 666 |
if (string_writer_switch_kind(self, codepoint) == CPY_NONE_ERROR) { |
| 667 |
return CPY_NONE_ERROR; |
| 668 |
} |
| 669 |
self_kind = self->kind; |
| 670 |
} |
| 671 |
|
| 672 |
// Ensure we have enough space |
| 673 |
if (!ensure_string_writer_size(self, str_len)) { |
| 674 |
return CPY_NONE_ERROR; |
| 675 |
} |
| 676 |
|
| 677 |
// Copy data - ASCII/Latin1 (kind 1) are handled uniformly |
| 678 |
if (self_kind == src_kind) { |
| 679 |
// Same kind, direct copy |
| 680 |
memcpy(self->buf + self->len * self_kind, src_data, str_len * src_kind); |
| 681 |
} else { |
| 682 |
// Different kinds, convert character by character |
| 683 |
for (Py_ssize_t i = 0; i < str_len; i++) { |
| 684 |
Py_UCS4 ch = PyUnicode_READ(src_kind, src_data, i); |
| 685 |
PyUnicode_WRITE(self_kind, self->buf, self->len + i, ch); |
| 686 |
} |
| 687 |
} |
| 688 |
|
| 689 |
self->len += str_len; |
| 690 |
return CPY_NONE; |
| 691 |
} |
| 692 |
|
| 693 |
static PyObject* |
| 694 |
StringWriter_write(PyObject *self, PyObject *const *args, size_t nargs) { |
| 695 |
if (unlikely(nargs != 1)) { |
| 696 |
PyErr_Format(PyExc_TypeError, |
| 697 |
"write() takes exactly 1 argument (%zu given)", nargs); |
| 698 |
return NULL; |
| 699 |
} |
| 700 |
if (!check_string_writer(self)) { |
| 701 |
return NULL; |
| 702 |
} |
| 703 |
PyObject *value = args[0]; |
| 704 |
if (unlikely(!PyUnicode_Check(value))) { |
| 705 |
PyErr_SetString(PyExc_TypeError, "value must be a str object"); |
| 706 |
return NULL; |
| 707 |
} |
| 708 |
if (unlikely(StringWriter_write_internal(self, value) == CPY_NONE_ERROR)) { |
| 709 |
return NULL; |
| 710 |
} |
| 711 |
Py_INCREF(Py_None); |
| 712 |
return Py_None; |
| 713 |
} |
| 714 |
|
| 715 |
// Convert string data to next larger kind (1->2 or 2->4) |
| 716 |
static void convert_string_data_in_place(char *buf, Py_ssize_t len, |
| 717 |
char old_kind, char new_kind) { |
| 718 |
if (old_kind == 1 && new_kind == 2) { |
| 719 |
// Convert backwards to avoid overwriting |
| 720 |
for (Py_ssize_t i = len - 1; i >= 0; i--) { |
| 721 |
uint8_t val = (uint8_t)buf[i]; |
| 722 |
uint16_t expanded = val; |
| 723 |
memcpy(buf + i * 2, &expanded, 2); |
| 724 |
} |
| 725 |
} else if (old_kind == 2 && new_kind == 4) { |
| 726 |
// Convert backwards to avoid overwriting |
| 727 |
for (Py_ssize_t i = len - 1; i >= 0; i--) { |
| 728 |
uint16_t val; |
| 729 |
memcpy(&val, buf + i * 2, 2); |
| 730 |
uint32_t expanded = val; |
| 731 |
memcpy(buf + i * 4, &expanded, 4); |
| 732 |
} |
| 733 |
} else { |
| 734 |
assert(false); |
| 735 |
} |
| 736 |
} |
| 737 |
|
| 738 |
static char convert_string_buffer_kind(StringWriterObject *self, char old_kind, char new_kind) { |
| 739 |
// new_kind is always 2 or 4, so the max representable len is PY_SSIZE_T_MAX >> {1,2}. |
| 740 |
// Use a shift instead of a division for cheap overflow check. |
| 741 |
Py_ssize_t max_len = PY_SSIZE_T_MAX >> (new_kind == 4 ? 2 : 1); |
| 742 |
if (unlikely(self->len > max_len)) { |
| 743 |
PyErr_NoMemory(); |
| 744 |
return CPY_NONE_ERROR; |
| 745 |
} |
| 746 |
// Current buffer size in bytes |
| 747 |
Py_ssize_t current_buf_size = (self->buf == self->data) ? WRITER_EMBEDDED_BUF_LEN : (self->capacity * old_kind); |
| 748 |
// Needed buffer size in bytes for new kind |
| 749 |
Py_ssize_t needed_size = self->len * new_kind; |
| 750 |
|
| 751 |
if (current_buf_size >= needed_size) { |
| 752 |
// Convert in place |
| 753 |
convert_string_data_in_place(self->buf, self->len, old_kind, new_kind); |
| 754 |
self->kind = new_kind; |
| 755 |
self->capacity = current_buf_size / new_kind; |
| 756 |
} else { |
| 757 |
// Need to allocate new buffer |
| 758 |
if (!grow_string_buffer_helper(self, self->len, new_kind)) { |
| 759 |
return CPY_NONE_ERROR; |
| 760 |
} |
| 761 |
} |
| 762 |
return CPY_NONE; |
| 763 |
} |
| 764 |
|
| 765 |
static char string_writer_switch_kind(StringWriterObject *self, int32_t value) { |
| 766 |
if (self->kind == 1) { |
| 767 |
// Either kind 1 -> 2 or 1 -> 4. First switch to kind 2. |
| 768 |
if (convert_string_buffer_kind(self, 1, 2) == CPY_NONE_ERROR) |
| 769 |
return CPY_NONE_ERROR; |
| 770 |
if ((uint32_t)value > 0xffff) { |
| 771 |
// Call recursively to switch from kind 2 to 4 |
| 772 |
return string_writer_switch_kind(self, value); |
| 773 |
} |
| 774 |
return CPY_NONE; |
| 775 |
} else { |
| 776 |
// Must be kind 2 -> 4 |
| 777 |
assert(self->kind == 2); |
| 778 |
assert((uint32_t)value > 0xffff); |
| 779 |
return convert_string_buffer_kind(self, 2, 4); |
| 780 |
} |
| 781 |
} |
| 782 |
|
| 783 |
// Handle all append cases except for append that stays within kind 1 |
| 784 |
static char string_append_slow_path(StringWriterObject *self, int32_t value) { |
| 785 |
if (self->kind == 2) { |
| 786 |
if ((uint32_t)value <= 0xffff) { |
| 787 |
// Fast path - kind 2 stays the same |
| 788 |
if (!ensure_string_writer_size(self, 1)) |
| 789 |
return CPY_NONE_ERROR; |
| 790 |
// Copy 2-byte character to buffer |
| 791 |
uint16_t val16 = (uint16_t)value; |
| 792 |
memcpy(self->buf + self->len * 2, &val16, 2); |
| 793 |
self->len++; |
| 794 |
return CPY_NONE; |
| 795 |
} |
| 796 |
// Always validate code point range before promotion (but after fast path). |
| 797 |
if (unlikely((uint32_t)value > 0x10FFFF)) |
| 798 |
goto fail_range; |
| 799 |
if (string_writer_switch_kind(self, value) == CPY_NONE_ERROR) |
| 800 |
return CPY_NONE_ERROR; |
| 801 |
return string_append_slow_path(self, value); |
| 802 |
} else if (self->kind == 1) { |
| 803 |
// Check precondition -- this must only be used on slow path |
| 804 |
assert((uint32_t)value > 0xff); |
| 805 |
if (unlikely((uint32_t)value > 0x10FFFF)) |
| 806 |
goto fail_range; |
| 807 |
if (string_writer_switch_kind(self, value) == CPY_NONE_ERROR) |
| 808 |
return CPY_NONE_ERROR; |
| 809 |
return string_append_slow_path(self, value); |
| 810 |
} |
| 811 |
assert(self->kind == 4); |
| 812 |
if (unlikely((uint32_t)value > 0x10FFFF)) |
| 813 |
goto fail_range; |
| 814 |
if (!ensure_string_writer_size(self, 1)) |
| 815 |
return CPY_NONE_ERROR; |
| 816 |
// Copy 4-byte character to buffer |
| 817 |
uint32_t val32 = (uint32_t)value; |
| 818 |
memcpy(self->buf + self->len * 4, &val32, 4); |
| 819 |
self->len++; |
| 820 |
return CPY_NONE; |
| 821 |
|
| 822 |
fail_range: |
| 823 |
PyErr_Format(PyExc_ValueError, |
| 824 |
"code point %d is outside valid Unicode range (0-1114111)", value); |
| 825 |
return CPY_NONE_ERROR; |
| 826 |
} |
| 827 |
|
| 828 |
static inline char |
| 829 |
StringWriter_append_internal(StringWriterObject *self, int32_t value) { |
| 830 |
char kind = self->kind; |
| 831 |
if (kind == 1 && (uint32_t)value < 256) { |
| 832 |
if (!ensure_string_writer_size(self, 1)) |
| 833 |
return CPY_NONE_ERROR; |
| 834 |
self->buf[self->len++] = value; |
| 835 |
self->kind = kind; |
| 836 |
return CPY_NONE; |
| 837 |
} |
| 838 |
return string_append_slow_path(self, value); |
| 839 |
} |
| 840 |
|
| 841 |
static PyObject* |
| 842 |
StringWriter_append(PyObject *self, PyObject *const *args, size_t nargs) { |
| 843 |
if (unlikely(nargs != 1)) { |
| 844 |
PyErr_Format(PyExc_TypeError, |
| 845 |
"append() takes exactly 1 argument (%zu given)", nargs); |
| 846 |
return NULL; |
| 847 |
} |
| 848 |
if (!check_string_writer(self)) { |
| 849 |
return NULL; |
| 850 |
} |
| 851 |
PyObject *value = args[0]; |
| 852 |
int32_t unboxed = CPyLong_AsInt32(value); |
| 853 |
if (unlikely(unboxed == CPY_LL_INT_ERROR && PyErr_Occurred())) { |
| 854 |
CPy_TypeError("i32", value); |
| 855 |
return NULL; |
| 856 |
} |
| 857 |
if (unlikely(StringWriter_append_internal((StringWriterObject *)self, unboxed) == CPY_NONE_ERROR)) { |
| 858 |
return NULL; |
| 859 |
} |
| 860 |
Py_INCREF(Py_None); |
| 861 |
return Py_None; |
| 862 |
} |
| 863 |
|
| 864 |
static PyTypeObject * |
| 865 |
StringWriter_type_internal(void) { |
| 866 |
return &StringWriterType; // Return borrowed reference |
| 867 |
}; |
| 868 |
|
| 869 |
static CPyTagged |
| 870 |
StringWriter_len_internal(PyObject *self) { |
| 871 |
StringWriterObject *writer = (StringWriterObject *)self; |
| 872 |
return writer->len << 1; |
| 873 |
} |
| 874 |
|
| 875 |
// End of StringWriter |
| 876 |
|
| 877 |
// Helper for write_*_le/be functions - validates args and returns BytesWriter |
| 878 |
static inline BytesWriterObject * |
| 879 |
parse_write_args(PyObject *const *args, size_t nargs, const char *func_name) { |
| 880 |
if (unlikely(nargs != 2)) { |
| 881 |
PyErr_Format(PyExc_TypeError, |
| 882 |
"%s() takes exactly 2 arguments (%zu given)", func_name, nargs); |
| 883 |
return NULL; |
| 884 |
} |
| 885 |
PyObject *writer = args[0]; |
| 886 |
if (!check_bytes_writer(writer)) { |
| 887 |
return NULL; |
| 888 |
} |
| 889 |
return (BytesWriterObject *)writer; |
| 890 |
} |
| 891 |
|
| 892 |
// Helper for read_*_le/be functions - validates args and returns data pointer |
| 893 |
// Returns NULL on error, sets *out_index to the validated index on success |
| 894 |
static inline const unsigned char * |
| 895 |
parse_read_args(PyObject *const *args, size_t nargs, const char *func_name, |
| 896 |
Py_ssize_t num_bytes, int64_t *out_index) { |
| 897 |
if (unlikely(nargs != 2)) { |
| 898 |
PyErr_Format(PyExc_TypeError, |
| 899 |
"%s() takes exactly 2 arguments (%zu given)", func_name, nargs); |
| 900 |
return NULL; |
| 901 |
} |
| 902 |
PyObject *bytes_obj = args[0]; |
| 903 |
if (unlikely(!PyBytes_Check(bytes_obj))) { |
| 904 |
PyErr_Format(PyExc_TypeError, "%s() argument 1 must be bytes", func_name); |
| 905 |
return NULL; |
| 906 |
} |
| 907 |
int64_t index = CPyLong_AsInt64(args[1]); |
| 908 |
if (unlikely(index == CPY_LL_INT_ERROR && PyErr_Occurred())) { |
| 909 |
return NULL; |
| 910 |
} |
| 911 |
if (unlikely(index < 0)) { |
| 912 |
PyErr_SetString(PyExc_ValueError, "index must be non-negative"); |
| 913 |
return NULL; |
| 914 |
} |
| 915 |
Py_ssize_t size = PyBytes_GET_SIZE(bytes_obj); |
| 916 |
if (unlikely(index > size - num_bytes)) { |
| 917 |
PyErr_Format(PyExc_IndexError, |
| 918 |
"index %lld out of range for bytes of length %zd", |
| 919 |
(long long)index, size); |
| 920 |
return NULL; |
| 921 |
} |
| 922 |
*out_index = index; |
| 923 |
return (const unsigned char *)PyBytes_AS_STRING(bytes_obj); |
| 924 |
} |
| 925 |
|
| 926 |
static PyObject* |
| 927 |
write_i16_le(PyObject *module, PyObject *const *args, size_t nargs) { |
| 928 |
BytesWriterObject *bw = parse_write_args(args, nargs, "write_i16_le"); |
| 929 |
if (bw == NULL) |
| 930 |
return NULL; |
| 931 |
int16_t unboxed = CPyLong_AsInt16(args[1]); |
| 932 |
if (unlikely(unboxed == CPY_LL_INT_ERROR && PyErr_Occurred())) |
| 933 |
return NULL; |
| 934 |
if (unlikely(!ensure_bytes_writer_size(bw, 2))) |
| 935 |
return NULL; |
| 936 |
BytesWriter_WriteI16LEUnsafe(bw, unboxed); |
| 937 |
Py_RETURN_NONE; |
| 938 |
} |
| 939 |
|
| 940 |
static PyObject* |
| 941 |
write_i16_be(PyObject *module, PyObject *const *args, size_t nargs) { |
| 942 |
BytesWriterObject *bw = parse_write_args(args, nargs, "write_i16_be"); |
| 943 |
if (bw == NULL) |
| 944 |
return NULL; |
| 945 |
int16_t unboxed = CPyLong_AsInt16(args[1]); |
| 946 |
if (unlikely(unboxed == CPY_LL_INT_ERROR && PyErr_Occurred())) |
| 947 |
return NULL; |
| 948 |
if (unlikely(!ensure_bytes_writer_size(bw, 2))) |
| 949 |
return NULL; |
| 950 |
BytesWriter_WriteI16BEUnsafe(bw, unboxed); |
| 951 |
Py_RETURN_NONE; |
| 952 |
} |
| 953 |
|
| 954 |
static PyObject* |
| 955 |
read_i16_le(PyObject *module, PyObject *const *args, size_t nargs) { |
| 956 |
int64_t index; |
| 957 |
const unsigned char *data = parse_read_args(args, nargs, "read_i16_le", 2, &index); |
| 958 |
if (data == NULL) |
| 959 |
return NULL; |
| 960 |
return PyLong_FromLong(CPyBytes_ReadI16LEUnsafe(data + index)); |
| 961 |
} |
| 962 |
|
| 963 |
static PyObject* |
| 964 |
read_i16_be(PyObject *module, PyObject *const *args, size_t nargs) { |
| 965 |
int64_t index; |
| 966 |
const unsigned char *data = parse_read_args(args, nargs, "read_i16_be", 2, &index); |
| 967 |
if (data == NULL) |
| 968 |
return NULL; |
| 969 |
return PyLong_FromLong(CPyBytes_ReadI16BEUnsafe(data + index)); |
| 970 |
} |
| 971 |
|
| 972 |
static PyObject* |
| 973 |
write_i32_le(PyObject *module, PyObject *const *args, size_t nargs) { |
| 974 |
BytesWriterObject *bw = parse_write_args(args, nargs, "write_i32_le"); |
| 975 |
if (bw == NULL) |
| 976 |
return NULL; |
| 977 |
int32_t unboxed = CPyLong_AsInt32(args[1]); |
| 978 |
if (unlikely(unboxed == CPY_LL_INT_ERROR && PyErr_Occurred())) |
| 979 |
return NULL; |
| 980 |
if (unlikely(!ensure_bytes_writer_size(bw, 4))) |
| 981 |
return NULL; |
| 982 |
BytesWriter_WriteI32LEUnsafe(bw, unboxed); |
| 983 |
Py_RETURN_NONE; |
| 984 |
} |
| 985 |
|
| 986 |
static PyObject* |
| 987 |
write_i32_be(PyObject *module, PyObject *const *args, size_t nargs) { |
| 988 |
BytesWriterObject *bw = parse_write_args(args, nargs, "write_i32_be"); |
| 989 |
if (bw == NULL) |
| 990 |
return NULL; |
| 991 |
int32_t unboxed = CPyLong_AsInt32(args[1]); |
| 992 |
if (unlikely(unboxed == CPY_LL_INT_ERROR && PyErr_Occurred())) |
| 993 |
return NULL; |
| 994 |
if (unlikely(!ensure_bytes_writer_size(bw, 4))) |
| 995 |
return NULL; |
| 996 |
BytesWriter_WriteI32BEUnsafe(bw, unboxed); |
| 997 |
Py_RETURN_NONE; |
| 998 |
} |
| 999 |
|
| 1000 |
static PyObject* |
| 1001 |
read_i32_le(PyObject *module, PyObject *const *args, size_t nargs) { |
| 1002 |
int64_t index; |
| 1003 |
const unsigned char *data = parse_read_args(args, nargs, "read_i32_le", 4, &index); |
| 1004 |
if (data == NULL) |
| 1005 |
return NULL; |
| 1006 |
return PyLong_FromLong(CPyBytes_ReadI32LEUnsafe(data + index)); |
| 1007 |
} |
| 1008 |
|
| 1009 |
static PyObject* |
| 1010 |
read_i32_be(PyObject *module, PyObject *const *args, size_t nargs) { |
| 1011 |
int64_t index; |
| 1012 |
const unsigned char *data = parse_read_args(args, nargs, "read_i32_be", 4, &index); |
| 1013 |
if (data == NULL) |
| 1014 |
return NULL; |
| 1015 |
return PyLong_FromLong(CPyBytes_ReadI32BEUnsafe(data + index)); |
| 1016 |
} |
| 1017 |
|
| 1018 |
static PyObject* |
| 1019 |
write_i64_le(PyObject *module, PyObject *const *args, size_t nargs) { |
| 1020 |
BytesWriterObject *bw = parse_write_args(args, nargs, "write_i64_le"); |
| 1021 |
if (bw == NULL) |
| 1022 |
return NULL; |
| 1023 |
int64_t unboxed = CPyLong_AsInt64(args[1]); |
| 1024 |
if (unlikely(unboxed == CPY_LL_INT_ERROR && PyErr_Occurred())) |
| 1025 |
return NULL; |
| 1026 |
if (unlikely(!ensure_bytes_writer_size(bw, 8))) |
| 1027 |
return NULL; |
| 1028 |
BytesWriter_WriteI64LEUnsafe(bw, unboxed); |
| 1029 |
Py_RETURN_NONE; |
| 1030 |
} |
| 1031 |
|
| 1032 |
static PyObject* |
| 1033 |
write_i64_be(PyObject *module, PyObject *const *args, size_t nargs) { |
| 1034 |
BytesWriterObject *bw = parse_write_args(args, nargs, "write_i64_be"); |
| 1035 |
if (bw == NULL) |
| 1036 |
return NULL; |
| 1037 |
int64_t unboxed = CPyLong_AsInt64(args[1]); |
| 1038 |
if (unlikely(unboxed == CPY_LL_INT_ERROR && PyErr_Occurred())) |
| 1039 |
return NULL; |
| 1040 |
if (unlikely(!ensure_bytes_writer_size(bw, 8))) |
| 1041 |
return NULL; |
| 1042 |
BytesWriter_WriteI64BEUnsafe(bw, unboxed); |
| 1043 |
Py_RETURN_NONE; |
| 1044 |
} |
| 1045 |
|
| 1046 |
static PyObject* |
| 1047 |
read_i64_le(PyObject *module, PyObject *const *args, size_t nargs) { |
| 1048 |
int64_t index; |
| 1049 |
const unsigned char *data = parse_read_args(args, nargs, "read_i64_le", 8, &index); |
| 1050 |
if (data == NULL) |
| 1051 |
return NULL; |
| 1052 |
return PyLong_FromLongLong(CPyBytes_ReadI64LEUnsafe(data + index)); |
| 1053 |
} |
| 1054 |
|
| 1055 |
static PyObject* |
| 1056 |
read_i64_be(PyObject *module, PyObject *const *args, size_t nargs) { |
| 1057 |
int64_t index; |
| 1058 |
const unsigned char *data = parse_read_args(args, nargs, "read_i64_be", 8, &index); |
| 1059 |
if (data == NULL) |
| 1060 |
return NULL; |
| 1061 |
return PyLong_FromLongLong(CPyBytes_ReadI64BEUnsafe(data + index)); |
| 1062 |
} |
| 1063 |
|
| 1064 |
static PyObject* |
| 1065 |
write_f32_le(PyObject *module, PyObject *const *args, size_t nargs) { |
| 1066 |
BytesWriterObject *bw = parse_write_args(args, nargs, "write_f32_le"); |
| 1067 |
if (bw == NULL) |
| 1068 |
return NULL; |
| 1069 |
double unboxed = PyFloat_AsDouble(args[1]); |
| 1070 |
if (unlikely(unboxed == -1.0 && PyErr_Occurred())) |
| 1071 |
return NULL; |
| 1072 |
if (unlikely(!ensure_bytes_writer_size(bw, 4))) |
| 1073 |
return NULL; |
| 1074 |
BytesWriter_WriteF32LEUnsafe(bw, (float)unboxed); |
| 1075 |
Py_RETURN_NONE; |
| 1076 |
} |
| 1077 |
|
| 1078 |
static PyObject* |
| 1079 |
write_f32_be(PyObject *module, PyObject *const *args, size_t nargs) { |
| 1080 |
BytesWriterObject *bw = parse_write_args(args, nargs, "write_f32_be"); |
| 1081 |
if (bw == NULL) |
| 1082 |
return NULL; |
| 1083 |
double unboxed = PyFloat_AsDouble(args[1]); |
| 1084 |
if (unlikely(unboxed == -1.0 && PyErr_Occurred())) |
| 1085 |
return NULL; |
| 1086 |
if (unlikely(!ensure_bytes_writer_size(bw, 4))) |
| 1087 |
return NULL; |
| 1088 |
BytesWriter_WriteF32BEUnsafe(bw, (float)unboxed); |
| 1089 |
Py_RETURN_NONE; |
| 1090 |
} |
| 1091 |
|
| 1092 |
static PyObject* |
| 1093 |
read_f32_le(PyObject *module, PyObject *const *args, size_t nargs) { |
| 1094 |
int64_t index; |
| 1095 |
const unsigned char *data = parse_read_args(args, nargs, "read_f32_le", 4, &index); |
| 1096 |
if (data == NULL) |
| 1097 |
return NULL; |
| 1098 |
return PyFloat_FromDouble((double)CPyBytes_ReadF32LEUnsafe(data + index)); |
| 1099 |
} |
| 1100 |
|
| 1101 |
static PyObject* |
| 1102 |
read_f32_be(PyObject *module, PyObject *const *args, size_t nargs) { |
| 1103 |
int64_t index; |
| 1104 |
const unsigned char *data = parse_read_args(args, nargs, "read_f32_be", 4, &index); |
| 1105 |
if (data == NULL) |
| 1106 |
return NULL; |
| 1107 |
return PyFloat_FromDouble((double)CPyBytes_ReadF32BEUnsafe(data + index)); |
| 1108 |
} |
| 1109 |
|
| 1110 |
static PyObject* |
| 1111 |
write_f64_le(PyObject *module, PyObject *const *args, size_t nargs) { |
| 1112 |
BytesWriterObject *bw = parse_write_args(args, nargs, "write_f64_le"); |
| 1113 |
if (bw == NULL) |
| 1114 |
return NULL; |
| 1115 |
double unboxed = PyFloat_AsDouble(args[1]); |
| 1116 |
if (unlikely(unboxed == -1.0 && PyErr_Occurred())) |
| 1117 |
return NULL; |
| 1118 |
if (unlikely(!ensure_bytes_writer_size(bw, 8))) |
| 1119 |
return NULL; |
| 1120 |
BytesWriter_WriteF64LEUnsafe(bw, unboxed); |
| 1121 |
Py_RETURN_NONE; |
| 1122 |
} |
| 1123 |
|
| 1124 |
static PyObject* |
| 1125 |
write_f64_be(PyObject *module, PyObject *const *args, size_t nargs) { |
| 1126 |
BytesWriterObject *bw = parse_write_args(args, nargs, "write_f64_be"); |
| 1127 |
if (bw == NULL) |
| 1128 |
return NULL; |
| 1129 |
double unboxed = PyFloat_AsDouble(args[1]); |
| 1130 |
if (unlikely(unboxed == -1.0 && PyErr_Occurred())) |
| 1131 |
return NULL; |
| 1132 |
if (unlikely(!ensure_bytes_writer_size(bw, 8))) |
| 1133 |
return NULL; |
| 1134 |
BytesWriter_WriteF64BEUnsafe(bw, unboxed); |
| 1135 |
Py_RETURN_NONE; |
| 1136 |
} |
| 1137 |
|
| 1138 |
static PyObject* |
| 1139 |
read_f64_le(PyObject *module, PyObject *const *args, size_t nargs) { |
| 1140 |
int64_t index; |
| 1141 |
const unsigned char *data = parse_read_args(args, nargs, "read_f64_le", 8, &index); |
| 1142 |
if (data == NULL) |
| 1143 |
return NULL; |
| 1144 |
return PyFloat_FromDouble(CPyBytes_ReadF64LEUnsafe(data + index)); |
| 1145 |
} |
| 1146 |
|
| 1147 |
static PyObject* |
| 1148 |
read_f64_be(PyObject *module, PyObject *const *args, size_t nargs) { |
| 1149 |
int64_t index; |
| 1150 |
const unsigned char *data = parse_read_args(args, nargs, "read_f64_be", 8, &index); |
| 1151 |
if (data == NULL) |
| 1152 |
return NULL; |
| 1153 |
return PyFloat_FromDouble(CPyBytes_ReadF64BEUnsafe(data + index)); |
| 1154 |
} |
| 1155 |
|
| 1156 |
// Python-level wrappers (`cp_*`) for interpreted callers. The C-side names |
| 1157 |
// are prefixed `cp_` to avoid colliding with libc's <ctype.h> isspace etc. |
| 1158 |
// The LibRTStrings_Is* helpers themselves are static inline in librt_strings.h |
| 1159 |
// so they compile directly into mypyc-emitted code with no capsule |
| 1160 |
// indirection. |
| 1161 |
|
| 1162 |
// Parse a Python int as i32 codepoint. Returns 0 on success and writes |
| 1163 |
// the value to *out; returns -1 on error with a Python exception set. |
| 1164 |
static int |
| 1165 |
cp_parse_i32(PyObject *arg, int32_t *out) { |
| 1166 |
int overflow; |
| 1167 |
long c = PyLong_AsLongAndOverflow(arg, &overflow); |
| 1168 |
if (c == -1 && PyErr_Occurred()) |
| 1169 |
return -1; |
| 1170 |
if (overflow != 0 || c < INT32_MIN || c > INT32_MAX) { |
| 1171 |
PyErr_SetString(PyExc_OverflowError, |
| 1172 |
"codepoint out of i32 range"); |
| 1173 |
return -1; |
| 1174 |
} |
| 1175 |
*out = (int32_t)c; |
| 1176 |
return 0; |
| 1177 |
} |
| 1178 |
|
| 1179 |
#define DEFINE_CP_BOOL_WRAPPER(name, fn) \ |
| 1180 |
static PyObject* \ |
| 1181 |
cp_##name(PyObject *module, PyObject *arg) { \ |
| 1182 |
int32_t c; \ |
| 1183 |
if (cp_parse_i32(arg, &c) < 0) \ |
| 1184 |
return NULL; \ |
| 1185 |
return PyBool_FromLong(fn(c)); \ |
| 1186 |
} |
| 1187 |
|
| 1188 |
DEFINE_CP_BOOL_WRAPPER(isspace, LibRTStrings_IsSpace) |
| 1189 |
DEFINE_CP_BOOL_WRAPPER(isdigit, LibRTStrings_IsDigit) |
| 1190 |
DEFINE_CP_BOOL_WRAPPER(isalnum, LibRTStrings_IsAlnum) |
| 1191 |
DEFINE_CP_BOOL_WRAPPER(isalpha, LibRTStrings_IsAlpha) |
| 1192 |
DEFINE_CP_BOOL_WRAPPER(isidentifier, LibRTStrings_IsIdentifier) |
| 1193 |
|
| 1194 |
#define DEFINE_CP_I32_WRAPPER(name, fn) \ |
| 1195 |
static PyObject* \ |
| 1196 |
cp_##name(PyObject *module, PyObject *arg) { \ |
| 1197 |
int32_t c; \ |
| 1198 |
if (cp_parse_i32(arg, &c) < 0) \ |
| 1199 |
return NULL; \ |
| 1200 |
return PyLong_FromLong((long) fn(c)); \ |
| 1201 |
} |
| 1202 |
|
| 1203 |
DEFINE_CP_I32_WRAPPER(toupper, LibRTStrings_ToUpper) |
| 1204 |
DEFINE_CP_I32_WRAPPER(tolower, LibRTStrings_ToLower) |
| 1205 |
|
| 1206 |
static PyMethodDef librt_strings_module_methods[] = { |
| 1207 |
{"write_i16_le", (PyCFunction) write_i16_le, METH_FASTCALL, |
| 1208 |
PyDoc_STR("Write a 16-bit signed integer to BytesWriter in little-endian format") |
| 1209 |
}, |
| 1210 |
{"write_i16_be", (PyCFunction) write_i16_be, METH_FASTCALL, |
| 1211 |
PyDoc_STR("Write a 16-bit signed integer to BytesWriter in big-endian format") |
| 1212 |
}, |
| 1213 |
{"read_i16_le", (PyCFunction) read_i16_le, METH_FASTCALL, |
| 1214 |
PyDoc_STR("Read a 16-bit signed integer from bytes in little-endian format") |
| 1215 |
}, |
| 1216 |
{"read_i16_be", (PyCFunction) read_i16_be, METH_FASTCALL, |
| 1217 |
PyDoc_STR("Read a 16-bit signed integer from bytes in big-endian format") |
| 1218 |
}, |
| 1219 |
{"write_i32_le", (PyCFunction) write_i32_le, METH_FASTCALL, |
| 1220 |
PyDoc_STR("Write a 32-bit signed integer to BytesWriter in little-endian format") |
| 1221 |
}, |
| 1222 |
{"write_i32_be", (PyCFunction) write_i32_be, METH_FASTCALL, |
| 1223 |
PyDoc_STR("Write a 32-bit signed integer to BytesWriter in big-endian format") |
| 1224 |
}, |
| 1225 |
{"read_i32_le", (PyCFunction) read_i32_le, METH_FASTCALL, |
| 1226 |
PyDoc_STR("Read a 32-bit signed integer from bytes in little-endian format") |
| 1227 |
}, |
| 1228 |
{"read_i32_be", (PyCFunction) read_i32_be, METH_FASTCALL, |
| 1229 |
PyDoc_STR("Read a 32-bit signed integer from bytes in big-endian format") |
| 1230 |
}, |
| 1231 |
{"write_i64_le", (PyCFunction) write_i64_le, METH_FASTCALL, |
| 1232 |
PyDoc_STR("Write a 64-bit signed integer to BytesWriter in little-endian format") |
| 1233 |
}, |
| 1234 |
{"write_i64_be", (PyCFunction) write_i64_be, METH_FASTCALL, |
| 1235 |
PyDoc_STR("Write a 64-bit signed integer to BytesWriter in big-endian format") |
| 1236 |
}, |
| 1237 |
{"read_i64_le", (PyCFunction) read_i64_le, METH_FASTCALL, |
| 1238 |
PyDoc_STR("Read a 64-bit signed integer from bytes in little-endian format") |
| 1239 |
}, |
| 1240 |
{"read_i64_be", (PyCFunction) read_i64_be, METH_FASTCALL, |
| 1241 |
PyDoc_STR("Read a 64-bit signed integer from bytes in big-endian format") |
| 1242 |
}, |
| 1243 |
{"write_f32_le", (PyCFunction) write_f32_le, METH_FASTCALL, |
| 1244 |
PyDoc_STR("Write a 32-bit float to BytesWriter in little-endian format") |
| 1245 |
}, |
| 1246 |
{"write_f32_be", (PyCFunction) write_f32_be, METH_FASTCALL, |
| 1247 |
PyDoc_STR("Write a 32-bit float to BytesWriter in big-endian format") |
| 1248 |
}, |
| 1249 |
{"read_f32_le", (PyCFunction) read_f32_le, METH_FASTCALL, |
| 1250 |
PyDoc_STR("Read a 32-bit float from bytes in little-endian format") |
| 1251 |
}, |
| 1252 |
{"read_f32_be", (PyCFunction) read_f32_be, METH_FASTCALL, |
| 1253 |
PyDoc_STR("Read a 32-bit float from bytes in big-endian format") |
| 1254 |
}, |
| 1255 |
{"write_f64_le", (PyCFunction) write_f64_le, METH_FASTCALL, |
| 1256 |
PyDoc_STR("Write a 64-bit float to BytesWriter in little-endian format") |
| 1257 |
}, |
| 1258 |
{"write_f64_be", (PyCFunction) write_f64_be, METH_FASTCALL, |
| 1259 |
PyDoc_STR("Write a 64-bit float to BytesWriter in big-endian format") |
| 1260 |
}, |
| 1261 |
{"read_f64_le", (PyCFunction) read_f64_le, METH_FASTCALL, |
| 1262 |
PyDoc_STR("Read a 64-bit float from bytes in little-endian format") |
| 1263 |
}, |
| 1264 |
{"read_f64_be", (PyCFunction) read_f64_be, METH_FASTCALL, |
| 1265 |
PyDoc_STR("Read a 64-bit float from bytes in big-endian format") |
| 1266 |
}, |
| 1267 |
{"isspace", cp_isspace, METH_O, |
| 1268 |
PyDoc_STR("Test whether a codepoint (i32) is Unicode whitespace.") |
| 1269 |
}, |
| 1270 |
{"isdigit", cp_isdigit, METH_O, |
| 1271 |
PyDoc_STR("Test whether a codepoint (i32) is a Unicode digit.") |
| 1272 |
}, |
| 1273 |
{"isalnum", cp_isalnum, METH_O, |
| 1274 |
PyDoc_STR("Test whether a codepoint (i32) is alphanumeric.") |
| 1275 |
}, |
| 1276 |
{"isalpha", cp_isalpha, METH_O, |
| 1277 |
PyDoc_STR("Test whether a codepoint (i32) is a Unicode letter.") |
| 1278 |
}, |
| 1279 |
{"isidentifier", cp_isidentifier, METH_O, |
| 1280 |
PyDoc_STR("Test whether a codepoint (i32) is a valid identifier start (XID_Start).") |
| 1281 |
}, |
| 1282 |
{"toupper", cp_toupper, METH_O, |
| 1283 |
PyDoc_STR("Single-codepoint uppercase mapping for a codepoint (i32). Returns the input unchanged if the Unicode uppercase expands to multiple codepoints (e.g. U+00DF uppercases to \"SS\"); use str.upper() for full Unicode case conversion.") |
| 1284 |
}, |
| 1285 |
{"tolower", cp_tolower, METH_O, |
| 1286 |
PyDoc_STR("Single-codepoint lowercase mapping for a codepoint (i32). Returns the input unchanged if the Unicode lowercase expands to multiple codepoints; use str.lower() for full Unicode case conversion.") |
| 1287 |
}, |
| 1288 |
{NULL, NULL, 0, NULL} |
| 1289 |
}; |
| 1290 |
|
| 1291 |
static int |
| 1292 |
strings_abi_version(void) { |
| 1293 |
return LIBRT_STRINGS_ABI_VERSION; |
| 1294 |
} |
| 1295 |
|
| 1296 |
static int |
| 1297 |
strings_api_version(void) { |
| 1298 |
return LIBRT_STRINGS_API_VERSION; |
| 1299 |
} |
| 1300 |
|
| 1301 |
static int |
| 1302 |
librt_strings_module_exec(PyObject *m) |
| 1303 |
{ |
| 1304 |
if (PyType_Ready(&BytesWriterType) < 0) { |
| 1305 |
return -1; |
| 1306 |
} |
| 1307 |
if (PyType_Ready(&StringWriterType) < 0) { |
| 1308 |
return -1; |
| 1309 |
} |
| 1310 |
if (PyModule_AddObjectRef(m, "BytesWriter", (PyObject *) &BytesWriterType) < 0) { |
| 1311 |
return -1; |
| 1312 |
} |
| 1313 |
if (PyModule_AddObjectRef(m, "StringWriter", (PyObject *) &StringWriterType) < 0) { |
| 1314 |
return -1; |
| 1315 |
} |
| 1316 |
|
| 1317 |
// Export mypy internal C API, be careful with the order! |
| 1318 |
static void *librt_strings_api[LIBRT_STRINGS_API_LEN] = { |
| 1319 |
(void *)strings_abi_version, |
| 1320 |
(void *)strings_api_version, |
| 1321 |
(void *)BytesWriter_internal, |
| 1322 |
(void *)BytesWriter_getvalue_internal, |
| 1323 |
(void *)BytesWriter_append_internal, |
| 1324 |
(void *)_grow_buffer, |
| 1325 |
(void *)BytesWriter_type_internal, |
| 1326 |
(void *)BytesWriter_truncate_internal, |
| 1327 |
(void *)StringWriter_internal, |
| 1328 |
(void *)StringWriter_getvalue_internal, |
| 1329 |
(void *)string_append_slow_path, |
| 1330 |
(void *)StringWriter_type_internal, |
| 1331 |
(void *)StringWriter_write_internal, |
| 1332 |
(void *)grow_string_buffer, |
| 1333 |
}; |
| 1334 |
PyObject *c_api_object = PyCapsule_New((void *)librt_strings_api, "librt.strings._C_API", NULL); |
| 1335 |
if (PyModule_Add(m, "_C_API", c_api_object) < 0) { |
| 1336 |
return -1; |
| 1337 |
} |
| 1338 |
return 0; |
| 1339 |
} |
| 1340 |
|
| 1341 |
static PyModuleDef_Slot librt_strings_module_slots[] = { |
| 1342 |
{Py_mod_exec, librt_strings_module_exec}, |
| 1343 |
#ifdef Py_MOD_GIL_NOT_USED |
| 1344 |
{Py_mod_gil, Py_MOD_GIL_NOT_USED}, |
| 1345 |
#endif |
| 1346 |
{0, NULL} |
| 1347 |
}; |
| 1348 |
|
| 1349 |
static PyModuleDef librt_strings_module = { |
| 1350 |
.m_base = PyModuleDef_HEAD_INIT, |
| 1351 |
.m_name = "strings", |
| 1352 |
.m_doc = "Utilities for working with str and bytes objects", |
| 1353 |
.m_size = 0, |
| 1354 |
.m_methods = librt_strings_module_methods, |
| 1355 |
.m_slots = librt_strings_module_slots, |
| 1356 |
}; |
| 1357 |
|
| 1358 |
PyMODINIT_FUNC |
| 1359 |
PyInit_strings(void) |
| 1360 |
{ |
| 1361 |
intern_strings(); |
| 1362 |
return PyModuleDef_Init(&librt_strings_module); |
| 1363 |
} |