Debian Codegraph @

mypyc/lib-rt/stringwriter_extra_ops.h

raw
1 #ifndef STRINGWRITER_EXTRA_OPS_H
2 #define STRINGWRITER_EXTRA_OPS_H
3
4 #include <Python.h>
5 #include <stdbool.h>
6 #include <stdint.h>
7
8 #include "mypyc_util.h"
9 #include "strings/librt_strings_api.h"
10
11 static inline CPyTagged
12 CPyStringWriter_Len(PyObject *obj) {
13 return (CPyTagged)((StringWriterObject *)obj)->len << 1;
14 }
15
16 static inline bool
17 CPyStringWriter_EnsureSize(StringWriterObject *data, Py_ssize_t n) {
18 if (likely(data->capacity - data->len >= n)) {
19 return true;
20 } else {
21 return LibRTStrings_grow_string_buffer(data, n);
22 }
23 }
24
25 static inline char
26 CPyStringWriter_Append(PyObject *obj, int32_t value) {
27 StringWriterObject *self = (StringWriterObject *)obj;
28 char kind = self->kind;
29
30 // Fast path: kind 1 (ASCII/Latin-1) with character < 256
31 if (kind == 1 && (uint32_t)value < 256) {
32 // Store length in local variable to enable additional optimizations
33 Py_ssize_t len = self->len;
34 if (!CPyStringWriter_EnsureSize(self, 1))
35 return CPY_NONE_ERROR;
36 self->buf[len] = (char)value;
37 self->len = len + 1;
38 return CPY_NONE;
39 }
40
41 // Slow path: handles kind switching and other cases
42 return LibRTStrings_string_append_slow_path(self, value);
43 }
44
45 // If index is negative, convert to non-negative index (no range checking)
46 static inline int64_t CPyStringWriter_AdjustIndex(PyObject *obj, int64_t index) {
47 if (index < 0) {
48 return index + ((StringWriterObject *)obj)->len;
49 }
50 return index;
51 }
52
53 static inline bool CPyStringWriter_RangeCheck(PyObject *obj, int64_t index) {
54 return index >= 0 && index < ((StringWriterObject *)obj)->len;
55 }
56
57 static inline int32_t CPyStringWriter_GetItem(PyObject *obj, int64_t index) {
58 StringWriterObject *self = (StringWriterObject *)obj;
59 char kind = self->kind;
60 char *buf = self->buf;
61
62 if (kind == 1) {
63 return (uint8_t)buf[index];
64 } else if (kind == 2) {
65 uint16_t val;
66 memcpy(&val, buf + index * 2, 2);
67 return (int32_t)val;
68 } else {
69 uint32_t val;
70 memcpy(&val, buf + index * 4, 4);
71 return (int32_t)val;
72 }
73 }
74
75 #endif