Debian Codegraph @

mypyc/lib-rt/str_ops.c

raw
1 #include "pythoncapi_compat.h"
2
3 // String primitive operations
4 //
5 // These are registered in mypyc.primitives.str_ops.
6
7 #include <Python.h>
8 #include "CPy.h"
9
10 // The _PyUnicode_CheckConsistency definition has been moved to the internal API
11 // https://github.com/python/cpython/pull/106398
12 #if defined(Py_DEBUG) && CPY_3_13_FEATURES
13 #include "internal/pycore_unicodeobject.h"
14 #endif
15
16 // Copied from cpython.git:Objects/unicodeobject.c@0ef4ffeefd1737c18dc9326133c7894d58108c2e.
17 #define BLOOM_MASK unsigned long
18 #define BLOOM(mask, ch) ((mask & (1UL << ((ch) & (BLOOM_WIDTH - 1)))))
19 #if LONG_BIT >= 128
20 #define BLOOM_WIDTH 128
21 #elif LONG_BIT >= 64
22 #define BLOOM_WIDTH 64
23 #elif LONG_BIT >= 32
24 #define BLOOM_WIDTH 32
25 #else
26 #error "LONG_BIT is smaller than 32"
27 #endif
28
29 // Copied from cpython.git:Objects/unicodeobject.c@0ef4ffeefd1737c18dc9326133c7894d58108c2e.
30 // This is needed for str.strip("...").
31 static inline BLOOM_MASK
32 make_bloom_mask(int kind, const void* ptr, Py_ssize_t len)
33 {
34 #define BLOOM_UPDATE(TYPE, MASK, PTR, LEN) \
35 do { \
36 TYPE *data = (TYPE *)PTR; \
37 TYPE *end = data + LEN; \
38 Py_UCS4 ch; \
39 for (; data != end; data++) { \
40 ch = *data; \
41 MASK |= (1UL << (ch & (BLOOM_WIDTH - 1))); \
42 } \
43 break; \
44 } while (0)
45
46 /* calculate simple bloom-style bitmask for a given unicode string */
47
48 BLOOM_MASK mask;
49
50 mask = 0;
51 switch (kind) {
52 case PyUnicode_1BYTE_KIND:
53 BLOOM_UPDATE(Py_UCS1, mask, ptr, len);
54 break;
55 case PyUnicode_2BYTE_KIND:
56 BLOOM_UPDATE(Py_UCS2, mask, ptr, len);
57 break;
58 case PyUnicode_4BYTE_KIND:
59 BLOOM_UPDATE(Py_UCS4, mask, ptr, len);
60 break;
61 default:
62 Py_UNREACHABLE();
63 }
64 return mask;
65
66 #undef BLOOM_UPDATE
67 }
68
69 static inline char _CPyStr_Equal_NoIdentCheck(PyObject *str1, PyObject *str2, Py_ssize_t str2_length) {
70 // This helper function only exists to deduplicate code in CPyStr_Equal and CPyStr_EqualLiteral
71 Py_ssize_t str1_length = PyUnicode_GET_LENGTH(str1);
72 if (str1_length != str2_length)
73 return 0;
74 int kind = PyUnicode_KIND(str1);
75 if (PyUnicode_KIND(str2) != kind)
76 return 0;
77 const void *data1 = PyUnicode_DATA(str1);
78 const void *data2 = PyUnicode_DATA(str2);
79 return memcmp(data1, data2, str1_length * kind) == 0;
80 }
81
82 // Adapted from CPython 3.13.1 (_PyUnicode_Equal)
83 char CPyStr_Equal(PyObject *str1, PyObject *str2) {
84 if (str1 == str2) {
85 return 1;
86 }
87 Py_ssize_t str2_length = PyUnicode_GET_LENGTH(str2);
88 return _CPyStr_Equal_NoIdentCheck(str1, str2, str2_length);
89 }
90
91 char CPyStr_EqualLiteral(PyObject *str, PyObject *literal_str, Py_ssize_t literal_length) {
92 if (str == literal_str) {
93 return 1;
94 }
95 return _CPyStr_Equal_NoIdentCheck(str, literal_str, literal_length);
96 }
97
98 PyObject *CPyStr_GetItem(PyObject *str, CPyTagged index) {
99 if (PyUnicode_READY(str) != -1) {
100 if (CPyTagged_CheckShort(index)) {
101 Py_ssize_t n = CPyTagged_ShortAsSsize_t(index);
102 Py_ssize_t size = PyUnicode_GET_LENGTH(str);
103 if (n < 0)
104 n += size;
105 if (n < 0 || n >= size) {
106 PyErr_SetString(PyExc_IndexError, "string index out of range");
107 return NULL;
108 }
109 enum PyUnicode_Kind kind = (enum PyUnicode_Kind)PyUnicode_KIND(str);
110 void *data = PyUnicode_DATA(str);
111 Py_UCS4 ch = PyUnicode_READ(kind, data, n);
112 if (ch < 256) {
113 // Latin-1 single-char strings are cached by CPython, so
114 // PyUnicode_FromOrdinal returns the cached object (with a
115 // new reference) instead of allocating a new string each time.
116 return PyUnicode_FromOrdinal(ch);
117 }
118 PyObject *unicode = PyUnicode_New(1, ch);
119 if (unicode == NULL)
120 return NULL;
121 if (PyUnicode_KIND(unicode) == PyUnicode_2BYTE_KIND) {
122 PyUnicode_2BYTE_DATA(unicode)[0] = (Py_UCS2)ch;
123 } else {
124 assert(PyUnicode_KIND(unicode) == PyUnicode_4BYTE_KIND);
125 PyUnicode_4BYTE_DATA(unicode)[0] = ch;
126 }
127 return unicode;
128 } else {
129 PyErr_SetString(PyExc_OverflowError, CPYTHON_LARGE_INT_ERRMSG);
130 return NULL;
131 }
132 } else {
133 PyObject *index_obj = CPyTagged_AsObject(index);
134 PyObject *result = PyObject_GetItem(str, index_obj);
135 Py_DECREF(index_obj);
136 return result;
137 }
138 }
139
140 PyObject *CPyStr_GetItemUnsafe(PyObject *str, Py_ssize_t index) {
141 // This is unsafe since we don't check for overflow when doing <<.
142 return CPyStr_GetItem(str, index << 1);
143 }
144
145 // A simplification of _PyUnicode_JoinArray() from CPython 3.9.6
146 PyObject *CPyStr_Build(Py_ssize_t len, ...) {
147 Py_ssize_t i;
148 va_list args;
149
150 // Calculate the total amount of space and check
151 // whether all components have the same kind.
152 Py_ssize_t sz = 0;
153 Py_UCS4 maxchar = 0;
154 int use_memcpy = 1; // Use memcpy by default
155 PyObject *last_obj = NULL;
156
157 va_start(args, len);
158 for (i = 0; i < len; i++) {
159 PyObject *item = va_arg(args, PyObject *);
160 if (!PyUnicode_Check(item)) {
161 PyErr_Format(PyExc_TypeError,
162 "sequence item %zd: expected str instance,"
163 " %.80s found",
164 i, Py_TYPE(item)->tp_name);
165 return NULL;
166 }
167 if (PyUnicode_READY(item) == -1)
168 return NULL;
169
170 size_t add_sz = PyUnicode_GET_LENGTH(item);
171 Py_UCS4 item_maxchar = PyUnicode_MAX_CHAR_VALUE(item);
172 maxchar = Py_MAX(maxchar, item_maxchar);
173
174 // Using size_t to avoid overflow during arithmetic calculation
175 if (add_sz > (size_t)(PY_SSIZE_T_MAX - sz)) {
176 PyErr_SetString(PyExc_OverflowError,
177 "join() result is too long for a Python string");
178 return NULL;
179 }
180 sz += add_sz;
181
182 // If these strings have different kind, we would call
183 // _PyUnicode_FastCopyCharacters() in the following part.
184 if (use_memcpy && last_obj != NULL) {
185 if (PyUnicode_KIND(last_obj) != PyUnicode_KIND(item))
186 use_memcpy = 0;
187 }
188 last_obj = item;
189 }
190 va_end(args);
191
192 // Construct the string
193 PyObject *res = PyUnicode_New(sz, maxchar);
194 if (res == NULL)
195 return NULL;
196
197 if (use_memcpy) {
198 unsigned char *res_data = PyUnicode_1BYTE_DATA(res);
199 unsigned int kind = PyUnicode_KIND(res);
200
201 va_start(args, len);
202 for (i = 0; i < len; ++i) {
203 PyObject *item = va_arg(args, PyObject *);
204 Py_ssize_t itemlen = PyUnicode_GET_LENGTH(item);
205 if (itemlen != 0) {
206 memcpy(res_data, PyUnicode_DATA(item), kind * itemlen);
207 res_data += kind * itemlen;
208 }
209 }
210 va_end(args);
211 assert(res_data == PyUnicode_1BYTE_DATA(res) + kind * PyUnicode_GET_LENGTH(res));
212 } else {
213 Py_ssize_t res_offset = 0;
214
215 va_start(args, len);
216 for (i = 0; i < len; ++i) {
217 PyObject *item = va_arg(args, PyObject *);
218 Py_ssize_t itemlen = PyUnicode_GET_LENGTH(item);
219 if (itemlen != 0) {
220 #if CPY_3_13_FEATURES
221 PyUnicode_CopyCharacters(res, res_offset, item, 0, itemlen);
222 #else
223 _PyUnicode_FastCopyCharacters(res, res_offset, item, 0, itemlen);
224 #endif
225 res_offset += itemlen;
226 }
227 }
228 va_end(args);
229 assert(res_offset == PyUnicode_GET_LENGTH(res));
230 }
231
232 #ifdef Py_DEBUG
233 assert(_PyUnicode_CheckConsistency(res, 1));
234 #endif
235 return res;
236 }
237
238 CPyTagged CPyStr_Find(PyObject *str, PyObject *substr, CPyTagged start, int direction) {
239 CPyTagged end = PyUnicode_GET_LENGTH(str) << 1;
240 return CPyStr_FindWithEnd(str, substr, start, end, direction);
241 }
242
243 CPyTagged CPyStr_FindWithEnd(PyObject *str, PyObject *substr, CPyTagged start, CPyTagged end, int direction) {
244 Py_ssize_t temp_start = CPyTagged_AsSsize_t(start);
245 if (temp_start == -1 && PyErr_Occurred()) {
246 PyErr_SetString(PyExc_OverflowError, CPYTHON_LARGE_INT_ERRMSG);
247 return CPY_INT_TAG;
248 }
249 Py_ssize_t temp_end = CPyTagged_AsSsize_t(end);
250 if (temp_end == -1 && PyErr_Occurred()) {
251 PyErr_SetString(PyExc_OverflowError, CPYTHON_LARGE_INT_ERRMSG);
252 return CPY_INT_TAG;
253 }
254 Py_ssize_t index = PyUnicode_Find(str, substr, temp_start, temp_end, direction);
255 if (unlikely(index == -2)) {
256 return CPY_INT_TAG;
257 }
258 return index << 1;
259 }
260
261 PyObject *CPyStr_Split(PyObject *str, PyObject *sep, CPyTagged max_split) {
262 Py_ssize_t temp_max_split = CPyTagged_AsSsize_t(max_split);
263 if (temp_max_split == -1 && PyErr_Occurred()) {
264 PyErr_SetString(PyExc_OverflowError, CPYTHON_LARGE_INT_ERRMSG);
265 return NULL;
266 }
267 return PyUnicode_Split(str, sep, temp_max_split);
268 }
269
270 PyObject *CPyStr_RSplit(PyObject *str, PyObject *sep, CPyTagged max_split) {
271 Py_ssize_t temp_max_split = CPyTagged_AsSsize_t(max_split);
272 if (temp_max_split == -1 && PyErr_Occurred()) {
273 PyErr_SetString(PyExc_OverflowError, CPYTHON_LARGE_INT_ERRMSG);
274 return NULL;
275 }
276 return PyUnicode_RSplit(str, sep, temp_max_split);
277 }
278
279 // This function has been copied from _PyUnicode_XStrip in cpython.git:Objects/unicodeobject.c@0ef4ffeefd1737c18dc9326133c7894d58108c2e.
280 static PyObject *_PyStr_XStrip(PyObject *self, int striptype, PyObject *sepobj) {
281 const void *data;
282 int kind;
283 Py_ssize_t i, j, len;
284 BLOOM_MASK sepmask;
285 Py_ssize_t seplen;
286
287 // This check is needed from Python 3.9 and earlier.
288 if (PyUnicode_READY(self) == -1 || PyUnicode_READY(sepobj) == -1)
289 return NULL;
290
291 kind = PyUnicode_KIND(self);
292 data = PyUnicode_DATA(self);
293 len = PyUnicode_GET_LENGTH(self);
294 seplen = PyUnicode_GET_LENGTH(sepobj);
295 sepmask = make_bloom_mask(PyUnicode_KIND(sepobj),
296 PyUnicode_DATA(sepobj),
297 seplen);
298
299 i = 0;
300 if (striptype != RIGHTSTRIP) {
301 while (i < len) {
302 Py_UCS4 ch = PyUnicode_READ(kind, data, i);
303 if (!BLOOM(sepmask, ch))
304 break;
305 if (PyUnicode_FindChar(sepobj, ch, 0, seplen, 1) < 0)
306 break;
307 i++;
308 }
309 }
310
311 j = len;
312 if (striptype != LEFTSTRIP) {
313 j--;
314 while (j >= i) {
315 Py_UCS4 ch = PyUnicode_READ(kind, data, j);
316 if (!BLOOM(sepmask, ch))
317 break;
318 if (PyUnicode_FindChar(sepobj, ch, 0, seplen, 1) < 0)
319 break;
320 j--;
321 }
322
323 j++;
324 }
325
326 return PyUnicode_Substring(self, i, j);
327 }
328
329 // Copied from do_strip function in cpython.git/Objects/unicodeobject.c@0ef4ffeefd1737c18dc9326133c7894d58108c2e.
330 PyObject *_CPyStr_Strip(PyObject *self, int strip_type, PyObject *sep) {
331 if (sep == NULL || Py_IsNone(sep)) {
332 Py_ssize_t len, i, j;
333
334 // This check is needed from Python 3.9 and earlier.
335 if (PyUnicode_READY(self) == -1)
336 return NULL;
337
338 len = PyUnicode_GET_LENGTH(self);
339
340 if (PyUnicode_IS_ASCII(self)) {
341 const Py_UCS1 *data = PyUnicode_1BYTE_DATA(self);
342
343 i = 0;
344 if (strip_type != RIGHTSTRIP) {
345 while (i < len) {
346 Py_UCS1 ch = data[i];
347 if (!_Py_ascii_whitespace[ch])
348 break;
349 i++;
350 }
351 }
352
353 j = len;
354 if (strip_type != LEFTSTRIP) {
355 j--;
356 while (j >= i) {
357 Py_UCS1 ch = data[j];
358 if (!_Py_ascii_whitespace[ch])
359 break;
360 j--;
361 }
362 j++;
363 }
364 }
365 else {
366 int kind = PyUnicode_KIND(self);
367 const void *data = PyUnicode_DATA(self);
368
369 i = 0;
370 if (strip_type != RIGHTSTRIP) {
371 while (i < len) {
372 Py_UCS4 ch = PyUnicode_READ(kind, data, i);
373 if (!Py_UNICODE_ISSPACE(ch))
374 break;
375 i++;
376 }
377 }
378
379 j = len;
380 if (strip_type != LEFTSTRIP) {
381 j--;
382 while (j >= i) {
383 Py_UCS4 ch = PyUnicode_READ(kind, data, j);
384 if (!Py_UNICODE_ISSPACE(ch))
385 break;
386 j--;
387 }
388 j++;
389 }
390 }
391
392 return PyUnicode_Substring(self, i, j);
393 }
394 return _PyStr_XStrip(self, strip_type, sep);
395 }
396
397 PyObject *CPyStr_Replace(PyObject *str, PyObject *old_substr,
398 PyObject *new_substr, CPyTagged max_replace) {
399 Py_ssize_t temp_max_replace = CPyTagged_AsSsize_t(max_replace);
400 if (temp_max_replace == -1 && PyErr_Occurred()) {
401 PyErr_SetString(PyExc_OverflowError, CPYTHON_LARGE_INT_ERRMSG);
402 return NULL;
403 }
404 return PyUnicode_Replace(str, old_substr, new_substr, temp_max_replace);
405 }
406
407 int CPyStr_Startswith(PyObject *self, PyObject *subobj) {
408 Py_ssize_t start = 0;
409 Py_ssize_t end = PyUnicode_GET_LENGTH(self);
410 if (PyTuple_Check(subobj)) {
411 Py_ssize_t i;
412 for (i = 0; i < PyTuple_GET_SIZE(subobj); i++) {
413 PyObject *substring = PyTuple_GET_ITEM(subobj, i);
414 if (!PyUnicode_Check(substring)) {
415 PyErr_Format(PyExc_TypeError,
416 "tuple for startswith must only contain str, "
417 "not %.100s",
418 Py_TYPE(substring)->tp_name);
419 return 2;
420 }
421 int result = PyUnicode_Tailmatch(self, substring, start, end, -1);
422 if (result) {
423 return 1;
424 }
425 }
426 return 0;
427 }
428 return PyUnicode_Tailmatch(self, subobj, start, end, -1);
429 }
430
431 int CPyStr_Endswith(PyObject *self, PyObject *subobj) {
432 Py_ssize_t start = 0;
433 Py_ssize_t end = PyUnicode_GET_LENGTH(self);
434 if (PyTuple_Check(subobj)) {
435 Py_ssize_t i;
436 for (i = 0; i < PyTuple_GET_SIZE(subobj); i++) {
437 PyObject *substring = PyTuple_GET_ITEM(subobj, i);
438 if (!PyUnicode_Check(substring)) {
439 PyErr_Format(PyExc_TypeError,
440 "tuple for endswith must only contain str, "
441 "not %.100s",
442 Py_TYPE(substring)->tp_name);
443 return 2;
444 }
445 int result = PyUnicode_Tailmatch(self, substring, start, end, 1);
446 if (result) {
447 return 1;
448 }
449 }
450 return 0;
451 }
452 return PyUnicode_Tailmatch(self, subobj, start, end, 1);
453 }
454
455 PyObject *CPyStr_Removeprefix(PyObject *self, PyObject *prefix) {
456 Py_ssize_t end = PyUnicode_GET_LENGTH(self);
457 int match = PyUnicode_Tailmatch(self, prefix, 0, end, -1);
458 if (match) {
459 Py_ssize_t prefix_end = PyUnicode_GET_LENGTH(prefix);
460 return PyUnicode_Substring(self, prefix_end, end);
461 }
462 return Py_NewRef(self);
463 }
464
465 PyObject *CPyStr_Removesuffix(PyObject *self, PyObject *suffix) {
466 Py_ssize_t end = PyUnicode_GET_LENGTH(self);
467 int match = PyUnicode_Tailmatch(self, suffix, 0, end, 1);
468 if (match) {
469 Py_ssize_t suffix_end = PyUnicode_GET_LENGTH(suffix);
470 return PyUnicode_Substring(self, 0, end - suffix_end);
471 }
472 return Py_NewRef(self);
473 }
474
475 /* This does a dodgy attempt to append in place */
476 PyObject *CPyStr_Append(PyObject *o1, PyObject *o2) {
477 PyUnicode_Append(&o1, o2);
478 return o1;
479 }
480
481 PyObject *CPyStr_GetSlice(PyObject *obj, CPyTagged start, CPyTagged end) {
482 if (likely(PyUnicode_CheckExact(obj)
483 && CPyTagged_CheckShort(start) && CPyTagged_CheckShort(end))) {
484 Py_ssize_t startn = CPyTagged_ShortAsSsize_t(start);
485 Py_ssize_t endn = CPyTagged_ShortAsSsize_t(end);
486 if (startn < 0) {
487 startn += PyUnicode_GET_LENGTH(obj);
488 if (startn < 0) {
489 startn = 0;
490 }
491 }
492 if (endn < 0) {
493 endn += PyUnicode_GET_LENGTH(obj);
494 if (endn < 0) {
495 endn = 0;
496 }
497 }
498 return PyUnicode_Substring(obj, startn, endn);
499 }
500 return CPyObject_GetSlice(obj, start, end);
501 }
502
503 /* Check if the given string is true (i.e. its length isn't zero) */
504 bool CPyStr_IsTrue(PyObject *obj) {
505 Py_ssize_t length = PyUnicode_GET_LENGTH(obj);
506 return length != 0;
507 }
508
509 Py_ssize_t CPyStr_Size_size_t(PyObject *str) {
510 if (PyUnicode_READY(str) != -1) {
511 return PyUnicode_GET_LENGTH(str);
512 }
513 return -1;
514 }
515
516 PyObject *CPy_Decode(PyObject *obj, PyObject *encoding, PyObject *errors) {
517 const char *enc = NULL;
518 const char *err = NULL;
519 if (encoding) {
520 enc = PyUnicode_AsUTF8AndSize(encoding, NULL);
521 if (!enc) return NULL;
522 }
523 if (errors) {
524 err = PyUnicode_AsUTF8AndSize(errors, NULL);
525 if (!err) return NULL;
526 }
527 if (PyBytes_Check(obj)) {
528 return PyUnicode_Decode(((PyBytesObject *)obj)->ob_sval,
529 ((PyVarObject *)obj)->ob_size,
530 enc, err);
531 } else {
532 return PyUnicode_FromEncodedObject(obj, enc, err);
533 }
534 }
535
536 PyObject *CPy_DecodeUTF8(PyObject *bytes) {
537 if (PyBytes_CheckExact(bytes)) {
538 char *buffer = PyBytes_AsString(bytes); // Borrowed reference
539 if (buffer == NULL) {
540 return NULL;
541 }
542 Py_ssize_t size = PyBytes_Size(bytes);
543 return PyUnicode_DecodeUTF8(buffer, size, "strict");
544 } else {
545 return PyUnicode_FromEncodedObject(bytes, "utf-8", "strict");
546 }
547 }
548
549 PyObject *CPy_DecodeASCII(PyObject *bytes) {
550 if (PyBytes_CheckExact(bytes)) {
551 char *buffer = PyBytes_AsString(bytes); // Borrowed reference
552 if (buffer == NULL) {
553 return NULL;
554 }
555 Py_ssize_t size = PyBytes_Size(bytes);
556 return PyUnicode_DecodeASCII(buffer, size, "strict");;
557 } else {
558 return PyUnicode_FromEncodedObject(bytes, "ascii", "strict");
559 }
560 }
561
562 PyObject *CPy_DecodeLatin1(PyObject *bytes) {
563 if (PyBytes_CheckExact(bytes)) {
564 char *buffer = PyBytes_AsString(bytes); // Borrowed reference
565 if (buffer == NULL) {
566 return NULL;
567 }
568 Py_ssize_t size = PyBytes_Size(bytes);
569 return PyUnicode_DecodeLatin1(buffer, size, "strict");
570 } else {
571 return PyUnicode_FromEncodedObject(bytes, "latin1", "strict");
572 }
573 }
574
575 PyObject *CPy_Encode(PyObject *obj, PyObject *encoding, PyObject *errors) {
576 const char *enc = NULL;
577 const char *err = NULL;
578 if (encoding) {
579 enc = PyUnicode_AsUTF8AndSize(encoding, NULL);
580 if (!enc) return NULL;
581 }
582 if (errors) {
583 err = PyUnicode_AsUTF8AndSize(errors, NULL);
584 if (!err) return NULL;
585 }
586 if (PyUnicode_Check(obj)) {
587 return PyUnicode_AsEncodedString(obj, enc, err);
588 } else {
589 PyErr_BadArgument();
590 return NULL;
591 }
592 }
593
594 Py_ssize_t CPyStr_Count(PyObject *unicode, PyObject *substring, CPyTagged start) {
595 Py_ssize_t temp_start = CPyTagged_AsSsize_t(start);
596 if (temp_start == -1 && PyErr_Occurred()) {
597 PyErr_SetString(PyExc_OverflowError, CPYTHON_LARGE_INT_ERRMSG);
598 return -1;
599 }
600 Py_ssize_t end = PyUnicode_GET_LENGTH(unicode);
601 return PyUnicode_Count(unicode, substring, temp_start, end);
602 }
603
604 Py_ssize_t CPyStr_CountFull(PyObject *unicode, PyObject *substring, CPyTagged start, CPyTagged end) {
605 Py_ssize_t temp_start = CPyTagged_AsSsize_t(start);
606 if (temp_start == -1 && PyErr_Occurred()) {
607 PyErr_SetString(PyExc_OverflowError, CPYTHON_LARGE_INT_ERRMSG);
608 return -1;
609 }
610 Py_ssize_t temp_end = CPyTagged_AsSsize_t(end);
611 if (temp_end == -1 && PyErr_Occurred()) {
612 PyErr_SetString(PyExc_OverflowError, CPYTHON_LARGE_INT_ERRMSG);
613 return -1;
614 }
615 return PyUnicode_Count(unicode, substring, temp_start, temp_end);
616 }
617
618
619 CPyTagged CPyStr_Ord(PyObject *obj) {
620 Py_ssize_t s = PyUnicode_GET_LENGTH(obj);
621 if (s == 1) {
622 int kind = PyUnicode_KIND(obj);
623 return PyUnicode_READ(kind, PyUnicode_DATA(obj), 0) << 1;
624 }
625 PyErr_Format(
626 PyExc_TypeError, "ord() expected a character, but a string of length %zd found", s);
627 return CPY_INT_TAG;
628 }
629
630 PyObject *CPyStr_Multiply(PyObject *str, CPyTagged count) {
631 Py_ssize_t temp_count = CPyTagged_AsSsize_t(count);
632 if (temp_count == -1 && PyErr_Occurred()) {
633 PyErr_SetString(PyExc_OverflowError, CPYTHON_LARGE_INT_ERRMSG);
634 return NULL;
635 }
636 return PySequence_Repeat(str, temp_count);
637 }
638
639
640 bool CPyStr_IsSpace(PyObject *str) {
641 Py_ssize_t len = PyUnicode_GET_LENGTH(str);
642 if (len == 0) return false;
643
644 if (PyUnicode_IS_ASCII(str)) {
645 const Py_UCS1 *data = PyUnicode_1BYTE_DATA(str);
646 for (Py_ssize_t i = 0; i < len; i++) {
647 if (!_Py_ascii_whitespace[data[i]])
648 return false;
649 }
650 return true;
651 }
652
653 int kind = PyUnicode_KIND(str);
654 const void *data = PyUnicode_DATA(str);
655 for (Py_ssize_t i = 0; i < len; i++) {
656 Py_UCS4 ch = PyUnicode_READ(kind, data, i);
657 if (!Py_UNICODE_ISSPACE(ch))
658 return false;
659 }
660 return true;
661 }
662
663 bool CPyStr_IsAlnum(PyObject *str) {
664 Py_ssize_t len = PyUnicode_GET_LENGTH(str);
665 if (len == 0) return false;
666
667 if (PyUnicode_IS_ASCII(str)) {
668 const Py_UCS1 *data = PyUnicode_1BYTE_DATA(str);
669 for (Py_ssize_t i = 0; i < len; i++) {
670 if (!Py_ISALNUM(data[i]))
671 return false;
672 }
673 return true;
674 }
675
676 int kind = PyUnicode_KIND(str);
677 const void *data = PyUnicode_DATA(str);
678 for (Py_ssize_t i = 0; i < len; i++) {
679 Py_UCS4 ch = PyUnicode_READ(kind, data, i);
680 if (!Py_UNICODE_ISALNUM(ch))
681 return false;
682 }
683 return true;
684 }
685
686 static inline int CPy_ASCII_Lower(unsigned char c) { return Py_TOLOWER(c); }
687 static inline int CPy_ASCII_Upper(unsigned char c) { return Py_TOUPPER(c); }
688
689 static inline PyObject *CPyStr_ChangeCase(PyObject *self,
690 int (*ascii_func)(unsigned char),
691 #if CPY_3_13_FEATURES
692 PyObject *method_name
693 #else
694 int (*unicode_func)(Py_UCS4, Py_UCS4 *)
695 #endif
696 ) {
697 Py_ssize_t len = PyUnicode_GET_LENGTH(self);
698 if (len == 0) {
699 Py_INCREF(self);
700 return self;
701 }
702
703 // ASCII fast path: 1-to-1, no expansion possible
704 if (PyUnicode_IS_ASCII(self)) {
705 PyObject *res = PyUnicode_New(len, 127);
706 if (res == NULL) return NULL;
707 const Py_UCS1 *data = PyUnicode_1BYTE_DATA(self);
708 Py_UCS1 *res_data = PyUnicode_1BYTE_DATA(res);
709 for (Py_ssize_t i = 0; i < len; i++) {
710 res_data[i] = ascii_func(data[i]);
711 }
712 return res;
713 }
714
715 #if CPY_3_13_FEATURES
716 // On 3.13+, _PyUnicode_ToLowerFull/ToUpperFull are no longer exported,
717 // so fall back to CPython's method implementation for non-ASCII strings.
718 return PyObject_CallMethodNoArgs(self, method_name);
719 #else
720 // General Unicode: unicode_func handles 1-to-N expansion.
721 // Worst case: each codepoint expands to 3 (per Unicode standard).
722 // The tmp buffer is short-lived, and PyUnicode_FromKindAndData
723 // compacts the result to the optimal string kind automatically.
724 int kind = PyUnicode_KIND(self);
725 const void *data = PyUnicode_DATA(self);
726 Py_UCS4 *tmp = PyMem_Malloc(sizeof(Py_UCS4) * len * 3);
727 if (tmp == NULL) return PyErr_NoMemory();
728
729 Py_UCS4 mapped[3];
730 Py_ssize_t out_len = 0;
731 for (Py_ssize_t i = 0; i < len; i++) {
732 int n = unicode_func(PyUnicode_READ(kind, data, i), mapped);
733 for (int j = 0; j < n; j++) {
734 tmp[out_len++] = mapped[j];
735 }
736 }
737
738 PyObject *res = PyUnicode_FromKindAndData(PyUnicode_4BYTE_KIND, tmp, out_len);
739 PyMem_Free(tmp);
740 return res;
741 #endif
742 }
743
744 PyObject *CPyStr_Lower(PyObject *self) {
745 #if CPY_3_13_FEATURES
746 return CPyStr_ChangeCase(self, CPy_ASCII_Lower, mypyc_interned_str.lower);
747 #else
748 return CPyStr_ChangeCase(self, CPy_ASCII_Lower, _PyUnicode_ToLowerFull);
749 #endif
750 }
751
752 PyObject *CPyStr_Upper(PyObject *self) {
753 #if CPY_3_13_FEATURES
754 return CPyStr_ChangeCase(self, CPy_ASCII_Upper, mypyc_interned_str.upper);
755 #else
756 return CPyStr_ChangeCase(self, CPy_ASCII_Upper, _PyUnicode_ToUpperFull);
757 #endif
758 }
759
760 bool CPyStr_IsDigit(PyObject *str) {
761 Py_ssize_t len = PyUnicode_GET_LENGTH(str);
762 if (len == 0) return false;
763
764 #define CHECK_ISDIGIT(TYPE, DATA, CHECK) \
765 { \
766 const TYPE *data = (const TYPE *)(DATA); \
767 for (Py_ssize_t i = 0; i < len; i++) { \
768 if (!CHECK(data[i])) \
769 return false; \
770 } \
771 }
772
773 // ASCII fast path
774 if (PyUnicode_IS_ASCII(str)) {
775 CHECK_ISDIGIT(Py_UCS1, PyUnicode_1BYTE_DATA(str), Py_ISDIGIT);
776 return true;
777 }
778
779 switch (PyUnicode_KIND(str)) {
780 case PyUnicode_1BYTE_KIND:
781 CHECK_ISDIGIT(Py_UCS1, PyUnicode_1BYTE_DATA(str), Py_UNICODE_ISDIGIT);
782 break;
783 case PyUnicode_2BYTE_KIND:
784 CHECK_ISDIGIT(Py_UCS2, PyUnicode_2BYTE_DATA(str), Py_UNICODE_ISDIGIT);
785 break;
786 case PyUnicode_4BYTE_KIND:
787 CHECK_ISDIGIT(Py_UCS4, PyUnicode_4BYTE_DATA(str), Py_UNICODE_ISDIGIT);
788 break;
789 default:
790 Py_UNREACHABLE();
791 }
792 return true;
793
794 #undef CHECK_ISDIGIT
795 }