bitarray 3.12.2__cp313-cp313-pyemscripten_2025_0_wasm32.whl

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -0,0 +1,3138 @@
1
+ // Header file providing new C API functions to old Python versions.
2
+ // Python 3.6 or newer is required.
3
+ //
4
+ // File distributed under the Zero Clause BSD (0BSD) license.
5
+ // Copyright Contributors to the pythoncapi_compat project.
6
+ //
7
+ // Homepage:
8
+ // https://github.com/python/pythoncapi_compat
9
+ //
10
+ // Latest version:
11
+ // https://raw.githubusercontent.com/python/pythoncapi-compat/main/pythoncapi_compat.h
12
+ //
13
+ // SPDX-License-Identifier: 0BSD
14
+
15
+ #ifndef PYTHONCAPI_COMPAT
16
+ #define PYTHONCAPI_COMPAT
17
+
18
+ #ifdef __cplusplus
19
+ extern "C" {
20
+ #endif
21
+
22
+ #include <Python.h>
23
+ #include <stddef.h> // offsetof()
24
+ #include <stdio.h> // fclose()
25
+ #include <string.h> // memcpy()
26
+
27
+ // Python 3.11 added PyFrame_GetBack() to Python.h
28
+ #if PY_VERSION_HEX < 0x030B0000 && !defined(PYPY_VERSION)
29
+ # include "frameobject.h" // PyFrameObject, PyFrame_GetBack()
30
+ #endif
31
+
32
+
33
+ #ifndef _Py_CAST
34
+ # define _Py_CAST(type, expr) ((type)(expr))
35
+ #endif
36
+
37
+ // Static inline functions should use _Py_NULL rather than using directly NULL
38
+ // to prevent C++ compiler warnings. On C23 and newer and on C++11 and newer,
39
+ // _Py_NULL is defined as nullptr.
40
+ #ifndef _Py_NULL
41
+ # if (defined (__STDC_VERSION__) && __STDC_VERSION__ > 201710L) \
42
+ || (defined(__cplusplus) && __cplusplus >= 201103)
43
+ # define _Py_NULL nullptr
44
+ # else
45
+ # define _Py_NULL NULL
46
+ # endif
47
+ #endif
48
+
49
+ // Cast argument to PyObject* type.
50
+ #ifndef _PyObject_CAST
51
+ # define _PyObject_CAST(op) _Py_CAST(PyObject*, op)
52
+ #endif
53
+ #ifndef _PyVarObject_CAST
54
+ # define _PyVarObject_CAST(op) _Py_CAST(PyVarObject*, (op))
55
+ #endif
56
+
57
+ #ifndef Py_BUILD_ASSERT
58
+ # define Py_BUILD_ASSERT(cond) \
59
+ do { (void)sizeof(char [1 - 2 * !(cond)]); } while(0)
60
+ #endif
61
+
62
+ #ifndef _Py_COMP_DIAG_PUSH
63
+ # if defined(__clang__)
64
+ # define _Py_COMP_DIAG_PUSH _Pragma("clang diagnostic push")
65
+ # define _Py_COMP_DIAG_IGNORE_DEPR_DECLS \
66
+ _Pragma("clang diagnostic ignored \"-Wdeprecated-declarations\"")
67
+ # define _Py_COMP_DIAG_POP _Pragma("clang diagnostic pop")
68
+ # elif defined(__GNUC__) \
69
+ && ((__GNUC__ >= 5) || (__GNUC__ == 4) && (__GNUC_MINOR__ >= 6))
70
+ # define _Py_COMP_DIAG_PUSH _Pragma("GCC diagnostic push")
71
+ # define _Py_COMP_DIAG_IGNORE_DEPR_DECLS \
72
+ _Pragma("GCC diagnostic ignored \"-Wdeprecated-declarations\"")
73
+ # define _Py_COMP_DIAG_POP _Pragma("GCC diagnostic pop")
74
+ # elif defined(_MSC_VER)
75
+ # define _Py_COMP_DIAG_PUSH __pragma(warning(push))
76
+ # define _Py_COMP_DIAG_IGNORE_DEPR_DECLS __pragma(warning(disable: 4996))
77
+ # define _Py_COMP_DIAG_POP __pragma(warning(pop))
78
+ # else
79
+ # define _Py_COMP_DIAG_PUSH
80
+ # define _Py_COMP_DIAG_IGNORE_DEPR_DECLS
81
+ # define _Py_COMP_DIAG_POP
82
+ # endif
83
+ #endif
84
+
85
+ #ifndef _Py_PACK_VERSION
86
+ # define _Py_PACK_FULL_VERSION(X, Y, Z, LEVEL, SERIAL) ( \
87
+ (((X) & 0xff) << 24) | \
88
+ (((Y) & 0xff) << 16) | \
89
+ (((Z) & 0xff) << 8) | \
90
+ (((LEVEL) & 0xf) << 4) | \
91
+ (((SERIAL) & 0xf) << 0))
92
+ # define _Py_PACK_VERSION(X, Y) _Py_PACK_FULL_VERSION(X, Y, 0, 0, 0)
93
+ #endif
94
+
95
+ #if (PY_VERSION_HEX >= _Py_PACK_VERSION(3, 13) \
96
+ && (!defined(Py_LIMITED_API) || Py_LIMITED_API+0 >= _Py_PACK_VERSION(3, 13)))
97
+ // "%T" format was added to Python 3.13
98
+ # define PYTHONCAPI_COMPAT_EXPECT_TYPE(ERRMSG, OBJ) \
99
+ PyErr_Format(PyExc_TypeError, ERRMSG "%T", (OBJ))
100
+ #elif !defined(Py_LIMITED_API)
101
+ # define PYTHONCAPI_COMPAT_EXPECT_TYPE(ERRMSG, OBJ) \
102
+ PyErr_Format(PyExc_TypeError, ERRMSG "%s", Py_TYPE(OBJ)->tp_name)
103
+ #elif Py_LIMITED_API+0 >= _Py_PACK_VERSION(3, 11)
104
+ # define PYTHONCAPI_COMPAT_EXPECT_TYPE(ERRMSG, OBJ) \
105
+ do { \
106
+ PyObject *_type_name = PyType_GetName(Py_TYPE(OBJ)); \
107
+ if (_type_name != NULL) { \
108
+ PyErr_Format(PyExc_TypeError, ERRMSG "%S", (OBJ)); \
109
+ Py_DECREF(_type_name); \
110
+ } \
111
+ } while (0)
112
+ #else
113
+ # define PYTHONCAPI_COMPAT_EXPECT_TYPE(ERRMSG, OBJ) \
114
+ do { \
115
+ PyObject *_type = _PyObject_CAST(Py_TYPE(OBJ)); \
116
+ PyObject *_type_name = PyObject_GetAttrString(_type, "__name__"); \
117
+ if (_type_name != NULL) { \
118
+ PyErr_Format(PyExc_TypeError, ERRMSG "%S", (OBJ)); \
119
+ Py_DECREF(_type_name); \
120
+ } \
121
+ } while (0)
122
+ #endif
123
+
124
+
125
+ // bpo-42262 added Py_NewRef() to Python 3.10
126
+ #if PY_VERSION_HEX < _Py_PACK_VERSION(3, 10) && !defined(Py_NewRef)
127
+ static inline PyObject* _Py_NewRef(PyObject *obj)
128
+ {
129
+ Py_INCREF(obj);
130
+ return obj;
131
+ }
132
+ #define Py_NewRef(obj) _Py_NewRef(_PyObject_CAST(obj))
133
+ #endif
134
+
135
+
136
+ // bpo-42262 added Py_XNewRef() to Python 3.10
137
+ #if PY_VERSION_HEX < _Py_PACK_VERSION(3, 10) && !defined(Py_XNewRef)
138
+ static inline PyObject* _Py_XNewRef(PyObject *obj)
139
+ {
140
+ Py_XINCREF(obj);
141
+ return obj;
142
+ }
143
+ #define Py_XNewRef(obj) _Py_XNewRef(_PyObject_CAST(obj))
144
+ #endif
145
+
146
+
147
+ // bpo-39573 added Py_SET_REFCNT() to Python 3.9
148
+ #if PY_VERSION_HEX < _Py_PACK_VERSION(3, 9) && !defined(Py_SET_REFCNT)
149
+ static inline void _Py_SET_REFCNT(PyObject *ob, Py_ssize_t refcnt)
150
+ {
151
+ ob->ob_refcnt = refcnt;
152
+ }
153
+ #define Py_SET_REFCNT(ob, refcnt) _Py_SET_REFCNT(_PyObject_CAST(ob), refcnt)
154
+ #endif
155
+
156
+
157
+ // bpo-43753 added Py_Is(), Py_IsNone(), Py_IsTrue() and Py_IsFalse()
158
+ // to Python 3.10.
159
+ // PyPy 3.11 provides Py_Is() and Py_IsNone().
160
+ // PyPy 3.12 provides Py_IsTrue() and Py_IsFalse().
161
+ #if !defined(Py_Is) && PY_VERSION_HEX < _Py_PACK_VERSION(3, 10)
162
+ # define Py_Is(x, y) ((x) == (y))
163
+ # define Py_IsNone(x) Py_Is(x, Py_None)
164
+ #endif
165
+ #if (!defined(Py_IsTrue) \
166
+ && (PY_VERSION_HEX < _Py_PACK_VERSION(3, 10) || defined(PYPY_VERSION)))
167
+ # define Py_IsTrue(x) Py_Is(x, Py_True)
168
+ # define Py_IsFalse(x) Py_Is(x, Py_False)
169
+ #endif
170
+
171
+
172
+ // bpo-39573 added Py_SET_TYPE() to Python 3.9
173
+ #if !defined(Py_SET_TYPE) && PY_VERSION_HEX < _Py_PACK_VERSION(3, 9)
174
+ static inline void _Py_SET_TYPE(PyObject *ob, PyTypeObject *type)
175
+ {
176
+ ob->ob_type = type;
177
+ }
178
+ #define Py_SET_TYPE(ob, type) _Py_SET_TYPE(_PyObject_CAST(ob), type)
179
+ #endif
180
+
181
+
182
+ // bpo-39573 added Py_SET_SIZE() to Python 3.9
183
+ #if !defined(Py_SET_SIZE) && PY_VERSION_HEX < _Py_PACK_VERSION(3, 9)
184
+ static inline void _Py_SET_SIZE(PyVarObject *ob, Py_ssize_t size)
185
+ {
186
+ ob->ob_size = size;
187
+ }
188
+ #define Py_SET_SIZE(ob, size) _Py_SET_SIZE((PyVarObject*)(ob), size)
189
+ #endif
190
+
191
+
192
+ // bpo-40421 added PyFrame_GetCode() to Python 3.9
193
+ // PyPy added PyFrame_GetCode() to PyPy3.12 v8.0.0
194
+ #if (PY_VERSION_HEX < _Py_PACK_VERSION(3, 9) \
195
+ || (defined(PYPY_VERSION) && PY_VERSION_HEX < _Py_PACK_VERSION(3, 12))) \
196
+ && !defined(Py_LIMITED_API)
197
+ static inline PyCodeObject* PyFrame_GetCode(PyFrameObject *frame)
198
+ {
199
+ assert(frame != _Py_NULL);
200
+ assert(frame->f_code != _Py_NULL);
201
+ return _Py_CAST(PyCodeObject*, Py_NewRef(frame->f_code));
202
+ }
203
+ #endif
204
+
205
+ #if !defined(Py_LIMITED_API) || PY_VERSION_HEX >= _Py_PACK_VERSION(3, 9)
206
+ static inline PyCodeObject* _PyFrame_GetCodeBorrow(PyFrameObject *frame)
207
+ {
208
+ PyCodeObject *code = PyFrame_GetCode(frame);
209
+ Py_DECREF(code);
210
+ return code;
211
+ }
212
+ #endif
213
+
214
+
215
+ // bpo-40421 added PyFrame_GetBack() to Python 3.9
216
+ #if (PY_VERSION_HEX < _Py_PACK_VERSION(3, 9) \
217
+ && !defined(PYPY_VERSION) && !defined(Py_LIMITED_API))
218
+ static inline PyFrameObject* PyFrame_GetBack(PyFrameObject *frame)
219
+ {
220
+ assert(frame != _Py_NULL);
221
+ return _Py_CAST(PyFrameObject*, Py_XNewRef(frame->f_back));
222
+ }
223
+ #endif
224
+
225
+ #if !defined(PYPY_VERSION) && !defined(Py_LIMITED_API)
226
+ static inline PyFrameObject* _PyFrame_GetBackBorrow(PyFrameObject *frame)
227
+ {
228
+ PyFrameObject *back = PyFrame_GetBack(frame);
229
+ Py_XDECREF(back);
230
+ return back;
231
+ }
232
+ #endif
233
+
234
+
235
+ // bpo-40421 added PyFrame_GetLocals() to Python 3.11
236
+ #if (PY_VERSION_HEX < _Py_PACK_VERSION(3, 11) \
237
+ && !defined(PYPY_VERSION) && !defined(Py_LIMITED_API))
238
+ static inline PyObject* PyFrame_GetLocals(PyFrameObject *frame)
239
+ {
240
+ if (PyFrame_FastToLocalsWithError(frame) < 0) {
241
+ return NULL;
242
+ }
243
+ return Py_NewRef(frame->f_locals);
244
+ }
245
+ #endif
246
+
247
+
248
+ // bpo-40421 added PyFrame_GetGlobals() to Python 3.11
249
+ #if (PY_VERSION_HEX < _Py_PACK_VERSION(3, 11) \
250
+ && !defined(PYPY_VERSION) && !defined(Py_LIMITED_API))
251
+ static inline PyObject* PyFrame_GetGlobals(PyFrameObject *frame)
252
+ {
253
+ return Py_NewRef(frame->f_globals);
254
+ }
255
+ #endif
256
+
257
+
258
+ // bpo-40421 added PyFrame_GetBuiltins() to Python 3.11
259
+ #if (PY_VERSION_HEX < _Py_PACK_VERSION(3, 11) \
260
+ && !defined(PYPY_VERSION) && !defined(Py_LIMITED_API))
261
+ static inline PyObject* PyFrame_GetBuiltins(PyFrameObject *frame)
262
+ {
263
+ return Py_NewRef(frame->f_builtins);
264
+ }
265
+ #endif
266
+
267
+
268
+ // bpo-40421 added PyFrame_GetLasti() to Python 3.11
269
+ #if (PY_VERSION_HEX < _Py_PACK_VERSION(3, 11) \
270
+ && !defined(PYPY_VERSION) && !defined(Py_LIMITED_API))
271
+ static inline int PyFrame_GetLasti(PyFrameObject *frame)
272
+ {
273
+ #if PY_VERSION_HEX >= _Py_PACK_VERSION(3, 10)
274
+ // bpo-27129: Since Python 3.10, f_lasti is an instruction offset,
275
+ // not a bytes offset anymore. Python uses 16-bit "wordcode" (2 bytes)
276
+ // instructions.
277
+ if (frame->f_lasti < 0) {
278
+ return -1;
279
+ }
280
+ return frame->f_lasti * 2;
281
+ #else
282
+ return frame->f_lasti;
283
+ #endif
284
+ }
285
+ #endif
286
+
287
+
288
+ // gh-91248 added PyFrame_GetVar() to Python 3.12
289
+ #if (PY_VERSION_HEX < _Py_PACK_VERSION(3, 12) \
290
+ && !defined(PYPY_VERSION) && !defined(Py_LIMITED_API))
291
+ static inline PyObject* PyFrame_GetVar(PyFrameObject *frame, PyObject *name)
292
+ {
293
+ PyObject *locals, *value;
294
+
295
+ locals = PyFrame_GetLocals(frame);
296
+ if (locals == NULL) {
297
+ return NULL;
298
+ }
299
+ value = PyDict_GetItemWithError(locals, name);
300
+ Py_DECREF(locals);
301
+
302
+ if (value == NULL) {
303
+ if (PyErr_Occurred()) {
304
+ return NULL;
305
+ }
306
+ PyErr_Format(PyExc_NameError, "variable %R does not exist", name);
307
+ return NULL;
308
+ }
309
+ return Py_NewRef(value);
310
+ }
311
+ #endif
312
+
313
+
314
+ // gh-91248 added PyFrame_GetVarString() to Python 3.12
315
+ #if (PY_VERSION_HEX < _Py_PACK_VERSION(3, 12) \
316
+ && !defined(PYPY_VERSION) && !defined(Py_LIMITED_API))
317
+ static inline PyObject*
318
+ PyFrame_GetVarString(PyFrameObject *frame, const char *name)
319
+ {
320
+ PyObject *name_obj, *value;
321
+ name_obj = PyUnicode_FromString(name);
322
+ if (name_obj == NULL) {
323
+ return NULL;
324
+ }
325
+ value = PyFrame_GetVar(frame, name_obj);
326
+ Py_DECREF(name_obj);
327
+ return value;
328
+ }
329
+ #endif
330
+
331
+
332
+ // Added to Python 3.9 and limited C API 3.9.
333
+ // Added to PyPy 3.11.
334
+ #if ((PY_VERSION_HEX < _Py_PACK_VERSION(3, 9) \
335
+ || (defined(PYPY_VERSION) && PY_VERSION_HEX < _Py_PACK_VERSION(3, 11))) \
336
+ && !defined(Py_LIMITED_API))
337
+ static inline PyInterpreterState *
338
+ PyThreadState_GetInterpreter(PyThreadState *tstate)
339
+ {
340
+ assert(tstate != _Py_NULL);
341
+ return tstate->interp;
342
+ }
343
+ #endif
344
+
345
+
346
+ // bpo-40429 added PyThreadState_GetFrame() to Python 3.9
347
+ #if (PY_VERSION_HEX < _Py_PACK_VERSION(3, 9) \
348
+ && !defined(PYPY_VERSION) && !defined(Py_LIMITED_API))
349
+ static inline PyFrameObject* PyThreadState_GetFrame(PyThreadState *tstate)
350
+ {
351
+ assert(tstate != _Py_NULL);
352
+ return _Py_CAST(PyFrameObject *, Py_XNewRef(tstate->frame));
353
+ }
354
+ #endif
355
+
356
+ #if ((!defined(Py_LIMITED_API) || Py_LIMITED_API+0 >= _Py_PACK_VERSION(3, 9)) \
357
+ && (!defined(PYPY_VERSION) || PY_VERSION_HEX >= _Py_PACK_VERSION(3, 11)))
358
+ static inline PyFrameObject*
359
+ _PyThreadState_GetFrameBorrow(PyThreadState *tstate)
360
+ {
361
+ PyFrameObject *frame = PyThreadState_GetFrame(tstate);
362
+ Py_XDECREF(_PyObject_CAST(frame));
363
+ return frame;
364
+ }
365
+ #endif
366
+
367
+
368
+ // Added to Python 3.9 and limited C API 3.9. On Windows, it's not available
369
+ // before stable ABI 3.10.
370
+ // Added to PyPy3.12 v8.0.0.
371
+ #if ((PY_VERSION_HEX < _Py_PACK_VERSION(3, 9) \
372
+ || (defined(PYPY_VERSION) && PY_VERSION_HEX < _Py_PACK_VERSION(3, 12))) \
373
+ && !defined(Py_LIMITED_API))
374
+ static inline PyInterpreterState* PyInterpreterState_Get(void)
375
+ {
376
+ PyThreadState *tstate;
377
+ PyInterpreterState *interp;
378
+
379
+ tstate = PyThreadState_GET();
380
+ if (tstate == _Py_NULL) {
381
+ Py_FatalError("GIL released (tstate is NULL)");
382
+ }
383
+ interp = tstate->interp;
384
+ if (interp == _Py_NULL) {
385
+ Py_FatalError("no current interpreter");
386
+ }
387
+ return interp;
388
+ }
389
+ #endif
390
+
391
+
392
+ // bpo-39947 added PyThreadState_GetID() to Python 3.9
393
+ #if (_Py_PACK_VERSION(3, 7) <= PY_VERSION_HEX && PY_VERSION_HEX < _Py_PACK_VERSION(3, 9) \
394
+ && !defined(PYPY_VERSION) && !defined(Py_LIMITED_API))
395
+ static inline uint64_t PyThreadState_GetID(PyThreadState *tstate)
396
+ {
397
+ assert(tstate != _Py_NULL);
398
+ return tstate->id;
399
+ }
400
+ #endif
401
+
402
+ // bpo-43760 added PyThreadState_EnterTracing() to Python 3.11
403
+ #if (PY_VERSION_HEX < _Py_PACK_VERSION(3, 11) \
404
+ && !defined(PYPY_VERSION) && !defined(Py_LIMITED_API))
405
+ static inline void PyThreadState_EnterTracing(PyThreadState *tstate)
406
+ {
407
+ tstate->tracing++;
408
+ #if PY_VERSION_HEX >= _Py_PACK_VERSION(3, 10)
409
+ tstate->cframe->use_tracing = 0;
410
+ #else
411
+ tstate->use_tracing = 0;
412
+ #endif
413
+ }
414
+ #endif
415
+
416
+ // bpo-43760 added PyThreadState_LeaveTracing() to Python 3.11
417
+ #if (PY_VERSION_HEX < _Py_PACK_VERSION(3, 11) \
418
+ && !defined(PYPY_VERSION) && !defined(Py_LIMITED_API))
419
+ static inline void PyThreadState_LeaveTracing(PyThreadState *tstate)
420
+ {
421
+ int use_tracing = (tstate->c_tracefunc != _Py_NULL
422
+ || tstate->c_profilefunc != _Py_NULL);
423
+ tstate->tracing--;
424
+ #if PY_VERSION_HEX >= _Py_PACK_VERSION(3, 10)
425
+ tstate->cframe->use_tracing = use_tracing;
426
+ #else
427
+ tstate->use_tracing = use_tracing;
428
+ #endif
429
+ }
430
+ #endif
431
+
432
+
433
+ // bpo-37194 added PyObject_CallNoArgs() to Python 3.9
434
+ // PyObject_CallNoArgs() added to PyPy 3.9.16-v7.3.11
435
+ #if (!defined(PyObject_CallNoArgs) \
436
+ && (PY_VERSION_HEX < _Py_PACK_VERSION(3, 9) \
437
+ || (defined(Py_LIMITED_API) && Py_LIMITED_API+0 < _Py_PACK_VERSION(3, 9))))
438
+ static inline PyObject* PyObject_CallNoArgs(PyObject *func)
439
+ {
440
+ return PyObject_CallFunctionObjArgs(func, NULL);
441
+ }
442
+ #endif
443
+
444
+
445
+ // bpo-39245 made PyObject_CallOneArg() public (previously called
446
+ // _PyObject_CallOneArg) in Python 3.9
447
+ // PyObject_CallOneArg() added to PyPy 3.9.16-v7.3.11
448
+ #if (!defined(PyObject_CallOneArg) \
449
+ && (PY_VERSION_HEX < _Py_PACK_VERSION(3, 9) || defined(Py_LIMITED_API)))
450
+ static inline PyObject* PyObject_CallOneArg(PyObject *func, PyObject *arg)
451
+ {
452
+ return PyObject_CallFunctionObjArgs(func, arg, NULL);
453
+ }
454
+ #endif
455
+
456
+
457
+ // bpo-1635741 added PyModule_AddObjectRef() to Python 3.10.
458
+ // The function was aded to the limited C API 3.10.
459
+ #if (PY_VERSION_HEX < _Py_PACK_VERSION(3, 10) \
460
+ || (defined(Py_LIMITED_API) && Py_LIMITED_API+0 < _Py_PACK_VERSION(3, 10)) \
461
+ && !(_Py_PACK_VERSION(3, 10) <= PY_VERSION_HEX && PY_VERSION_HEX < _Py_PACK_VERSION(3, 11)))
462
+ static inline int
463
+ PyModule_AddObjectRef(PyObject *module, const char *name, PyObject *value)
464
+ {
465
+ int res;
466
+
467
+ if (!value && !PyErr_Occurred()) {
468
+ // PyModule_AddObject() raises TypeError in this case
469
+ PyErr_SetString(PyExc_SystemError,
470
+ "PyModule_AddObjectRef() must be called "
471
+ "with an exception raised if value is NULL");
472
+ return -1;
473
+ }
474
+
475
+ Py_XINCREF(value);
476
+ res = PyModule_AddObject(module, name, value);
477
+ if (res < 0) {
478
+ Py_XDECREF(value);
479
+ }
480
+ return res;
481
+ }
482
+ #endif
483
+
484
+
485
+ // bpo-40024 added PyModule_AddType() to Python 3.9
486
+ // On Windows, PyModule_AddType() was added to limited C API 3.9.
487
+ #if (PY_VERSION_HEX < _Py_PACK_VERSION(3, 9) \
488
+ || (defined(Py_LIMITED_API) && Py_LIMITED_API+0 < _Py_PACK_VERSION(3, 9)) \
489
+ || (defined(Py_LIMITED_API) && Py_LIMITED_API+0 < _Py_PACK_VERSION(3, 10) && defined(MS_WINDOWS)))
490
+ static inline int
491
+ _PythonCAPICompat_Module_AddType(PyObject *module, PyTypeObject *type)
492
+ {
493
+ #ifndef Py_LIMITED_API
494
+ const char *name, *dot;
495
+ #else
496
+ PyObject *name;
497
+ int res;
498
+ #endif
499
+
500
+ if (PyType_Ready(type) < 0) {
501
+ return -1;
502
+ }
503
+
504
+ #ifndef Py_LIMITED_API
505
+ // inline _PyType_Name()
506
+ name = type->tp_name;
507
+ assert(name != _Py_NULL);
508
+ dot = strrchr(name, '.');
509
+ if (dot != _Py_NULL) {
510
+ name = dot + 1;
511
+ }
512
+
513
+ return PyModule_AddObjectRef(module, name, _PyObject_CAST(type));
514
+ #else
515
+ if (!PyModule_Check(module)) {
516
+ PyErr_SetString(PyExc_TypeError,
517
+ "PyModule_AddObjectRef() first argument "
518
+ "must be a module");
519
+ return -1;
520
+ }
521
+
522
+ name = PyObject_GetAttrString(_PyObject_CAST(type), "__name__");
523
+ if (name == NULL) {
524
+ return -1;
525
+ }
526
+
527
+ PyObject *dict = PyModule_GetDict(module); // borrowed ref
528
+ res = PyDict_SetItem(dict, name, _PyObject_CAST(type));
529
+ Py_DECREF(name);
530
+ return res;
531
+ #endif
532
+ }
533
+
534
+ #if defined(Py_LIMITED_API) && Py_LIMITED_API+0 < _Py_PACK_VERSION(3, 10) && defined(MS_WINDOWS)
535
+ // On Python 3.9, PyModule_AddType() is part of the limited C API,
536
+ // but the function is not exported in the stable ABI.
537
+ # define PyModule_AddType _PythonCAPICompat_Module_AddType
538
+ #else
539
+ static inline int PyModule_AddType(PyObject *module, PyTypeObject *type)
540
+ {
541
+ return _PythonCAPICompat_Module_AddType(module, type);
542
+ }
543
+ #endif
544
+ #endif
545
+
546
+
547
+ // bpo-40241 added PyObject_GC_IsTracked() to Python 3.9.
548
+ // bpo-4688 added _PyObject_GC_IS_TRACKED() to Python 2.7.0a2.
549
+ // On Windows, PyObject_GC_IsTracked() was only added to stable ABI 3.10.
550
+ #if (PY_VERSION_HEX < _Py_PACK_VERSION(3, 9) \
551
+ && !defined(PYPY_VERSION) && !defined(Py_LIMITED_API))
552
+ static inline int PyObject_GC_IsTracked(PyObject* obj)
553
+ {
554
+ return (PyObject_IS_GC(obj) && _PyObject_GC_IS_TRACKED(obj));
555
+ }
556
+ #endif
557
+
558
+ // bpo-40241 added PyObject_GC_IsFinalized() to Python 3.9.
559
+ // bpo-18112 added _PyGCHead_FINALIZED() to Python 3.4.0 final.
560
+ // On Windows, PyObject_GC_IsFinalized() was only added to stable ABI 3.10.
561
+ #if (PY_VERSION_HEX < _Py_PACK_VERSION(3, 9) \
562
+ && !defined(PYPY_VERSION) && !defined(Py_LIMITED_API))
563
+ static inline int PyObject_GC_IsFinalized(PyObject *obj)
564
+ {
565
+ PyGC_Head *gc = _Py_CAST(PyGC_Head*, obj) - 1;
566
+ return (PyObject_IS_GC(obj) && _PyGCHead_FINALIZED(gc));
567
+ }
568
+ #endif
569
+
570
+
571
+ // bpo-39573 added Py_IS_TYPE() to Python 3.9
572
+ #if !defined(Py_IS_TYPE) && PY_VERSION_HEX < _Py_PACK_VERSION(3, 9)
573
+ static inline int _Py_IS_TYPE(PyObject *ob, PyTypeObject *type) {
574
+ return Py_TYPE(ob) == type;
575
+ }
576
+ #define Py_IS_TYPE(ob, type) _Py_IS_TYPE(_PyObject_CAST(ob), type)
577
+ #endif
578
+
579
+
580
+ // bpo-46906 added PyFloat_Pack2() and PyFloat_Unpack2() to Python 3.11a7.
581
+ // bpo-11734 added _PyFloat_Pack2() and _PyFloat_Unpack2() to Python 3.6.
582
+ // Python 3.11a2 moved _PyFloat_Pack2() and _PyFloat_Unpack2() to the internal
583
+ // C API: Python 3.11a2-3.11a6 versions are not supported.
584
+ #if (PY_VERSION_HEX <= _Py_PACK_VERSION(3, 11) \
585
+ && !defined(PYPY_VERSION) && !defined(Py_LIMITED_API))
586
+ static inline int PyFloat_Pack2(double x, char *p, int le)
587
+ { return _PyFloat_Pack2(x, (unsigned char*)p, le); }
588
+
589
+ static inline double PyFloat_Unpack2(const char *p, int le)
590
+ { return _PyFloat_Unpack2((const unsigned char *)p, le); }
591
+ #endif
592
+
593
+
594
+ // bpo-46906 added PyFloat_Pack4(), PyFloat_Pack8(), PyFloat_Unpack4() and
595
+ // PyFloat_Unpack8() to Python 3.11a7.
596
+ // Python 3.11a2 moved _PyFloat_Pack4(), _PyFloat_Pack8(), _PyFloat_Unpack4()
597
+ // and _PyFloat_Unpack8() to the internal C API: Python 3.11a2-3.11a6 versions
598
+ // are not supported.
599
+ #if (PY_VERSION_HEX <= _Py_PACK_VERSION(3, 11) \
600
+ && !defined(PYPY_VERSION) && !defined(Py_LIMITED_API))
601
+ static inline int PyFloat_Pack4(double x, char *p, int le)
602
+ { return _PyFloat_Pack4(x, (unsigned char*)p, le); }
603
+
604
+ static inline int PyFloat_Pack8(double x, char *p, int le)
605
+ { return _PyFloat_Pack8(x, (unsigned char*)p, le); }
606
+
607
+ static inline double PyFloat_Unpack4(const char *p, int le)
608
+ { return _PyFloat_Unpack4((const unsigned char *)p, le); }
609
+
610
+ static inline double PyFloat_Unpack8(const char *p, int le)
611
+ { return _PyFloat_Unpack8((const unsigned char *)p, le); }
612
+ #endif
613
+
614
+
615
+ // gh-92154 added PyCode_GetCode() to Python 3.11
616
+ #if (PY_VERSION_HEX < _Py_PACK_VERSION(3, 11) \
617
+ && !defined(PYPY_VERSION) && !defined(Py_LIMITED_API))
618
+ static inline PyObject* PyCode_GetCode(PyCodeObject *code)
619
+ {
620
+ return Py_NewRef(code->co_code);
621
+ }
622
+ #endif
623
+
624
+
625
+ // gh-95008 added PyCode_GetVarnames() to Python 3.11.0rc1
626
+ #if (PY_VERSION_HEX < _Py_PACK_VERSION(3, 11) \
627
+ && !defined(PYPY_VERSION) && !defined(Py_LIMITED_API))
628
+ static inline PyObject* PyCode_GetVarnames(PyCodeObject *code)
629
+ {
630
+ return Py_NewRef(code->co_varnames);
631
+ }
632
+ #endif
633
+
634
+ // gh-95008 added PyCode_GetFreevars() to Python 3.11.0rc1
635
+ #if (PY_VERSION_HEX < _Py_PACK_VERSION(3, 11) \
636
+ && !defined(PYPY_VERSION) && !defined(Py_LIMITED_API))
637
+ static inline PyObject* PyCode_GetFreevars(PyCodeObject *code)
638
+ {
639
+ return Py_NewRef(code->co_freevars);
640
+ }
641
+ #endif
642
+
643
+ // gh-95008 added PyCode_GetCellvars() to Python 3.11.0rc1
644
+ #if (PY_VERSION_HEX < _Py_PACK_VERSION(3, 11) \
645
+ && !defined(PYPY_VERSION) && !defined(Py_LIMITED_API))
646
+ static inline PyObject* PyCode_GetCellvars(PyCodeObject *code)
647
+ {
648
+ return Py_NewRef(code->co_cellvars);
649
+ }
650
+ #endif
651
+
652
+
653
+ // Py_UNUSED() was added to Python 3.4.
654
+ #ifndef Py_UNUSED
655
+ # if defined(__GNUC__) || defined(__clang__)
656
+ # define Py_UNUSED(name) _unused_ ## name __attribute__((unused))
657
+ # else
658
+ # define Py_UNUSED(name) _unused_ ## name
659
+ # endif
660
+ #endif
661
+
662
+
663
+ // PyImport_AddModuleRef() was added to Python 3.13 and limited C API 3.13
664
+ #if (PY_VERSION_HEX < _Py_PACK_VERSION(3, 13) \
665
+ || (defined(Py_LIMITED_API) && Py_LIMITED_API+0 < _Py_PACK_VERSION(3, 13)))
666
+ static inline PyObject* PyImport_AddModuleRef(const char *name)
667
+ {
668
+ return Py_XNewRef(PyImport_AddModule(name));
669
+ }
670
+ #endif
671
+
672
+
673
+ // gh-105927 added PyWeakref_GetRef() to Python 3.13
674
+ #if (PY_VERSION_HEX < _Py_PACK_VERSION(3, 13) \
675
+ || (defined(Py_LIMITED_API) && Py_LIMITED_API+0 < _Py_PACK_VERSION(3, 13)))
676
+
677
+ #if (defined(Py_LIMITED_API) && Py_LIMITED_API+0 < _Py_PACK_VERSION(3, 13) \
678
+ && PY_VERSION_HEX >= _Py_PACK_VERSION(3, 15))
679
+ // Function removed from Python 3.15 C API, but it remains available
680
+ // in the stable ABI
681
+ PyAPI_FUNC(PyObject *) PyWeakref_GetObject(PyObject *ref);
682
+ #endif
683
+
684
+ static inline int PyWeakref_GetRef(PyObject *ref, PyObject **pobj)
685
+ {
686
+ PyObject *obj;
687
+ if (ref != NULL && !PyWeakref_Check(ref)) {
688
+ *pobj = NULL;
689
+ PyErr_SetString(PyExc_TypeError, "expected a weakref");
690
+ return -1;
691
+ }
692
+
693
+ _Py_COMP_DIAG_PUSH
694
+ _Py_COMP_DIAG_IGNORE_DEPR_DECLS
695
+ obj = PyWeakref_GetObject(ref);
696
+ _Py_COMP_DIAG_POP
697
+ if (obj == NULL) {
698
+ // SystemError if ref is NULL
699
+ *pobj = NULL;
700
+ return -1;
701
+ }
702
+ if (obj == Py_None) {
703
+ *pobj = NULL;
704
+ return 0;
705
+ }
706
+ *pobj = Py_NewRef(obj);
707
+ return 1;
708
+ }
709
+ #endif
710
+
711
+
712
+ // bpo-36974 added PY_VECTORCALL_ARGUMENTS_OFFSET to Python 3.8b1
713
+ #ifndef PY_VECTORCALL_ARGUMENTS_OFFSET
714
+ # define PY_VECTORCALL_ARGUMENTS_OFFSET (_Py_CAST(size_t, 1) << (8 * sizeof(size_t) - 1))
715
+ #endif
716
+
717
+ // bpo-36974 added PyVectorcall_NARGS() to Python 3.8b1
718
+ #if (PY_VERSION_HEX < _Py_PACK_VERSION(3, 8) \
719
+ || (defined(Py_LIMITED_API) && PY_VERSION_HEX < _Py_PACK_VERSION(3, 12)))
720
+ static inline Py_ssize_t PyVectorcall_NARGS(size_t n)
721
+ {
722
+ return n & ~PY_VECTORCALL_ARGUMENTS_OFFSET;
723
+ }
724
+ #endif
725
+
726
+
727
+ // gh-105922 added PyObject_Vectorcall() to Python 3.9
728
+ #if (PY_VERSION_HEX < _Py_PACK_VERSION(3, 9) \
729
+ || (defined(Py_LIMITED_API) && Py_LIMITED_API+0 < _Py_PACK_VERSION(3, 12)))
730
+ static inline PyObject*
731
+ PyObject_Vectorcall(PyObject *callable, PyObject *const *args,
732
+ size_t nargsf, PyObject *kwnames)
733
+ {
734
+ #if (PY_VERSION_HEX >= _Py_PACK_VERSION(3, 8) \
735
+ && !defined(PYPY_VERSION) && !defined(Py_LIMITED_API))
736
+ // bpo-36974 added _PyObject_Vectorcall() to Python 3.8
737
+ return _PyObject_Vectorcall(callable, args, nargsf, kwnames);
738
+ #else
739
+ PyObject *posargs = NULL, *kwargs = NULL;
740
+ PyObject *res;
741
+ Py_ssize_t nposargs, nkwargs, i;
742
+
743
+ if (nargsf != 0 && args == NULL) {
744
+ PyErr_BadInternalCall();
745
+ goto error;
746
+ }
747
+ if (kwnames != NULL && !PyTuple_Check(kwnames)) {
748
+ PyErr_BadInternalCall();
749
+ goto error;
750
+ }
751
+
752
+ nposargs = (Py_ssize_t)PyVectorcall_NARGS(nargsf);
753
+ if (kwnames) {
754
+ #ifndef Py_LIMITED_API
755
+ nkwargs = PyTuple_GET_SIZE(kwnames);
756
+ #else
757
+ nkwargs = PyTuple_Size(kwnames);
758
+ #endif
759
+ }
760
+ else {
761
+ nkwargs = 0;
762
+ }
763
+
764
+ posargs = PyTuple_New(nposargs);
765
+ if (posargs == NULL) {
766
+ goto error;
767
+ }
768
+ if (nposargs) {
769
+ for (i=0; i < nposargs; i++) {
770
+ #ifndef Py_LIMITED_API
771
+ PyTuple_SET_ITEM(posargs, i, Py_NewRef(*args));
772
+ #else
773
+ if (PyTuple_SetItem(posargs, i, Py_NewRef(*args)) < 0) {
774
+ goto error;
775
+ }
776
+ #endif
777
+ args++;
778
+ }
779
+ }
780
+
781
+ if (nkwargs) {
782
+ kwargs = PyDict_New();
783
+ if (kwargs == NULL) {
784
+ goto error;
785
+ }
786
+
787
+ for (i = 0; i < nkwargs; i++) {
788
+ #ifndef Py_LIMITED_API
789
+ PyObject *key = PyTuple_GET_ITEM(kwnames, i); // borrowed ref
790
+ #else
791
+ PyObject *key = PyTuple_GetItem(kwnames, i); // borrowed ref
792
+ if (key == NULL) {
793
+ goto error;
794
+ }
795
+ #endif
796
+ PyObject *value = *args;
797
+ args++;
798
+ if (PyDict_SetItem(kwargs, key, value) < 0) {
799
+ goto error;
800
+ }
801
+ }
802
+ }
803
+ else {
804
+ kwargs = NULL;
805
+ }
806
+
807
+ res = PyObject_Call(callable, posargs, kwargs);
808
+ Py_DECREF(posargs);
809
+ Py_XDECREF(kwargs);
810
+ return res;
811
+
812
+ error:
813
+ Py_DECREF(posargs);
814
+ Py_XDECREF(kwargs);
815
+ return NULL;
816
+ #endif
817
+ }
818
+ #endif
819
+
820
+
821
+ // gh-106521 added PyObject_GetOptionalAttr() and
822
+ // PyObject_GetOptionalAttrString() to Python 3.13
823
+ #if (PY_VERSION_HEX < _Py_PACK_VERSION(3, 13) \
824
+ || (defined(Py_LIMITED_API) && Py_LIMITED_API+0 < _Py_PACK_VERSION(3, 13)))
825
+ static inline int
826
+ PyObject_GetOptionalAttr(PyObject *obj, PyObject *attr_name, PyObject **result)
827
+ {
828
+ // bpo-32571 added _PyObject_LookupAttr() to Python 3.7
829
+ #if (PY_VERSION_HEX >= _Py_PACK_VERSION(3, 7) \
830
+ && !defined(PYPY_VERSION) && !defined(Py_LIMITED_API))
831
+ return _PyObject_LookupAttr(obj, attr_name, result);
832
+ #else
833
+ *result = PyObject_GetAttr(obj, attr_name);
834
+ if (*result != NULL) {
835
+ return 1;
836
+ }
837
+ if (!PyErr_Occurred()) {
838
+ return 0;
839
+ }
840
+ if (PyErr_ExceptionMatches(PyExc_AttributeError)) {
841
+ PyErr_Clear();
842
+ return 0;
843
+ }
844
+ return -1;
845
+ #endif
846
+ }
847
+
848
+ static inline int
849
+ PyObject_GetOptionalAttrString(PyObject *obj, const char *attr_name, PyObject **result)
850
+ {
851
+ int rc;
852
+ PyObject *name_obj = PyUnicode_FromString(attr_name);
853
+ if (name_obj == NULL) {
854
+ *result = NULL;
855
+ return -1;
856
+ }
857
+ rc = PyObject_GetOptionalAttr(obj, name_obj, result);
858
+ Py_DECREF(name_obj);
859
+ return rc;
860
+ }
861
+ #endif
862
+
863
+
864
+ // gh-106307 added PyObject_GetOptionalAttr() and
865
+ // PyMapping_GetOptionalItemString() to Python 3.13
866
+ #if (PY_VERSION_HEX < _Py_PACK_VERSION(3, 13) \
867
+ || (defined(Py_LIMITED_API) && Py_LIMITED_API+0 < _Py_PACK_VERSION(3, 13)))
868
+ static inline int
869
+ PyMapping_GetOptionalItem(PyObject *obj, PyObject *key, PyObject **result)
870
+ {
871
+ *result = PyObject_GetItem(obj, key);
872
+ if (*result) {
873
+ return 1;
874
+ }
875
+ if (!PyErr_ExceptionMatches(PyExc_KeyError)) {
876
+ return -1;
877
+ }
878
+ PyErr_Clear();
879
+ return 0;
880
+ }
881
+
882
+ static inline int
883
+ PyMapping_GetOptionalItemString(PyObject *obj, const char *key, PyObject **result)
884
+ {
885
+ int rc;
886
+ PyObject *key_obj = PyUnicode_FromString(key);
887
+ if (key_obj == NULL) {
888
+ *result = NULL;
889
+ return -1;
890
+ }
891
+ rc = PyMapping_GetOptionalItem(obj, key_obj, result);
892
+ Py_DECREF(key_obj);
893
+ return rc;
894
+ }
895
+ #endif
896
+
897
+ // gh-108511 added PyMapping_HasKeyWithError() and
898
+ // PyMapping_HasKeyStringWithError() to Python 3.13
899
+ #if PY_VERSION_HEX < _Py_PACK_VERSION(3, 13)
900
+ static inline int
901
+ PyMapping_HasKeyWithError(PyObject *obj, PyObject *key)
902
+ {
903
+ PyObject *res;
904
+ int rc = PyMapping_GetOptionalItem(obj, key, &res);
905
+ Py_XDECREF(res);
906
+ return rc;
907
+ }
908
+
909
+ static inline int
910
+ PyMapping_HasKeyStringWithError(PyObject *obj, const char *key)
911
+ {
912
+ PyObject *res;
913
+ int rc = PyMapping_GetOptionalItemString(obj, key, &res);
914
+ Py_XDECREF(res);
915
+ return rc;
916
+ }
917
+ #endif
918
+
919
+
920
+ // gh-108511 added PyObject_HasAttrWithError() and
921
+ // PyObject_HasAttrStringWithError() to Python 3.13
922
+ #if (PY_VERSION_HEX < _Py_PACK_VERSION(3, 13) \
923
+ || (defined(Py_LIMITED_API) && Py_LIMITED_API+0 < _Py_PACK_VERSION(3, 13)))
924
+ static inline int
925
+ PyObject_HasAttrWithError(PyObject *obj, PyObject *attr)
926
+ {
927
+ PyObject *res;
928
+ int rc = PyObject_GetOptionalAttr(obj, attr, &res);
929
+ Py_XDECREF(res);
930
+ return rc;
931
+ }
932
+
933
+ static inline int
934
+ PyObject_HasAttrStringWithError(PyObject *obj, const char *attr)
935
+ {
936
+ PyObject *res;
937
+ int rc = PyObject_GetOptionalAttrString(obj, attr, &res);
938
+ Py_XDECREF(res);
939
+ return rc;
940
+ }
941
+ #endif
942
+
943
+
944
+ // gh-106004 added PyDict_GetItemRef() and PyDict_GetItemStringRef()
945
+ // to Python 3.13
946
+ #if (PY_VERSION_HEX < _Py_PACK_VERSION(3, 13) \
947
+ || (defined(Py_LIMITED_API) && Py_LIMITED_API+0 < _Py_PACK_VERSION(3, 13)))
948
+ static inline int
949
+ PyDict_GetItemRef(PyObject *mp, PyObject *key, PyObject **result)
950
+ {
951
+ PyObject *item = PyDict_GetItemWithError(mp, key);
952
+ if (item != NULL) {
953
+ *result = Py_NewRef(item);
954
+ return 1; // found
955
+ }
956
+ if (!PyErr_Occurred()) {
957
+ *result = NULL;
958
+ return 0; // not found
959
+ }
960
+ *result = NULL;
961
+ return -1;
962
+ }
963
+
964
+ static inline int
965
+ PyDict_GetItemStringRef(PyObject *mp, const char *key, PyObject **result)
966
+ {
967
+ int res;
968
+ PyObject *key_obj = PyUnicode_FromString(key);
969
+ if (key_obj == NULL) {
970
+ *result = NULL;
971
+ return -1;
972
+ }
973
+ res = PyDict_GetItemRef(mp, key_obj, result);
974
+ Py_DECREF(key_obj);
975
+ return res;
976
+ }
977
+ #endif
978
+
979
+
980
+ // gh-106307 added PyModule_Add() to Python 3.13
981
+ #if (PY_VERSION_HEX < _Py_PACK_VERSION(3, 13) \
982
+ || (defined(Py_LIMITED_API) && Py_LIMITED_API+0 < _Py_PACK_VERSION(3, 13)))
983
+ static inline int
984
+ PyModule_Add(PyObject *mod, const char *name, PyObject *value)
985
+ {
986
+ int res = PyModule_AddObjectRef(mod, name, value);
987
+ Py_XDECREF(value);
988
+ return res;
989
+ }
990
+ #endif
991
+
992
+
993
+ // gh-108014 added Py_IsFinalizing() to Python 3.13 (limited C API).
994
+ // bpo-1856 added _Py_Finalizing to Python 3.2.1b1.
995
+ // _Py_IsFinalizing() was added to PyPy 7.3.0.
996
+ #if ((PY_VERSION_HEX < _Py_PACK_VERSION(3, 13)) \
997
+ && (!defined(PYPY_VERSION_NUM) || PYPY_VERSION_NUM >= 0x7030000) \
998
+ && !defined(Py_LIMITED_API))
999
+ static inline int Py_IsFinalizing(void)
1000
+ {
1001
+ #if PY_VERSION_HEX >= _Py_PACK_VERSION(3, 7)
1002
+ // _Py_IsFinalizing() was added to Python 3.7.
1003
+ return _Py_IsFinalizing();
1004
+ #else
1005
+ return (_Py_Finalizing != NULL);
1006
+ #endif
1007
+ }
1008
+ #endif
1009
+
1010
+
1011
+ // gh-108323 added PyDict_ContainsString() to Python 3.13
1012
+ #if PY_VERSION_HEX < _Py_PACK_VERSION(3, 13) || defined(Py_LIMITED_API)
1013
+ static inline int PyDict_ContainsString(PyObject *op, const char *key)
1014
+ {
1015
+ PyObject *key_obj = PyUnicode_FromString(key);
1016
+ if (key_obj == NULL) {
1017
+ return -1;
1018
+ }
1019
+ int res = PyDict_Contains(op, key_obj);
1020
+ Py_DECREF(key_obj);
1021
+ return res;
1022
+ }
1023
+ #endif
1024
+
1025
+
1026
+ // gh-108445 added PyLong_AsInt() to Python 3.13
1027
+ #if (PY_VERSION_HEX < _Py_PACK_VERSION(3, 13) \
1028
+ || (defined(Py_LIMITED_API) && Py_LIMITED_API+0 < _Py_PACK_VERSION(3, 13)))
1029
+ static inline int PyLong_AsInt(PyObject *obj)
1030
+ {
1031
+ #if defined(PYPY_VERSION) || defined(Py_LIMITED_API)
1032
+ long value = PyLong_AsLong(obj);
1033
+ if (value == -1 && PyErr_Occurred()) {
1034
+ return -1;
1035
+ }
1036
+ if (value < (long)INT_MIN || (long)INT_MAX < value) {
1037
+ PyErr_SetString(PyExc_OverflowError,
1038
+ "Python int too large to convert to C int");
1039
+ return -1;
1040
+ }
1041
+ return (int)value;
1042
+ #else
1043
+ return _PyLong_AsInt(obj);
1044
+ #endif
1045
+ }
1046
+ #endif
1047
+
1048
+
1049
+ // gh-107073 added PyObject_VisitManagedDict() to Python 3.13
1050
+ #if PY_VERSION_HEX < _Py_PACK_VERSION(3, 13) && !defined(Py_LIMITED_API)
1051
+ static inline int
1052
+ PyObject_VisitManagedDict(PyObject *obj, visitproc visit, void *arg)
1053
+ {
1054
+ PyObject **dict = _PyObject_GetDictPtr(obj);
1055
+ if (dict == NULL || *dict == NULL) {
1056
+ return -1;
1057
+ }
1058
+ Py_VISIT(*dict);
1059
+ return 0;
1060
+ }
1061
+
1062
+ static inline void
1063
+ PyObject_ClearManagedDict(PyObject *obj)
1064
+ {
1065
+ PyObject **dict = _PyObject_GetDictPtr(obj);
1066
+ if (dict == NULL || *dict == NULL) {
1067
+ return;
1068
+ }
1069
+ Py_CLEAR(*dict);
1070
+ }
1071
+ #endif
1072
+
1073
+ // gh-108867 added PyThreadState_GetUnchecked() to Python 3.13
1074
+ // Python 3.5.2 added _PyThreadState_UncheckedGet().
1075
+ #if PY_VERSION_HEX < _Py_PACK_VERSION(3, 13) && !defined(Py_LIMITED_API)
1076
+ static inline PyThreadState*
1077
+ PyThreadState_GetUnchecked(void)
1078
+ {
1079
+ return _PyThreadState_UncheckedGet();
1080
+ }
1081
+ #endif
1082
+
1083
+ // gh-110289 added PyUnicode_EqualToUTF8() and PyUnicode_EqualToUTF8AndSize()
1084
+ // to Python 3.13
1085
+ #if (PY_VERSION_HEX < _Py_PACK_VERSION(3, 13) \
1086
+ || (defined(Py_LIMITED_API) && Py_LIMITED_API+0 < _Py_PACK_VERSION(3, 13)))
1087
+ static inline int
1088
+ PyUnicode_EqualToUTF8AndSize(PyObject *unicode, const char *str, Py_ssize_t str_len)
1089
+ {
1090
+ Py_ssize_t len;
1091
+ #if defined(Py_LIMITED_API) && Py_LIMITED_API+0 < _Py_PACK_VERSION(3, 10)
1092
+ PyObject *bytes;
1093
+ #endif
1094
+ const void *utf8;
1095
+ PyObject *exc_type, *exc_value, *exc_tb;
1096
+ int res;
1097
+
1098
+ // API cannot report errors so save/restore the exception
1099
+ PyErr_Fetch(&exc_type, &exc_value, &exc_tb);
1100
+
1101
+ #ifndef Py_LIMITED_API
1102
+ if (PyUnicode_READY(unicode) < 0) {
1103
+ // Memory allocation failure. The API cannot report error,
1104
+ // so ignore the exception and return 0.
1105
+ res = 0;
1106
+ goto done;
1107
+ }
1108
+
1109
+ if (PyUnicode_IS_ASCII(unicode)) {
1110
+ utf8 = PyUnicode_DATA(unicode);
1111
+ len = PyUnicode_GET_LENGTH(unicode);
1112
+ }
1113
+ else
1114
+ #endif
1115
+ {
1116
+ #if defined(Py_LIMITED_API) && Py_LIMITED_API+0 < _Py_PACK_VERSION(3, 10)
1117
+ // Limited C API 3.9 and older
1118
+ bytes = PyUnicode_AsUTF8String(unicode);
1119
+ if (bytes == NULL) {
1120
+ // Memory allocation failure. The API cannot report error,
1121
+ // so ignore the exception and return 0.
1122
+ res = 0;
1123
+ goto done;
1124
+ }
1125
+ utf8 = PyBytes_AsString(bytes);
1126
+ len = PyBytes_Size(bytes);
1127
+ #else
1128
+ // Python 3.12 and older, and limited C API 3.10 and newer.
1129
+ // Python 3.10 added PyUnicode_AsUTF8AndSize() to the limited C API.
1130
+ utf8 = PyUnicode_AsUTF8AndSize(unicode, &len);
1131
+ if (utf8 == NULL) {
1132
+ // Memory allocation failure. The API cannot report error,
1133
+ // so ignore the exception and return 0.
1134
+ res = 0;
1135
+ goto done;
1136
+ }
1137
+ #endif
1138
+ }
1139
+
1140
+ if (len != str_len) {
1141
+ res = 0;
1142
+ }
1143
+ else {
1144
+ res = (memcmp(utf8, str, (size_t)len) == 0);
1145
+ }
1146
+ #if defined(Py_LIMITED_API) && Py_LIMITED_API+0 < _Py_PACK_VERSION(3, 10)
1147
+ Py_DECREF(bytes);
1148
+ #endif
1149
+
1150
+ done:
1151
+ PyErr_Restore(exc_type, exc_value, exc_tb);
1152
+ return res;
1153
+ }
1154
+
1155
+ static inline int
1156
+ PyUnicode_EqualToUTF8(PyObject *unicode, const char *str)
1157
+ {
1158
+ return PyUnicode_EqualToUTF8AndSize(unicode, str, (Py_ssize_t)strlen(str));
1159
+ }
1160
+ #endif
1161
+
1162
+
1163
+ // gh-111138 added PyList_Extend() and PyList_Clear() to Python 3.13
1164
+ #if PY_VERSION_HEX < _Py_PACK_VERSION(3, 13) || defined(Py_LIMITED_API)
1165
+ static inline int
1166
+ PyList_Extend(PyObject *list, PyObject *iterable)
1167
+ {
1168
+ return PyList_SetSlice(list, PY_SSIZE_T_MAX, PY_SSIZE_T_MAX, iterable);
1169
+ }
1170
+
1171
+ static inline int
1172
+ PyList_Clear(PyObject *list)
1173
+ {
1174
+ return PyList_SetSlice(list, 0, PY_SSIZE_T_MAX, NULL);
1175
+ }
1176
+ #endif
1177
+
1178
+ // gh-111262 added PyDict_Pop() and PyDict_PopString() to Python 3.13
1179
+ #if PY_VERSION_HEX < _Py_PACK_VERSION(3, 13) || defined(Py_LIMITED_API)
1180
+ static inline int
1181
+ PyDict_Pop(PyObject *dict, PyObject *key, PyObject **result)
1182
+ {
1183
+ PyObject *value;
1184
+
1185
+ if (!PyDict_Check(dict)) {
1186
+ PyErr_BadInternalCall();
1187
+ if (result) {
1188
+ *result = NULL;
1189
+ }
1190
+ return -1;
1191
+ }
1192
+
1193
+ // bpo-16991 added _PyDict_Pop() to Python 3.5.
1194
+ // Python 3.6 changed _PyDict_Pop() first argument type to PyObject*.
1195
+ // Python 3.13 removed _PyDict_Pop().
1196
+ #if defined(PYPY_VERSION) || PY_VERSION_HEX >= _Py_PACK_VERSION(3, 13) || defined(Py_LIMITED_API)
1197
+ value = PyObject_CallMethod(dict, "pop", "O", key);
1198
+ #else
1199
+ value = _PyDict_Pop(dict, key, NULL);
1200
+ #endif
1201
+ if (value == NULL) {
1202
+ if (result) {
1203
+ *result = NULL;
1204
+ }
1205
+ if (PyErr_Occurred() && !PyErr_ExceptionMatches(PyExc_KeyError)) {
1206
+ return -1;
1207
+ }
1208
+ PyErr_Clear();
1209
+ return 0;
1210
+ }
1211
+ if (result) {
1212
+ *result = value;
1213
+ }
1214
+ else {
1215
+ Py_DECREF(value);
1216
+ }
1217
+ return 1;
1218
+ }
1219
+
1220
+ static inline int
1221
+ PyDict_PopString(PyObject *dict, const char *key, PyObject **result)
1222
+ {
1223
+ PyObject *key_obj = PyUnicode_FromString(key);
1224
+ if (key_obj == NULL) {
1225
+ if (result != NULL) {
1226
+ *result = NULL;
1227
+ }
1228
+ return -1;
1229
+ }
1230
+
1231
+ int res = PyDict_Pop(dict, key_obj, result);
1232
+ Py_DECREF(key_obj);
1233
+ return res;
1234
+ }
1235
+ #endif
1236
+
1237
+
1238
+ // gh-111545 added Py_HashPointer() to Python 3.13
1239
+ #if PY_VERSION_HEX < _Py_PACK_VERSION(3, 13) || defined(Py_LIMITED_API)
1240
+ static inline Py_hash_t Py_HashPointer(const void *ptr)
1241
+ {
1242
+ #if PY_VERSION_HEX >= _Py_PACK_VERSION(3, 9) && !defined(PYPY_VERSION) && !defined(Py_LIMITED_API)
1243
+ return _Py_HashPointer(ptr);
1244
+ #elif !defined(Py_LIMITED_API)
1245
+ // PyPy _Py_HashPointer() argument type is "void*", not "const void*"
1246
+ return _Py_HashPointer(_Py_CAST(void*, ptr));
1247
+ #else
1248
+ // Limited C API implementation
1249
+ uintptr_t x = (uintptr_t)ptr;
1250
+ Py_BUILD_ASSERT(sizeof(x) == sizeof(ptr));
1251
+
1252
+ // Bottom 3 or 4 bits are likely to be 0; rotate x by 4 to the right
1253
+ // to avoid excessive hash collisions for dicts and sets.
1254
+ x = (x >> 4) | (x << (8 * sizeof(uintptr_t) - 4));
1255
+
1256
+ if (x == (uintptr_t)-1) {
1257
+ x = (uintptr_t)-2;
1258
+ }
1259
+
1260
+ Py_BUILD_ASSERT(sizeof(x) == sizeof(Py_hash_t));
1261
+ return (Py_hash_t)x;
1262
+ #endif
1263
+ }
1264
+ #endif
1265
+
1266
+
1267
+ #if PY_VERSION_HEX < _Py_PACK_VERSION(3, 13) || defined(Py_LIMITED_API)
1268
+ Py_hash_t
1269
+ PyObject_GenericHash(PyObject *obj)
1270
+ {
1271
+ return Py_HashPointer(obj);
1272
+ }
1273
+ #endif
1274
+
1275
+
1276
+ // Python 3.13a4 added a PyTime API.
1277
+ // Use the private API added to Python 3.5.
1278
+ #if PY_VERSION_HEX < _Py_PACK_VERSION(3, 13) && !defined(Py_LIMITED_API)
1279
+ typedef _PyTime_t PyTime_t;
1280
+ #define PyTime_MIN _PyTime_MIN
1281
+ #define PyTime_MAX _PyTime_MAX
1282
+
1283
+ static inline double PyTime_AsSecondsDouble(PyTime_t t)
1284
+ { return _PyTime_AsSecondsDouble(t); }
1285
+
1286
+ static inline int PyTime_Monotonic(PyTime_t *result)
1287
+ { return _PyTime_GetMonotonicClockWithInfo(result, NULL); }
1288
+
1289
+ static inline int PyTime_Time(PyTime_t *result)
1290
+ { return _PyTime_GetSystemClockWithInfo(result, NULL); }
1291
+
1292
+ static inline int PyTime_PerfCounter(PyTime_t *result)
1293
+ {
1294
+ #if PY_VERSION_HEX >= _Py_PACK_VERSION(3, 7) && !defined(PYPY_VERSION)
1295
+ return _PyTime_GetPerfCounterWithInfo(result, NULL);
1296
+ #elif PY_VERSION_HEX >= _Py_PACK_VERSION(3, 7)
1297
+ // Call time.perf_counter_ns() and convert Python int object to PyTime_t.
1298
+ // Cache time.perf_counter_ns() function for best performance.
1299
+ static PyObject *func = NULL;
1300
+ if (func == NULL) {
1301
+ PyObject *mod = PyImport_ImportModule("time");
1302
+ if (mod == NULL) {
1303
+ return -1;
1304
+ }
1305
+
1306
+ func = PyObject_GetAttrString(mod, "perf_counter_ns");
1307
+ Py_DECREF(mod);
1308
+ if (func == NULL) {
1309
+ return -1;
1310
+ }
1311
+ }
1312
+
1313
+ PyObject *res = PyObject_CallNoArgs(func);
1314
+ if (res == NULL) {
1315
+ return -1;
1316
+ }
1317
+ long long value = PyLong_AsLongLong(res);
1318
+ Py_DECREF(res);
1319
+
1320
+ if (value == -1 && PyErr_Occurred()) {
1321
+ return -1;
1322
+ }
1323
+
1324
+ Py_BUILD_ASSERT(sizeof(value) >= sizeof(PyTime_t));
1325
+ *result = (PyTime_t)value;
1326
+ return 0;
1327
+ #else
1328
+ // Call time.perf_counter() and convert C double to PyTime_t.
1329
+ // Cache time.perf_counter() function for best performance.
1330
+ static PyObject *func = NULL;
1331
+ if (func == NULL) {
1332
+ PyObject *mod = PyImport_ImportModule("time");
1333
+ if (mod == NULL) {
1334
+ return -1;
1335
+ }
1336
+
1337
+ func = PyObject_GetAttrString(mod, "perf_counter");
1338
+ Py_DECREF(mod);
1339
+ if (func == NULL) {
1340
+ return -1;
1341
+ }
1342
+ }
1343
+
1344
+ PyObject *res = PyObject_CallNoArgs(func);
1345
+ if (res == NULL) {
1346
+ return -1;
1347
+ }
1348
+ double d = PyFloat_AsDouble(res);
1349
+ Py_DECREF(res);
1350
+
1351
+ if (d == -1.0 && PyErr_Occurred()) {
1352
+ return -1;
1353
+ }
1354
+
1355
+ // Avoid floor() to avoid having to link to libm
1356
+ *result = (PyTime_t)(d * 1e9);
1357
+ return 0;
1358
+ #endif
1359
+ }
1360
+
1361
+ #endif
1362
+
1363
+ // gh-111389 added hash constants to Python 3.13. These constants were
1364
+ // added first as private macros to Python 3.4 and PyPy 7.3.8.
1365
+ #if (!defined(PyHASH_BITS) \
1366
+ && ((!defined(PYPY_VERSION) && PY_VERSION_HEX >= _Py_PACK_VERSION(3, 4)) \
1367
+ || (defined(PYPY_VERSION) && PY_VERSION_HEX >= _Py_PACK_VERSION(3, 7) \
1368
+ && PYPY_VERSION_NUM >= _Py_PACK_FULL_VERSION(7, 3, 8, 0, 0))) \
1369
+ && !defined(Py_LIMITED_API))
1370
+ # define PyHASH_BITS _PyHASH_BITS
1371
+ # define PyHASH_MODULUS _PyHASH_MODULUS
1372
+ # define PyHASH_INF _PyHASH_INF
1373
+ # define PyHASH_IMAG _PyHASH_IMAG
1374
+ #endif
1375
+
1376
+
1377
+ // gh-111545 added Py_GetConstant() and Py_GetConstantBorrowed()
1378
+ // to Python 3.13
1379
+ #if (PY_VERSION_HEX < _Py_PACK_VERSION(3, 13) \
1380
+ || (defined(Py_LIMITED_API) && Py_LIMITED_API+0 < _Py_PACK_VERSION(3, 13)))
1381
+
1382
+ #ifndef Py_CONSTANT_NONE
1383
+ # define Py_CONSTANT_NONE 0
1384
+ # define Py_CONSTANT_FALSE 1
1385
+ # define Py_CONSTANT_TRUE 2
1386
+ # define Py_CONSTANT_ELLIPSIS 3
1387
+ # define Py_CONSTANT_NOT_IMPLEMENTED 4
1388
+ # define Py_CONSTANT_ZERO 5
1389
+ # define Py_CONSTANT_ONE 6
1390
+ # define Py_CONSTANT_EMPTY_STR 7
1391
+ # define Py_CONSTANT_EMPTY_BYTES 8
1392
+ # define Py_CONSTANT_EMPTY_TUPLE 9
1393
+ #endif
1394
+
1395
+ static inline PyObject* Py_GetConstant(unsigned int constant_id)
1396
+ {
1397
+ static PyObject* constants[Py_CONSTANT_EMPTY_TUPLE + 1] = {NULL};
1398
+
1399
+ if (constants[Py_CONSTANT_NONE] == NULL) {
1400
+ constants[Py_CONSTANT_NONE] = Py_None;
1401
+ constants[Py_CONSTANT_FALSE] = Py_False;
1402
+ constants[Py_CONSTANT_TRUE] = Py_True;
1403
+ constants[Py_CONSTANT_ELLIPSIS] = Py_Ellipsis;
1404
+ constants[Py_CONSTANT_NOT_IMPLEMENTED] = Py_NotImplemented;
1405
+
1406
+ constants[Py_CONSTANT_ZERO] = PyLong_FromLong(0);
1407
+ if (constants[Py_CONSTANT_ZERO] == NULL) {
1408
+ goto fatal_error;
1409
+ }
1410
+
1411
+ constants[Py_CONSTANT_ONE] = PyLong_FromLong(1);
1412
+ if (constants[Py_CONSTANT_ONE] == NULL) {
1413
+ goto fatal_error;
1414
+ }
1415
+
1416
+ constants[Py_CONSTANT_EMPTY_STR] = PyUnicode_FromStringAndSize("", 0);
1417
+ if (constants[Py_CONSTANT_EMPTY_STR] == NULL) {
1418
+ goto fatal_error;
1419
+ }
1420
+
1421
+ constants[Py_CONSTANT_EMPTY_BYTES] = PyBytes_FromStringAndSize("", 0);
1422
+ if (constants[Py_CONSTANT_EMPTY_BYTES] == NULL) {
1423
+ goto fatal_error;
1424
+ }
1425
+
1426
+ constants[Py_CONSTANT_EMPTY_TUPLE] = PyTuple_New(0);
1427
+ if (constants[Py_CONSTANT_EMPTY_TUPLE] == NULL) {
1428
+ goto fatal_error;
1429
+ }
1430
+ // goto dance to avoid compiler warnings about Py_FatalError()
1431
+ goto init_done;
1432
+
1433
+ fatal_error:
1434
+ // This case should never happen
1435
+ Py_FatalError("Py_GetConstant() failed to get constants");
1436
+ }
1437
+
1438
+ init_done:
1439
+ if (constant_id <= Py_CONSTANT_EMPTY_TUPLE) {
1440
+ return Py_NewRef(constants[constant_id]);
1441
+ }
1442
+ else {
1443
+ PyErr_BadInternalCall();
1444
+ return NULL;
1445
+ }
1446
+ }
1447
+
1448
+ static inline PyObject* Py_GetConstantBorrowed(unsigned int constant_id)
1449
+ {
1450
+ PyObject *obj = Py_GetConstant(constant_id);
1451
+ Py_XDECREF(obj);
1452
+ return obj;
1453
+ }
1454
+ #endif
1455
+
1456
+
1457
+ // gh-114329 added PyList_GetItemRef() to Python 3.13
1458
+ #if (PY_VERSION_HEX < _Py_PACK_VERSION(3, 13) \
1459
+ || (defined(Py_LIMITED_API) && Py_LIMITED_API+0 < _Py_PACK_VERSION(3, 13)))
1460
+ static inline PyObject *
1461
+ PyList_GetItemRef(PyObject *op, Py_ssize_t index)
1462
+ {
1463
+ PyObject *item = PyList_GetItem(op, index);
1464
+ Py_XINCREF(item);
1465
+ return item;
1466
+ }
1467
+ #endif
1468
+
1469
+
1470
+ // gh-114329 added PyList_GetItemRef() to Python 3.13
1471
+ #if (PY_VERSION_HEX < _Py_PACK_VERSION(3, 13) \
1472
+ || (defined(Py_LIMITED_API) && Py_LIMITED_API+0 < _Py_PACK_VERSION(3, 15)))
1473
+ static inline int
1474
+ PyDict_SetDefaultRef(PyObject *d, PyObject *key, PyObject *default_value,
1475
+ PyObject **result)
1476
+ {
1477
+ PyObject *value;
1478
+ if (PyDict_GetItemRef(d, key, &value) < 0) {
1479
+ // get error
1480
+ if (result) {
1481
+ *result = NULL;
1482
+ }
1483
+ return -1;
1484
+ }
1485
+ if (value != NULL) {
1486
+ // present
1487
+ if (result) {
1488
+ *result = value;
1489
+ }
1490
+ else {
1491
+ Py_DECREF(value);
1492
+ }
1493
+ return 1;
1494
+ }
1495
+
1496
+ // missing: set the item
1497
+ if (PyDict_SetItem(d, key, default_value) < 0) {
1498
+ // set error
1499
+ if (result) {
1500
+ *result = NULL;
1501
+ }
1502
+ return -1;
1503
+ }
1504
+ if (result) {
1505
+ *result = Py_NewRef(default_value);
1506
+ }
1507
+ return 0;
1508
+ }
1509
+ #endif
1510
+
1511
+ #if PY_VERSION_HEX < _Py_PACK_VERSION(3, 13)
1512
+ # define Py_BEGIN_CRITICAL_SECTION(op) {
1513
+ # define Py_END_CRITICAL_SECTION() }
1514
+ # define Py_BEGIN_CRITICAL_SECTION2(a, b) {
1515
+ # define Py_END_CRITICAL_SECTION2() }
1516
+ #endif
1517
+
1518
+ #if (PY_VERSION_HEX < _Py_PACK_VERSION(3, 14) \
1519
+ && !defined(PYPY_VERSION) && !defined(Py_LIMITED_API))
1520
+ typedef struct PyUnicodeWriter PyUnicodeWriter;
1521
+
1522
+ static inline void PyUnicodeWriter_Discard(PyUnicodeWriter *writer)
1523
+ {
1524
+ _PyUnicodeWriter_Dealloc((_PyUnicodeWriter*)writer);
1525
+ PyMem_Free(writer);
1526
+ }
1527
+
1528
+ static inline PyUnicodeWriter* PyUnicodeWriter_Create(Py_ssize_t length)
1529
+ {
1530
+ if (length < 0) {
1531
+ PyErr_SetString(PyExc_ValueError,
1532
+ "length must be positive");
1533
+ return NULL;
1534
+ }
1535
+
1536
+ const size_t size = sizeof(_PyUnicodeWriter);
1537
+ PyUnicodeWriter *pub_writer = (PyUnicodeWriter *)PyMem_Malloc(size);
1538
+ if (pub_writer == _Py_NULL) {
1539
+ PyErr_NoMemory();
1540
+ return _Py_NULL;
1541
+ }
1542
+ _PyUnicodeWriter *writer = (_PyUnicodeWriter *)pub_writer;
1543
+
1544
+ _PyUnicodeWriter_Init(writer);
1545
+ if (_PyUnicodeWriter_Prepare(writer, length, 127) < 0) {
1546
+ PyUnicodeWriter_Discard(pub_writer);
1547
+ return NULL;
1548
+ }
1549
+ writer->overallocate = 1;
1550
+ return pub_writer;
1551
+ }
1552
+
1553
+ static inline PyObject* PyUnicodeWriter_Finish(PyUnicodeWriter *writer)
1554
+ {
1555
+ PyObject *str = _PyUnicodeWriter_Finish((_PyUnicodeWriter*)writer);
1556
+ assert(((_PyUnicodeWriter*)writer)->buffer == NULL);
1557
+ PyMem_Free(writer);
1558
+ return str;
1559
+ }
1560
+
1561
+ static inline int
1562
+ PyUnicodeWriter_WriteChar(PyUnicodeWriter *writer, Py_UCS4 ch)
1563
+ {
1564
+ if (ch > 0x10ffff) {
1565
+ PyErr_SetString(PyExc_ValueError,
1566
+ "character must be in range(0x110000)");
1567
+ return -1;
1568
+ }
1569
+
1570
+ return _PyUnicodeWriter_WriteChar((_PyUnicodeWriter*)writer, ch);
1571
+ }
1572
+
1573
+ static inline int
1574
+ PyUnicodeWriter_WriteStr(PyUnicodeWriter *writer, PyObject *obj)
1575
+ {
1576
+ PyObject *str = PyObject_Str(obj);
1577
+ if (str == NULL) {
1578
+ return -1;
1579
+ }
1580
+
1581
+ int res = _PyUnicodeWriter_WriteStr((_PyUnicodeWriter*)writer, str);
1582
+ Py_DECREF(str);
1583
+ return res;
1584
+ }
1585
+
1586
+ static inline int
1587
+ PyUnicodeWriter_WriteRepr(PyUnicodeWriter *writer, PyObject *obj)
1588
+ {
1589
+ if (obj == NULL) {
1590
+ return _PyUnicodeWriter_WriteASCIIString((_PyUnicodeWriter*)writer,
1591
+ "<NULL>", 6);
1592
+ }
1593
+
1594
+ PyObject *str = PyObject_Repr(obj);
1595
+ if (str == NULL) {
1596
+ return -1;
1597
+ }
1598
+
1599
+ int res = _PyUnicodeWriter_WriteStr((_PyUnicodeWriter*)writer, str);
1600
+ Py_DECREF(str);
1601
+ return res;
1602
+ }
1603
+
1604
+ static inline int
1605
+ PyUnicodeWriter_WriteUTF8(PyUnicodeWriter *writer,
1606
+ const char *str, Py_ssize_t size)
1607
+ {
1608
+ if (size < 0) {
1609
+ size = (Py_ssize_t)strlen(str);
1610
+ }
1611
+
1612
+ PyObject *str_obj = PyUnicode_FromStringAndSize(str, size);
1613
+ if (str_obj == _Py_NULL) {
1614
+ return -1;
1615
+ }
1616
+
1617
+ int res = _PyUnicodeWriter_WriteStr((_PyUnicodeWriter*)writer, str_obj);
1618
+ Py_DECREF(str_obj);
1619
+ return res;
1620
+ }
1621
+
1622
+ static inline int
1623
+ PyUnicodeWriter_WriteASCII(PyUnicodeWriter *writer,
1624
+ const char *str, Py_ssize_t size)
1625
+ {
1626
+ if (size < 0) {
1627
+ size = (Py_ssize_t)strlen(str);
1628
+ }
1629
+
1630
+ return _PyUnicodeWriter_WriteASCIIString((_PyUnicodeWriter*)writer,
1631
+ str, size);
1632
+ }
1633
+
1634
+ static inline int
1635
+ PyUnicodeWriter_WriteWideChar(PyUnicodeWriter *writer,
1636
+ const wchar_t *str, Py_ssize_t size)
1637
+ {
1638
+ if (size < 0) {
1639
+ size = (Py_ssize_t)wcslen(str);
1640
+ }
1641
+
1642
+ PyObject *str_obj = PyUnicode_FromWideChar(str, size);
1643
+ if (str_obj == _Py_NULL) {
1644
+ return -1;
1645
+ }
1646
+
1647
+ int res = _PyUnicodeWriter_WriteStr((_PyUnicodeWriter*)writer, str_obj);
1648
+ Py_DECREF(str_obj);
1649
+ return res;
1650
+ }
1651
+
1652
+ static inline int
1653
+ PyUnicodeWriter_WriteSubstring(PyUnicodeWriter *writer, PyObject *str,
1654
+ Py_ssize_t start, Py_ssize_t end)
1655
+ {
1656
+ if (!PyUnicode_Check(str)) {
1657
+ PYTHONCAPI_COMPAT_EXPECT_TYPE("expect str, not ", str);
1658
+ return -1;
1659
+ }
1660
+ if (start < 0 || start > end) {
1661
+ PyErr_Format(PyExc_ValueError, "invalid start argument");
1662
+ return -1;
1663
+ }
1664
+ if (end > PyUnicode_GET_LENGTH(str)) {
1665
+ PyErr_Format(PyExc_ValueError, "invalid end argument");
1666
+ return -1;
1667
+ }
1668
+
1669
+ return _PyUnicodeWriter_WriteSubstring((_PyUnicodeWriter*)writer, str,
1670
+ start, end);
1671
+ }
1672
+
1673
+ static inline int
1674
+ PyUnicodeWriter_WriteUCS4(PyUnicodeWriter *writer,
1675
+ const Py_UCS4 *ucs4, Py_ssize_t size)
1676
+ {
1677
+ PyObject *str = PyUnicode_FromKindAndData(PyUnicode_4BYTE_KIND,
1678
+ ucs4, size);
1679
+ if (str == NULL) {
1680
+ return -1;
1681
+ }
1682
+
1683
+ int res = _PyUnicodeWriter_WriteStr((_PyUnicodeWriter*)writer, str);
1684
+ Py_DECREF(str);
1685
+ return res;
1686
+ }
1687
+
1688
+ static inline int
1689
+ PyUnicodeWriter_Format(PyUnicodeWriter *writer, const char *format, ...)
1690
+ {
1691
+ va_list vargs;
1692
+ va_start(vargs, format);
1693
+ PyObject *str = PyUnicode_FromFormatV(format, vargs);
1694
+ va_end(vargs);
1695
+ if (str == _Py_NULL) {
1696
+ return -1;
1697
+ }
1698
+
1699
+ int res = _PyUnicodeWriter_WriteStr((_PyUnicodeWriter*)writer, str);
1700
+ Py_DECREF(str);
1701
+ return res;
1702
+ }
1703
+ #endif // PY_VERSION_HEX < _Py_PACK_VERSION(3, 14)
1704
+
1705
+ // gh-116560 added PyLong_GetSign() to Python 3.14
1706
+ #if PY_VERSION_HEX < _Py_PACK_VERSION(3, 14) || defined(Py_LIMITED_API)
1707
+ static inline int PyLong_GetSign(PyObject *obj, int *sign)
1708
+ {
1709
+ #ifndef Py_LIMITED_API
1710
+ if (!PyLong_Check(obj)) {
1711
+ PYTHONCAPI_COMPAT_EXPECT_TYPE("expect int, got ", obj);
1712
+ return -1;
1713
+ }
1714
+
1715
+ *sign = _PyLong_Sign(obj);
1716
+ return 0;
1717
+ #else
1718
+ PyObject *zero = Py_GetConstant(Py_CONSTANT_ZERO);
1719
+ int cmp;
1720
+
1721
+ if (!PyLong_Check(obj)) {
1722
+ PYTHONCAPI_COMPAT_EXPECT_TYPE("expect int, got ", obj);
1723
+ return -1;
1724
+ }
1725
+
1726
+ cmp = PyObject_RichCompareBool(obj, zero, Py_GT);
1727
+ if (cmp > 0) {
1728
+ *sign = 1;
1729
+ return 0;
1730
+ }
1731
+ if (cmp < 0) {
1732
+ return -1;
1733
+ }
1734
+
1735
+ cmp = PyObject_RichCompareBool(obj, zero, Py_LT);
1736
+ if (cmp > 0) {
1737
+ *sign = -1;
1738
+ return 0;
1739
+ }
1740
+ if (cmp < 0) {
1741
+ return -1;
1742
+ }
1743
+ *sign = 0;
1744
+ return 0;
1745
+ #endif
1746
+ }
1747
+ #endif
1748
+
1749
+ // gh-126061 added PyLong_IsPositive/Negative/Zero() to Python in 3.14.0
1750
+ #if PY_VERSION_HEX < _Py_PACK_VERSION(3, 14) || defined(Py_LIMITED_API)
1751
+ static inline int PyLong_IsPositive(PyObject *obj)
1752
+ {
1753
+ #ifndef Py_LIMITED_API
1754
+ if (!PyLong_Check(obj)) {
1755
+ PYTHONCAPI_COMPAT_EXPECT_TYPE("expected int, got ", obj);
1756
+ return -1;
1757
+ }
1758
+ return _PyLong_Sign(obj) == 1;
1759
+ #else
1760
+ PyObject *zero = Py_GetConstant(Py_CONSTANT_ZERO);
1761
+
1762
+ if (!PyLong_Check(obj)) {
1763
+ PyErr_Format(PyExc_TypeError, "expect int, got %R", obj);
1764
+ return -1;
1765
+ }
1766
+
1767
+ return PyObject_RichCompareBool(obj, zero, Py_GT);
1768
+ #endif
1769
+ }
1770
+
1771
+ static inline int PyLong_IsNegative(PyObject *obj)
1772
+ {
1773
+ #ifndef Py_LIMITED_API
1774
+ if (!PyLong_Check(obj)) {
1775
+ PYTHONCAPI_COMPAT_EXPECT_TYPE("expected int, got ", obj);
1776
+ return -1;
1777
+ }
1778
+ return _PyLong_Sign(obj) == -1;
1779
+ #else
1780
+ PyObject *zero = Py_GetConstant(Py_CONSTANT_ZERO);
1781
+ int cmp;
1782
+
1783
+ if (!PyLong_Check(obj)) {
1784
+ PYTHONCAPI_COMPAT_EXPECT_TYPE("expect int, got ", obj);
1785
+ return -1;
1786
+ }
1787
+
1788
+ cmp = PyObject_RichCompareBool(obj, zero, Py_LT);
1789
+ if (cmp > 0) {
1790
+ return 1;
1791
+ }
1792
+ if (cmp < 0) {
1793
+ return -1;
1794
+ }
1795
+ return 0;
1796
+ #endif
1797
+ }
1798
+
1799
+ static inline int PyLong_IsZero(PyObject *obj)
1800
+ {
1801
+ #ifndef Py_LIMITED_API
1802
+ if (!PyLong_Check(obj)) {
1803
+ PYTHONCAPI_COMPAT_EXPECT_TYPE("expected int, got ", obj);
1804
+ return -1;
1805
+ }
1806
+ return _PyLong_Sign(obj) == 0;
1807
+ #else
1808
+ PyObject *zero = Py_GetConstant(Py_CONSTANT_ZERO);
1809
+
1810
+ if (!PyLong_Check(obj)) {
1811
+ PYTHONCAPI_COMPAT_EXPECT_TYPE("expect int, got ", obj);
1812
+ return -1;
1813
+ }
1814
+
1815
+ return PyObject_RichCompareBool(obj, zero, Py_EQ);
1816
+ #endif
1817
+ }
1818
+ #endif
1819
+
1820
+
1821
+ // gh-124502 added PyUnicode_Equal() to Python 3.14
1822
+ #if (PY_VERSION_HEX < _Py_PACK_VERSION(3, 14) \
1823
+ || (defined(Py_LIMITED_API) && Py_LIMITED_API+0 < _Py_PACK_VERSION(3, 14)))
1824
+
1825
+ #if (PY_VERSION_HEX >= _Py_PACK_VERSION(3, 13) \
1826
+ && !defined(PYPY_VERSION) && !defined(Py_LIMITED_API))
1827
+ PyAPI_FUNC(int) _PyUnicode_Equal(PyObject *str1, PyObject *str2);
1828
+ #endif
1829
+
1830
+ static inline int PyUnicode_Equal(PyObject *str1, PyObject *str2)
1831
+ {
1832
+ if (!PyUnicode_Check(str1)) {
1833
+ PYTHONCAPI_COMPAT_EXPECT_TYPE("first argument must be str, not ", str1);
1834
+ return -1;
1835
+ }
1836
+ if (!PyUnicode_Check(str2)) {
1837
+ PYTHONCAPI_COMPAT_EXPECT_TYPE("second argument must be str, not ", str2);
1838
+ return -1;
1839
+ }
1840
+
1841
+ #if (PY_VERSION_HEX >= _Py_PACK_VERSION(3, 13) \
1842
+ && !defined(PYPY_VERSION) && !defined(Py_LIMITED_API))
1843
+ return _PyUnicode_Equal(str1, str2);
1844
+ #elif !defined(PYPY_VERSION) && !defined(Py_LIMITED_API)
1845
+ return _PyUnicode_EQ(str1, str2);
1846
+ #elif (PY_VERSION_HEX >= _Py_PACK_VERSION(3, 9) \
1847
+ && defined(PYPY_VERSION) && !defined(Py_LIMITED_API))
1848
+ return _PyUnicode_EQ(str1, str2);
1849
+ #else
1850
+ {
1851
+ int cmp = PyUnicode_Compare(str1, str2);
1852
+ if (cmp == -1 && PyErr_Occurred()) {
1853
+ return -1;
1854
+ }
1855
+ return (cmp == 0);
1856
+ }
1857
+ #endif
1858
+ }
1859
+ #endif
1860
+
1861
+
1862
+ // gh-121645 added PyBytes_Join() to Python 3.14
1863
+ #if PY_VERSION_HEX < _Py_PACK_VERSION(3, 14) || defined(Py_LIMITED_API)
1864
+ static inline PyObject* PyBytes_Join(PyObject *sep, PyObject *iterable)
1865
+ {
1866
+ #ifndef Py_LIMITED_API
1867
+ return _PyBytes_Join(sep, iterable);
1868
+ #else
1869
+ if (sep == NULL) {
1870
+ PyErr_BadInternalCall();
1871
+ return NULL;
1872
+ }
1873
+ if (!PyBytes_Check(sep)) {
1874
+ PyErr_Format(PyExc_TypeError,
1875
+ "sep: expected bytes, got %T", sep);
1876
+ return NULL;
1877
+ }
1878
+
1879
+ return PyObject_CallMethod(sep, "join", "O", iterable);
1880
+ #endif
1881
+ }
1882
+ #endif
1883
+
1884
+
1885
+ #if (PY_VERSION_HEX < _Py_PACK_VERSION(3, 14) \
1886
+ || (defined(Py_LIMITED_API) && Py_LIMITED_API+0 < _Py_PACK_VERSION(3, 16)))
1887
+
1888
+ #if !defined(PYPY_VERSION) && !defined(Py_LIMITED_API)
1889
+ PyAPI_FUNC(Py_hash_t) _Py_HashBytes(const void *src, Py_ssize_t len);
1890
+ #endif
1891
+
1892
+ static inline Py_hash_t Py_HashBuffer(const void *ptr, Py_ssize_t len)
1893
+ {
1894
+ #if !defined(PYPY_VERSION) && !defined(Py_LIMITED_API)
1895
+ return _Py_HashBytes(ptr, len);
1896
+ #else
1897
+ Py_hash_t hash;
1898
+ PyObject *bytes = PyBytes_FromStringAndSize((const char*)ptr, len);
1899
+ if (bytes == NULL) {
1900
+ return -1;
1901
+ }
1902
+ hash = PyObject_Hash(bytes);
1903
+ Py_DECREF(bytes);
1904
+ return hash;
1905
+ #endif
1906
+ }
1907
+ #endif
1908
+
1909
+
1910
+ #if (PY_VERSION_HEX < _Py_PACK_VERSION(3, 14) \
1911
+ || (defined(Py_LIMITED_API) && Py_LIMITED_API+0 < _Py_PACK_VERSION(3, 14)))
1912
+ static inline int PyIter_NextItem(PyObject *iter, PyObject **item)
1913
+ {
1914
+ // Limited API: PyType_GetSlot() only accepts all types since Python 3.10
1915
+ #if !defined(Py_LIMITED_API) || Py_LIMITED_API+0 >= _Py_PACK_VERSION(3, 10)
1916
+ iternextfunc tp_iternext;
1917
+
1918
+ assert(iter != NULL);
1919
+ assert(item != NULL);
1920
+
1921
+ #ifndef Py_LIMITED_API
1922
+ tp_iternext = Py_TYPE(iter)->tp_iternext;
1923
+ #else
1924
+ tp_iternext = _Py_CAST(iternextfunc, PyType_GetSlot(Py_TYPE(iter), Py_tp_iternext));
1925
+ #endif
1926
+ if (tp_iternext == NULL) {
1927
+ *item = NULL;
1928
+ PYTHONCAPI_COMPAT_EXPECT_TYPE("expected an iterator, got ", iter);
1929
+ return -1;
1930
+ }
1931
+
1932
+ if ((*item = tp_iternext(iter))) {
1933
+ return 1;
1934
+ }
1935
+ if (!PyErr_Occurred()) {
1936
+ return 0;
1937
+ }
1938
+ if (PyErr_ExceptionMatches(PyExc_StopIteration)) {
1939
+ PyErr_Clear();
1940
+ return 0;
1941
+ }
1942
+ return -1;
1943
+ #else
1944
+ // Implementation for limited C API 3.9 and older
1945
+
1946
+ assert(iter != NULL);
1947
+ assert(item != NULL);
1948
+
1949
+ // Cannot check if iter is an iterator: PyIter_Check() is only implemented
1950
+ // as a function since Python 3.8.
1951
+
1952
+ *item = PyIter_Next(iter);
1953
+ if (*item != NULL) {
1954
+ return 1;
1955
+ }
1956
+ else if (!PyErr_Occurred()) {
1957
+ return 0;
1958
+ }
1959
+ else {
1960
+ return -1;
1961
+ }
1962
+ #endif
1963
+ }
1964
+ #endif
1965
+
1966
+
1967
+ #if (PY_VERSION_HEX < _Py_PACK_VERSION(3, 14) \
1968
+ || (defined(Py_LIMITED_API) && Py_LIMITED_API+0 < _Py_PACK_VERSION(3, 14)))
1969
+ static inline PyObject* PyLong_FromInt32(int32_t value)
1970
+ {
1971
+ Py_BUILD_ASSERT(sizeof(long) >= 4);
1972
+ return PyLong_FromLong(value);
1973
+ }
1974
+
1975
+ static inline PyObject* PyLong_FromInt64(int64_t value)
1976
+ {
1977
+ Py_BUILD_ASSERT(sizeof(long long) >= 8);
1978
+ return PyLong_FromLongLong(value);
1979
+ }
1980
+
1981
+ static inline PyObject* PyLong_FromUInt32(uint32_t value)
1982
+ {
1983
+ Py_BUILD_ASSERT(sizeof(unsigned long) >= 4);
1984
+ return PyLong_FromUnsignedLong(value);
1985
+ }
1986
+
1987
+ static inline PyObject* PyLong_FromUInt64(uint64_t value)
1988
+ {
1989
+ Py_BUILD_ASSERT(sizeof(unsigned long long) >= 8);
1990
+ return PyLong_FromUnsignedLongLong(value);
1991
+ }
1992
+
1993
+ static inline int PyLong_AsInt32(PyObject *obj, int32_t *pvalue)
1994
+ {
1995
+ Py_BUILD_ASSERT(sizeof(int) == 4);
1996
+ int value = PyLong_AsInt(obj);
1997
+ if (value == -1 && PyErr_Occurred()) {
1998
+ return -1;
1999
+ }
2000
+ *pvalue = (int32_t)value;
2001
+ return 0;
2002
+ }
2003
+
2004
+ static inline int PyLong_AsInt64(PyObject *obj, int64_t *pvalue)
2005
+ {
2006
+ Py_BUILD_ASSERT(sizeof(long long) == 8);
2007
+ long long value = PyLong_AsLongLong(obj);
2008
+ if (value == -1 && PyErr_Occurred()) {
2009
+ return -1;
2010
+ }
2011
+ *pvalue = (int64_t)value;
2012
+ return 0;
2013
+ }
2014
+
2015
+ static inline int PyLong_AsUInt32(PyObject *obj, uint32_t *pvalue)
2016
+ {
2017
+ Py_BUILD_ASSERT(sizeof(long) >= 4);
2018
+ unsigned long value = PyLong_AsUnsignedLong(obj);
2019
+ if (value == (unsigned long)-1 && PyErr_Occurred()) {
2020
+ return -1;
2021
+ }
2022
+ #if SIZEOF_LONG > 4
2023
+ if ((unsigned long)UINT32_MAX < value) {
2024
+ PyErr_SetString(PyExc_OverflowError,
2025
+ "Python int too large to convert to C uint32_t");
2026
+ return -1;
2027
+ }
2028
+ #endif
2029
+ *pvalue = (uint32_t)value;
2030
+ return 0;
2031
+ }
2032
+
2033
+ static inline int PyLong_AsUInt64(PyObject *obj, uint64_t *pvalue)
2034
+ {
2035
+ Py_BUILD_ASSERT(sizeof(long long) == 8);
2036
+ unsigned long long value = PyLong_AsUnsignedLongLong(obj);
2037
+ if (value == (unsigned long long)-1 && PyErr_Occurred()) {
2038
+ return -1;
2039
+ }
2040
+ *pvalue = (uint64_t)value;
2041
+ return 0;
2042
+ }
2043
+ #endif
2044
+
2045
+
2046
+ // gh-102471 added import and export API for integers to 3.14.0.
2047
+ #if (PY_VERSION_HEX < _Py_PACK_VERSION(3, 14) \
2048
+ && !defined(PYPY_VERSION) && !defined(Py_LIMITED_API))
2049
+ // Helpers to access PyLongObject internals.
2050
+ static inline void
2051
+ _PyLong_SetSignAndDigitCount(PyLongObject *op, int sign, Py_ssize_t size)
2052
+ {
2053
+ #if PY_VERSION_HEX >= _Py_PACK_VERSION(3, 12)
2054
+ op->long_value.lv_tag = (uintptr_t)(1 - sign) | ((uintptr_t)(size) << 3);
2055
+ #elif PY_VERSION_HEX >= _Py_PACK_VERSION(3, 9)
2056
+ Py_SET_SIZE(op, sign * size);
2057
+ #else
2058
+ Py_SIZE(op) = sign * size;
2059
+ #endif
2060
+ }
2061
+
2062
+ static inline Py_ssize_t
2063
+ _PyLong_DigitCount(const PyLongObject *op)
2064
+ {
2065
+ #if PY_VERSION_HEX >= _Py_PACK_VERSION(3, 12)
2066
+ return (Py_ssize_t)(op->long_value.lv_tag >> 3);
2067
+ #else
2068
+ return _PyLong_Sign((PyObject*)op) < 0 ? -Py_SIZE(op) : Py_SIZE(op);
2069
+ #endif
2070
+ }
2071
+
2072
+ static inline digit*
2073
+ _PyLong_GetDigits(const PyLongObject *op)
2074
+ {
2075
+ #if PY_VERSION_HEX >= _Py_PACK_VERSION(3, 12)
2076
+ return (digit*)(op->long_value.ob_digit);
2077
+ #else
2078
+ return (digit*)(op->ob_digit);
2079
+ #endif
2080
+ }
2081
+
2082
+ typedef struct PyLongLayout {
2083
+ uint8_t bits_per_digit;
2084
+ uint8_t digit_size;
2085
+ int8_t digits_order;
2086
+ int8_t digit_endianness;
2087
+ } PyLongLayout;
2088
+
2089
+ typedef struct PyLongExport {
2090
+ int64_t value;
2091
+ uint8_t negative;
2092
+ Py_ssize_t ndigits;
2093
+ const void *digits;
2094
+ Py_uintptr_t _reserved;
2095
+ } PyLongExport;
2096
+
2097
+ typedef struct PyLongWriter PyLongWriter;
2098
+
2099
+ static inline const PyLongLayout*
2100
+ PyLong_GetNativeLayout(void)
2101
+ {
2102
+ static const PyLongLayout PyLong_LAYOUT = {
2103
+ PyLong_SHIFT,
2104
+ sizeof(digit),
2105
+ -1, // least significant first
2106
+ PY_LITTLE_ENDIAN ? -1 : 1,
2107
+ };
2108
+
2109
+ return &PyLong_LAYOUT;
2110
+ }
2111
+
2112
+ static inline int
2113
+ PyLong_Export(PyObject *obj, PyLongExport *export_long)
2114
+ {
2115
+ if (!PyLong_Check(obj)) {
2116
+ memset(export_long, 0, sizeof(*export_long));
2117
+ PYTHONCAPI_COMPAT_EXPECT_TYPE("expected int, got ", obj);
2118
+ return -1;
2119
+ }
2120
+
2121
+ // Fast-path: try to convert to a int64_t
2122
+ PyLongObject *self = (PyLongObject*)obj;
2123
+ int overflow;
2124
+ #if SIZEOF_LONG == 8
2125
+ long value = PyLong_AsLongAndOverflow(obj, &overflow);
2126
+ #else
2127
+ // Windows has 32-bit long, so use 64-bit long long instead
2128
+ long long value = PyLong_AsLongLongAndOverflow(obj, &overflow);
2129
+ #endif
2130
+ Py_BUILD_ASSERT(sizeof(value) == sizeof(int64_t));
2131
+ // the function cannot fail since obj is a PyLongObject
2132
+ assert(!(value == -1 && PyErr_Occurred()));
2133
+
2134
+ if (!overflow) {
2135
+ export_long->value = value;
2136
+ export_long->negative = 0;
2137
+ export_long->ndigits = 0;
2138
+ export_long->digits = 0;
2139
+ export_long->_reserved = 0;
2140
+ }
2141
+ else {
2142
+ export_long->value = 0;
2143
+ export_long->negative = _PyLong_Sign(obj) < 0;
2144
+ export_long->ndigits = _PyLong_DigitCount(self);
2145
+ if (export_long->ndigits == 0) {
2146
+ export_long->ndigits = 1;
2147
+ }
2148
+ export_long->digits = _PyLong_GetDigits(self);
2149
+ export_long->_reserved = (Py_uintptr_t)Py_NewRef(obj);
2150
+ }
2151
+ return 0;
2152
+ }
2153
+
2154
+ static inline void
2155
+ PyLong_FreeExport(PyLongExport *export_long)
2156
+ {
2157
+ PyObject *obj = (PyObject*)export_long->_reserved;
2158
+
2159
+ if (obj) {
2160
+ export_long->_reserved = 0;
2161
+ Py_DECREF(obj);
2162
+ }
2163
+ }
2164
+
2165
+ static inline PyLongWriter*
2166
+ PyLongWriter_Create(int negative, Py_ssize_t ndigits, void **digits)
2167
+ {
2168
+ if (ndigits <= 0) {
2169
+ PyErr_SetString(PyExc_ValueError, "ndigits must be positive");
2170
+ return NULL;
2171
+ }
2172
+ assert(digits != NULL);
2173
+
2174
+ PyLongObject *obj = _PyLong_New(ndigits);
2175
+ if (obj == NULL) {
2176
+ return NULL;
2177
+ }
2178
+ _PyLong_SetSignAndDigitCount(obj, negative?-1:1, ndigits);
2179
+
2180
+ *digits = _PyLong_GetDigits(obj);
2181
+ return (PyLongWriter*)obj;
2182
+ }
2183
+
2184
+ static inline void
2185
+ PyLongWriter_Discard(PyLongWriter *writer)
2186
+ {
2187
+ PyLongObject *obj = (PyLongObject *)writer;
2188
+
2189
+ assert(Py_REFCNT(obj) == 1);
2190
+ Py_DECREF(obj);
2191
+ }
2192
+
2193
+ static inline PyObject*
2194
+ PyLongWriter_Finish(PyLongWriter *writer)
2195
+ {
2196
+ PyObject *obj = (PyObject *)writer;
2197
+ PyLongObject *self = (PyLongObject*)obj;
2198
+ Py_ssize_t j = _PyLong_DigitCount(self);
2199
+ Py_ssize_t i = j;
2200
+ int sign = _PyLong_Sign(obj);
2201
+
2202
+ assert(Py_REFCNT(obj) == 1);
2203
+
2204
+ // Normalize and get singleton if possible
2205
+ while (i > 0 && _PyLong_GetDigits(self)[i-1] == 0) {
2206
+ --i;
2207
+ }
2208
+ if (i != j) {
2209
+ if (i == 0) {
2210
+ sign = 0;
2211
+ }
2212
+ _PyLong_SetSignAndDigitCount(self, sign, i);
2213
+ }
2214
+ if (i <= 1) {
2215
+ long val = sign * (long)(_PyLong_GetDigits(self)[0]);
2216
+ Py_DECREF(obj);
2217
+ return PyLong_FromLong(val);
2218
+ }
2219
+
2220
+ return obj;
2221
+ }
2222
+ #endif
2223
+
2224
+
2225
+ #if PY_VERSION_HEX < _Py_PACK_VERSION(3, 12)
2226
+ # define Py_T_SHORT 0
2227
+ # define Py_T_INT 1
2228
+ # define Py_T_LONG 2
2229
+ # define Py_T_FLOAT 3
2230
+ # define Py_T_DOUBLE 4
2231
+ # define Py_T_STRING 5
2232
+ # define _Py_T_OBJECT 6
2233
+ # define Py_T_CHAR 7
2234
+ # define Py_T_BYTE 8
2235
+ # define Py_T_UBYTE 9
2236
+ # define Py_T_USHORT 10
2237
+ # define Py_T_UINT 11
2238
+ # define Py_T_ULONG 12
2239
+ # define Py_T_STRING_INPLACE 13
2240
+ # define Py_T_BOOL 14
2241
+ # define Py_T_OBJECT_EX 16
2242
+ # define Py_T_LONGLONG 17
2243
+ # define Py_T_ULONGLONG 18
2244
+ # define Py_T_PYSSIZET 19
2245
+
2246
+ # ifndef PYPY_VERSION
2247
+ # define _Py_T_NONE 20
2248
+ # endif
2249
+
2250
+ # define Py_READONLY 1
2251
+ # define Py_AUDIT_READ 2
2252
+ # define _Py_WRITE_RESTRICTED 4
2253
+ #endif
2254
+
2255
+
2256
+ // gh-127350 added Py_fopen() and Py_fclose() to Python 3.14a4
2257
+ #if PY_VERSION_HEX < _Py_PACK_VERSION(3, 14) || defined(Py_LIMITED_API)
2258
+
2259
+ #if !defined(PYPY_VERSION) && !defined(Py_LIMITED_API)
2260
+ PyAPI_FUNC(FILE*) _Py_fopen_obj(PyObject *path, const char *mode);
2261
+ #endif
2262
+
2263
+ static inline FILE* Py_fopen(PyObject *path, const char *mode)
2264
+ {
2265
+ #if !defined(PYPY_VERSION) && !defined(Py_LIMITED_API)
2266
+ return _Py_fopen_obj(path, mode);
2267
+ #else
2268
+ FILE *f;
2269
+ PyObject *bytes;
2270
+ const char *path_bytes;
2271
+ if (!PyUnicode_FSConverter(path, &bytes)) {
2272
+ return NULL;
2273
+ }
2274
+ #ifndef Py_LIMITED_API
2275
+ path_bytes = PyBytes_AS_STRING(bytes);
2276
+ #else
2277
+ path_bytes = PyBytes_AsString(bytes);
2278
+ #endif
2279
+
2280
+ f = fopen(path_bytes, mode);
2281
+ Py_DECREF(bytes);
2282
+
2283
+ if (f == NULL) {
2284
+ PyErr_SetFromErrnoWithFilenameObject(PyExc_OSError, path);
2285
+ return NULL;
2286
+ }
2287
+ return f;
2288
+ #endif
2289
+ }
2290
+
2291
+ static inline int Py_fclose(FILE *file)
2292
+ {
2293
+ return fclose(file);
2294
+ }
2295
+ #endif
2296
+
2297
+
2298
+ #if (_Py_PACK_VERSION(3, 9) <= PY_VERSION_HEX \
2299
+ && PY_VERSION_HEX < _Py_PACK_VERSION(3, 14) \
2300
+ && !defined(PYPY_VERSION) && !defined(Py_LIMITED_API))
2301
+
2302
+ // Use the internal C API added to Python 3.9
2303
+ PyAPI_FUNC(const PyConfig*) _Py_GetConfig(void);
2304
+
2305
+ static inline PyObject*
2306
+ PyConfig_Get(const char *name)
2307
+ {
2308
+ typedef enum {
2309
+ _PyConfig_MEMBER_INT,
2310
+ _PyConfig_MEMBER_UINT,
2311
+ _PyConfig_MEMBER_ULONG,
2312
+ _PyConfig_MEMBER_BOOL,
2313
+ _PyConfig_MEMBER_WSTR,
2314
+ _PyConfig_MEMBER_WSTR_OPT,
2315
+ _PyConfig_MEMBER_WSTR_LIST,
2316
+ } PyConfigMemberType;
2317
+
2318
+ typedef struct {
2319
+ const char *name;
2320
+ size_t offset;
2321
+ PyConfigMemberType type;
2322
+ const char *sys_attr;
2323
+ } PyConfigSpec;
2324
+
2325
+ #define PYTHONCAPI_COMPAT_SPEC(MEMBER, TYPE, sys_attr) \
2326
+ {#MEMBER, offsetof(PyConfig, MEMBER), \
2327
+ _PyConfig_MEMBER_##TYPE, sys_attr}
2328
+
2329
+ static const PyConfigSpec config_spec[] = {
2330
+ PYTHONCAPI_COMPAT_SPEC(argv, WSTR_LIST, "argv"),
2331
+ PYTHONCAPI_COMPAT_SPEC(base_exec_prefix, WSTR_OPT, "base_exec_prefix"),
2332
+ PYTHONCAPI_COMPAT_SPEC(base_executable, WSTR_OPT, "_base_executable"),
2333
+ PYTHONCAPI_COMPAT_SPEC(base_prefix, WSTR_OPT, "base_prefix"),
2334
+ PYTHONCAPI_COMPAT_SPEC(bytes_warning, UINT, _Py_NULL),
2335
+ PYTHONCAPI_COMPAT_SPEC(exec_prefix, WSTR_OPT, "exec_prefix"),
2336
+ PYTHONCAPI_COMPAT_SPEC(executable, WSTR_OPT, "executable"),
2337
+ PYTHONCAPI_COMPAT_SPEC(inspect, BOOL, _Py_NULL),
2338
+ #if _Py_PACK_VERSION(3, 12) <= PY_VERSION_HEX
2339
+ PYTHONCAPI_COMPAT_SPEC(int_max_str_digits, UINT, _Py_NULL),
2340
+ #endif
2341
+ PYTHONCAPI_COMPAT_SPEC(interactive, BOOL, _Py_NULL),
2342
+ PYTHONCAPI_COMPAT_SPEC(module_search_paths, WSTR_LIST, "path"),
2343
+ PYTHONCAPI_COMPAT_SPEC(optimization_level, UINT, _Py_NULL),
2344
+ PYTHONCAPI_COMPAT_SPEC(parser_debug, BOOL, _Py_NULL),
2345
+ #if _Py_PACK_VERSION(3, 9) <= PY_VERSION_HEX
2346
+ PYTHONCAPI_COMPAT_SPEC(platlibdir, WSTR, "platlibdir"),
2347
+ #endif
2348
+ PYTHONCAPI_COMPAT_SPEC(prefix, WSTR_OPT, "prefix"),
2349
+ PYTHONCAPI_COMPAT_SPEC(pycache_prefix, WSTR_OPT, "pycache_prefix"),
2350
+ PYTHONCAPI_COMPAT_SPEC(quiet, BOOL, _Py_NULL),
2351
+ #if _Py_PACK_VERSION(3, 11) <= PY_VERSION_HEX
2352
+ PYTHONCAPI_COMPAT_SPEC(stdlib_dir, WSTR_OPT, "_stdlib_dir"),
2353
+ #endif
2354
+ PYTHONCAPI_COMPAT_SPEC(use_environment, BOOL, _Py_NULL),
2355
+ PYTHONCAPI_COMPAT_SPEC(verbose, UINT, _Py_NULL),
2356
+ PYTHONCAPI_COMPAT_SPEC(warnoptions, WSTR_LIST, "warnoptions"),
2357
+ PYTHONCAPI_COMPAT_SPEC(write_bytecode, BOOL, _Py_NULL),
2358
+ PYTHONCAPI_COMPAT_SPEC(xoptions, WSTR_LIST, "_xoptions"),
2359
+ PYTHONCAPI_COMPAT_SPEC(buffered_stdio, BOOL, _Py_NULL),
2360
+ PYTHONCAPI_COMPAT_SPEC(check_hash_pycs_mode, WSTR, _Py_NULL),
2361
+ #if _Py_PACK_VERSION(3, 11) <= PY_VERSION_HEX
2362
+ PYTHONCAPI_COMPAT_SPEC(code_debug_ranges, BOOL, _Py_NULL),
2363
+ #endif
2364
+ PYTHONCAPI_COMPAT_SPEC(configure_c_stdio, BOOL, _Py_NULL),
2365
+ #if _Py_PACK_VERSION(3, 13) <= PY_VERSION_HEX
2366
+ PYTHONCAPI_COMPAT_SPEC(cpu_count, INT, _Py_NULL),
2367
+ #endif
2368
+ PYTHONCAPI_COMPAT_SPEC(dev_mode, BOOL, _Py_NULL),
2369
+ PYTHONCAPI_COMPAT_SPEC(dump_refs, BOOL, _Py_NULL),
2370
+ #if _Py_PACK_VERSION(3, 11) <= PY_VERSION_HEX
2371
+ PYTHONCAPI_COMPAT_SPEC(dump_refs_file, WSTR_OPT, _Py_NULL),
2372
+ #endif
2373
+ #ifdef Py_GIL_DISABLED
2374
+ PYTHONCAPI_COMPAT_SPEC(enable_gil, INT, _Py_NULL),
2375
+ #endif
2376
+ PYTHONCAPI_COMPAT_SPEC(faulthandler, BOOL, _Py_NULL),
2377
+ PYTHONCAPI_COMPAT_SPEC(filesystem_encoding, WSTR, _Py_NULL),
2378
+ PYTHONCAPI_COMPAT_SPEC(filesystem_errors, WSTR, _Py_NULL),
2379
+ PYTHONCAPI_COMPAT_SPEC(hash_seed, ULONG, _Py_NULL),
2380
+ PYTHONCAPI_COMPAT_SPEC(home, WSTR_OPT, _Py_NULL),
2381
+ PYTHONCAPI_COMPAT_SPEC(import_time, BOOL, _Py_NULL),
2382
+ PYTHONCAPI_COMPAT_SPEC(install_signal_handlers, BOOL, _Py_NULL),
2383
+ PYTHONCAPI_COMPAT_SPEC(isolated, BOOL, _Py_NULL),
2384
+ #ifdef MS_WINDOWS
2385
+ PYTHONCAPI_COMPAT_SPEC(legacy_windows_stdio, BOOL, _Py_NULL),
2386
+ #endif
2387
+ PYTHONCAPI_COMPAT_SPEC(malloc_stats, BOOL, _Py_NULL),
2388
+ #if _Py_PACK_VERSION(3, 10) <= PY_VERSION_HEX
2389
+ PYTHONCAPI_COMPAT_SPEC(orig_argv, WSTR_LIST, "orig_argv"),
2390
+ #endif
2391
+ PYTHONCAPI_COMPAT_SPEC(parse_argv, BOOL, _Py_NULL),
2392
+ PYTHONCAPI_COMPAT_SPEC(pathconfig_warnings, BOOL, _Py_NULL),
2393
+ #if _Py_PACK_VERSION(3, 12) <= PY_VERSION_HEX
2394
+ PYTHONCAPI_COMPAT_SPEC(perf_profiling, UINT, _Py_NULL),
2395
+ #endif
2396
+ PYTHONCAPI_COMPAT_SPEC(program_name, WSTR, _Py_NULL),
2397
+ PYTHONCAPI_COMPAT_SPEC(run_command, WSTR_OPT, _Py_NULL),
2398
+ PYTHONCAPI_COMPAT_SPEC(run_filename, WSTR_OPT, _Py_NULL),
2399
+ PYTHONCAPI_COMPAT_SPEC(run_module, WSTR_OPT, _Py_NULL),
2400
+ #if _Py_PACK_VERSION(3, 11) <= PY_VERSION_HEX
2401
+ PYTHONCAPI_COMPAT_SPEC(safe_path, BOOL, _Py_NULL),
2402
+ #endif
2403
+ PYTHONCAPI_COMPAT_SPEC(show_ref_count, BOOL, _Py_NULL),
2404
+ PYTHONCAPI_COMPAT_SPEC(site_import, BOOL, _Py_NULL),
2405
+ PYTHONCAPI_COMPAT_SPEC(skip_source_first_line, BOOL, _Py_NULL),
2406
+ PYTHONCAPI_COMPAT_SPEC(stdio_encoding, WSTR, _Py_NULL),
2407
+ PYTHONCAPI_COMPAT_SPEC(stdio_errors, WSTR, _Py_NULL),
2408
+ PYTHONCAPI_COMPAT_SPEC(tracemalloc, UINT, _Py_NULL),
2409
+ #if _Py_PACK_VERSION(3, 11) <= PY_VERSION_HEX
2410
+ PYTHONCAPI_COMPAT_SPEC(use_frozen_modules, BOOL, _Py_NULL),
2411
+ #endif
2412
+ PYTHONCAPI_COMPAT_SPEC(use_hash_seed, BOOL, _Py_NULL),
2413
+ PYTHONCAPI_COMPAT_SPEC(user_site_directory, BOOL, _Py_NULL),
2414
+ #if _Py_PACK_VERSION(3, 10) <= PY_VERSION_HEX
2415
+ PYTHONCAPI_COMPAT_SPEC(warn_default_encoding, BOOL, _Py_NULL),
2416
+ #endif
2417
+ };
2418
+
2419
+ #undef PYTHONCAPI_COMPAT_SPEC
2420
+
2421
+ const PyConfigSpec *spec;
2422
+ int found = 0;
2423
+ for (size_t i=0; i < sizeof(config_spec) / sizeof(config_spec[0]); i++) {
2424
+ spec = &config_spec[i];
2425
+ if (strcmp(spec->name, name) == 0) {
2426
+ found = 1;
2427
+ break;
2428
+ }
2429
+ }
2430
+ if (found) {
2431
+ if (spec->sys_attr != NULL) {
2432
+ PyObject *value = PySys_GetObject(spec->sys_attr);
2433
+ if (value == NULL) {
2434
+ PyErr_Format(PyExc_RuntimeError, "lost sys.%s", spec->sys_attr);
2435
+ return NULL;
2436
+ }
2437
+ return Py_NewRef(value);
2438
+ }
2439
+
2440
+ const PyConfig *config = _Py_GetConfig();
2441
+ void *member = (char *)config + spec->offset;
2442
+ switch (spec->type) {
2443
+ case _PyConfig_MEMBER_INT:
2444
+ case _PyConfig_MEMBER_UINT:
2445
+ {
2446
+ int value = *(int *)member;
2447
+ return PyLong_FromLong(value);
2448
+ }
2449
+ case _PyConfig_MEMBER_BOOL:
2450
+ {
2451
+ int value = *(int *)member;
2452
+ return PyBool_FromLong(value != 0);
2453
+ }
2454
+ case _PyConfig_MEMBER_ULONG:
2455
+ {
2456
+ unsigned long value = *(unsigned long *)member;
2457
+ return PyLong_FromUnsignedLong(value);
2458
+ }
2459
+ case _PyConfig_MEMBER_WSTR:
2460
+ case _PyConfig_MEMBER_WSTR_OPT:
2461
+ {
2462
+ wchar_t *wstr = *(wchar_t **)member;
2463
+ if (wstr != NULL) {
2464
+ return PyUnicode_FromWideChar(wstr, -1);
2465
+ }
2466
+ else {
2467
+ return Py_NewRef(Py_None);
2468
+ }
2469
+ }
2470
+ case _PyConfig_MEMBER_WSTR_LIST:
2471
+ {
2472
+ const PyWideStringList *list = (const PyWideStringList *)member;
2473
+ PyObject *tuple = PyTuple_New(list->length);
2474
+ if (tuple == NULL) {
2475
+ return NULL;
2476
+ }
2477
+
2478
+ for (Py_ssize_t i = 0; i < list->length; i++) {
2479
+ PyObject *item = PyUnicode_FromWideChar(list->items[i], -1);
2480
+ if (item == NULL) {
2481
+ Py_DECREF(tuple);
2482
+ return NULL;
2483
+ }
2484
+ PyTuple_SET_ITEM(tuple, i, item);
2485
+ }
2486
+ return tuple;
2487
+ }
2488
+ default:
2489
+ Py_UNREACHABLE();
2490
+ }
2491
+ }
2492
+
2493
+ PyErr_Format(PyExc_ValueError, "unknown config option name: %s", name);
2494
+ return NULL;
2495
+ }
2496
+
2497
+ static inline int
2498
+ PyConfig_GetInt(const char *name, int *value)
2499
+ {
2500
+ PyObject *obj = PyConfig_Get(name);
2501
+ if (obj == NULL) {
2502
+ return -1;
2503
+ }
2504
+
2505
+ if (!PyLong_Check(obj)) {
2506
+ Py_DECREF(obj);
2507
+ PyErr_Format(PyExc_TypeError, "config option %s is not an int", name);
2508
+ return -1;
2509
+ }
2510
+
2511
+ int as_int = PyLong_AsInt(obj);
2512
+ Py_DECREF(obj);
2513
+ if (as_int == -1 && PyErr_Occurred()) {
2514
+ PyErr_Format(PyExc_OverflowError,
2515
+ "config option %s value does not fit into a C int", name);
2516
+ return -1;
2517
+ }
2518
+
2519
+ *value = as_int;
2520
+ return 0;
2521
+ }
2522
+ #endif // PY_VERSION_HEX > _Py_PACK_VERSION(3, 9) && !defined(PYPY_VERSION)
2523
+
2524
+ // gh-133144 added PyUnstable_Object_IsUniquelyReferenced() to Python 3.14.
2525
+ // Adapted from _PyObject_IsUniquelyReferenced() implementation.
2526
+ // Not available on PyPy: Py_REFCNT() semantics is different on PyPy.
2527
+ #if (PY_VERSION_HEX < _Py_PACK_VERSION(3, 14) \
2528
+ && !defined(PYPY_VERSION) && !defined(Py_LIMITED_API))
2529
+ static inline int PyUnstable_Object_IsUniquelyReferenced(PyObject *obj)
2530
+ {
2531
+ #if !defined(Py_GIL_DISABLED)
2532
+ return Py_REFCNT(obj) == 1;
2533
+ #else
2534
+ // NOTE: the entire ob_ref_shared field must be zero, including flags, to
2535
+ // ensure that other threads cannot concurrently create new references to
2536
+ // this object.
2537
+ return (_Py_IsOwnedByCurrentThread(obj) &&
2538
+ _Py_atomic_load_uint32_relaxed(&obj->ob_ref_local) == 1 &&
2539
+ _Py_atomic_load_ssize_relaxed(&obj->ob_ref_shared) == 0);
2540
+ #endif
2541
+ }
2542
+ #endif
2543
+
2544
+ // gh-128926 added PyUnstable_TryIncRef() and PyUnstable_EnableTryIncRef() to
2545
+ // Python 3.14. Adapted from _Py_TryIncref() and _PyObject_SetMaybeWeakref().
2546
+ // Not available on PyPy: Py_REFCNT() semantics is different on PyPy.
2547
+ #if PY_VERSION_HEX < _Py_PACK_VERSION(3, 14) && !defined(PYPY_VERSION)
2548
+ static inline int PyUnstable_TryIncRef(PyObject *op)
2549
+ {
2550
+ #ifndef Py_GIL_DISABLED
2551
+ if (Py_REFCNT(op) > 0) {
2552
+ Py_INCREF(op);
2553
+ return 1;
2554
+ }
2555
+ return 0;
2556
+ #else
2557
+ // _Py_TryIncrefFast()
2558
+ uint32_t local = _Py_atomic_load_uint32_relaxed(&op->ob_ref_local);
2559
+ local += 1;
2560
+ if (local == 0) {
2561
+ // immortal
2562
+ return 1;
2563
+ }
2564
+ if (_Py_IsOwnedByCurrentThread(op)) {
2565
+ _Py_INCREF_STAT_INC();
2566
+ _Py_atomic_store_uint32_relaxed(&op->ob_ref_local, local);
2567
+ #ifdef Py_REF_DEBUG
2568
+ _Py_INCREF_IncRefTotal();
2569
+ #endif
2570
+ return 1;
2571
+ }
2572
+
2573
+ // _Py_TryIncRefShared()
2574
+ Py_ssize_t shared = _Py_atomic_load_ssize_relaxed(&op->ob_ref_shared);
2575
+ for (;;) {
2576
+ // If the shared refcount is zero and the object is either merged
2577
+ // or may not have weak references, then we cannot incref it.
2578
+ if (shared == 0 || shared == _Py_REF_MERGED) {
2579
+ return 0;
2580
+ }
2581
+
2582
+ if (_Py_atomic_compare_exchange_ssize(
2583
+ &op->ob_ref_shared,
2584
+ &shared,
2585
+ shared + (1 << _Py_REF_SHARED_SHIFT))) {
2586
+ #ifdef Py_REF_DEBUG
2587
+ _Py_INCREF_IncRefTotal();
2588
+ #endif
2589
+ _Py_INCREF_STAT_INC();
2590
+ return 1;
2591
+ }
2592
+ }
2593
+ #endif
2594
+ }
2595
+
2596
+ static inline void PyUnstable_EnableTryIncRef(PyObject *op)
2597
+ {
2598
+ #ifdef Py_GIL_DISABLED
2599
+ // _PyObject_SetMaybeWeakref()
2600
+ if (_Py_IsImmortal(op)) {
2601
+ return;
2602
+ }
2603
+ for (;;) {
2604
+ Py_ssize_t shared = _Py_atomic_load_ssize_relaxed(&op->ob_ref_shared);
2605
+ if ((shared & _Py_REF_SHARED_FLAG_MASK) != 0) {
2606
+ // Nothing to do if it's in WEAKREFS, QUEUED, or MERGED states.
2607
+ return;
2608
+ }
2609
+ if (_Py_atomic_compare_exchange_ssize(
2610
+ &op->ob_ref_shared, &shared, shared | _Py_REF_MAYBE_WEAKREF)) {
2611
+ return;
2612
+ }
2613
+ }
2614
+ #else
2615
+ (void)op; // unused argument
2616
+ #endif
2617
+ }
2618
+ #endif // PY_VERSION_HEX < _Py_PACK_VERSION(3, 14) && !defined(PYPY_VERSION)
2619
+
2620
+
2621
+ #if (PY_VERSION_HEX < _Py_PACK_VERSION(3, 15) \
2622
+ || (defined(Py_LIMITED_API) && Py_LIMITED_API+0 < _Py_PACK_VERSION(3, 15)))
2623
+ static inline PyObject*
2624
+ PySys_GetAttrString(const char *name)
2625
+ {
2626
+ PyObject *value = Py_XNewRef(PySys_GetObject(name));
2627
+ if (value != NULL) {
2628
+ return value;
2629
+ }
2630
+ if (!PyErr_Occurred()) {
2631
+ PyErr_Format(PyExc_RuntimeError, "lost sys.%s", name);
2632
+ }
2633
+ return NULL;
2634
+ }
2635
+
2636
+ static inline PyObject*
2637
+ PySys_GetAttr(PyObject *name)
2638
+ {
2639
+ #if defined(Py_LIMITED_API) && Py_LIMITED_API+0 < _Py_PACK_VERSION(3, 10)
2640
+ // Limited C API 3.9 and older
2641
+ PyObject *bytes, *result;
2642
+ bytes = PyUnicode_AsUTF8String(name);
2643
+ if (bytes == NULL) {
2644
+ return NULL;
2645
+ }
2646
+ result = PySys_GetAttrString(PyBytes_AsString(bytes));
2647
+ Py_DECREF(bytes);
2648
+ return result;
2649
+ #else
2650
+ // Python 3.14 and newer, and limited C API 3.10 and newer
2651
+ #ifndef Py_LIMITED_API
2652
+ const char *name_str = PyUnicode_AsUTF8(name);
2653
+ #else
2654
+ const char *name_str = PyUnicode_AsUTF8AndSize(name, NULL);
2655
+ #endif
2656
+ if (name_str == NULL) {
2657
+ return NULL;
2658
+ }
2659
+
2660
+ return PySys_GetAttrString(name_str);
2661
+ #endif
2662
+ }
2663
+
2664
+ static inline int
2665
+ PySys_GetOptionalAttrString(const char *name, PyObject **value)
2666
+ {
2667
+ *value = Py_XNewRef(PySys_GetObject(name));
2668
+ if (*value != NULL) {
2669
+ return 1;
2670
+ }
2671
+ return 0;
2672
+ }
2673
+
2674
+ static inline int
2675
+ PySys_GetOptionalAttr(PyObject *name, PyObject **value)
2676
+ {
2677
+ #if defined(Py_LIMITED_API) && Py_LIMITED_API+0 < _Py_PACK_VERSION(3, 10)
2678
+ // Limited C API 3.9 and older
2679
+ PyObject *bytes;
2680
+ int res;
2681
+ bytes = PyUnicode_AsUTF8String(name);
2682
+ if (bytes == NULL) {
2683
+ *value = NULL;
2684
+ return -1;
2685
+ }
2686
+ res = PySys_GetOptionalAttrString(PyBytes_AsString(bytes), value);
2687
+ Py_DECREF(bytes);
2688
+ return res;
2689
+ #else
2690
+ #ifndef Py_LIMITED_API
2691
+ const char *name_str = PyUnicode_AsUTF8(name);
2692
+ #else
2693
+ const char *name_str = PyUnicode_AsUTF8AndSize(name, NULL);
2694
+ #endif
2695
+ if (name_str == NULL) {
2696
+ *value = NULL;
2697
+ return -1;
2698
+ }
2699
+
2700
+ return PySys_GetOptionalAttrString(name_str, value);
2701
+ #endif
2702
+ }
2703
+ #endif // PY_VERSION_HEX < _Py_PACK_VERSION(3, 15)
2704
+
2705
+
2706
+ // _PyBytes_Resize() is not available in the limited C API.
2707
+ #if PY_VERSION_HEX < _Py_PACK_VERSION(3, 15) && !defined(Py_LIMITED_API)
2708
+ typedef struct PyBytesWriter {
2709
+ char small_buffer[256];
2710
+ PyObject *obj;
2711
+ Py_ssize_t size;
2712
+ } PyBytesWriter;
2713
+
2714
+ static inline Py_ssize_t
2715
+ _PyBytesWriter_GetAllocated(PyBytesWriter *writer)
2716
+ {
2717
+ if (writer->obj == NULL) {
2718
+ return sizeof(writer->small_buffer);
2719
+ }
2720
+ else {
2721
+ return PyBytes_GET_SIZE(writer->obj);
2722
+ }
2723
+ }
2724
+
2725
+
2726
+ static inline int
2727
+ _PyBytesWriter_Resize_impl(PyBytesWriter *writer, Py_ssize_t size,
2728
+ int resize)
2729
+ {
2730
+ int overallocate = resize;
2731
+ assert(size >= 0);
2732
+
2733
+ if (size <= _PyBytesWriter_GetAllocated(writer)) {
2734
+ return 0;
2735
+ }
2736
+
2737
+ if (overallocate) {
2738
+ #ifdef MS_WINDOWS
2739
+ /* On Windows, overallocate by 50% is the best factor */
2740
+ if (size <= (PY_SSIZE_T_MAX - size / 2)) {
2741
+ size += size / 2;
2742
+ }
2743
+ #else
2744
+ /* On Linux, overallocate by 25% is the best factor */
2745
+ if (size <= (PY_SSIZE_T_MAX - size / 4)) {
2746
+ size += size / 4;
2747
+ }
2748
+ #endif
2749
+ }
2750
+
2751
+ if (writer->obj != NULL) {
2752
+ if (_PyBytes_Resize(&writer->obj, size)) {
2753
+ return -1;
2754
+ }
2755
+ assert(writer->obj != NULL);
2756
+ }
2757
+ else {
2758
+ writer->obj = PyBytes_FromStringAndSize(NULL, size);
2759
+ if (writer->obj == NULL) {
2760
+ return -1;
2761
+ }
2762
+
2763
+ if (resize) {
2764
+ assert((size_t)size > sizeof(writer->small_buffer));
2765
+ memcpy(PyBytes_AS_STRING(writer->obj),
2766
+ writer->small_buffer,
2767
+ sizeof(writer->small_buffer));
2768
+ }
2769
+ }
2770
+ return 0;
2771
+ }
2772
+
2773
+ static inline void*
2774
+ PyBytesWriter_GetData(PyBytesWriter *writer)
2775
+ {
2776
+ if (writer->obj == NULL) {
2777
+ return writer->small_buffer;
2778
+ }
2779
+ else {
2780
+ return PyBytes_AS_STRING(writer->obj);
2781
+ }
2782
+ }
2783
+
2784
+ static inline Py_ssize_t
2785
+ PyBytesWriter_GetSize(PyBytesWriter *writer)
2786
+ {
2787
+ return writer->size;
2788
+ }
2789
+
2790
+ static inline void
2791
+ PyBytesWriter_Discard(PyBytesWriter *writer)
2792
+ {
2793
+ if (writer == NULL) {
2794
+ return;
2795
+ }
2796
+
2797
+ Py_XDECREF(writer->obj);
2798
+ PyMem_Free(writer);
2799
+ }
2800
+
2801
+ static inline PyBytesWriter*
2802
+ PyBytesWriter_Create(Py_ssize_t size)
2803
+ {
2804
+ if (size < 0) {
2805
+ PyErr_SetString(PyExc_ValueError, "size must be >= 0");
2806
+ return NULL;
2807
+ }
2808
+
2809
+ PyBytesWriter *writer = (PyBytesWriter*)PyMem_Malloc(sizeof(PyBytesWriter));
2810
+ if (writer == NULL) {
2811
+ PyErr_NoMemory();
2812
+ return NULL;
2813
+ }
2814
+
2815
+ writer->obj = NULL;
2816
+ writer->size = 0;
2817
+
2818
+ if (size >= 1) {
2819
+ if (_PyBytesWriter_Resize_impl(writer, size, 0) < 0) {
2820
+ PyBytesWriter_Discard(writer);
2821
+ return NULL;
2822
+ }
2823
+ writer->size = size;
2824
+ }
2825
+ return writer;
2826
+ }
2827
+
2828
+ static inline PyObject*
2829
+ PyBytesWriter_FinishWithSize(PyBytesWriter *writer, Py_ssize_t size)
2830
+ {
2831
+ PyObject *result;
2832
+ if (size == 0) {
2833
+ result = PyBytes_FromStringAndSize("", 0);
2834
+ }
2835
+ else if (writer->obj != NULL) {
2836
+ Py_ssize_t old_size = PyBytes_GET_SIZE(writer->obj);
2837
+ if (size != old_size) {
2838
+ if (_PyBytes_Resize(&writer->obj, size)) {
2839
+ goto error;
2840
+ }
2841
+ }
2842
+ result = writer->obj;
2843
+ writer->obj = NULL;
2844
+ }
2845
+ else {
2846
+ result = PyBytes_FromStringAndSize(writer->small_buffer, size);
2847
+ }
2848
+ PyBytesWriter_Discard(writer);
2849
+ return result;
2850
+
2851
+ error:
2852
+ PyBytesWriter_Discard(writer);
2853
+ return NULL;
2854
+ }
2855
+
2856
+ static inline PyObject*
2857
+ PyBytesWriter_Finish(PyBytesWriter *writer)
2858
+ {
2859
+ return PyBytesWriter_FinishWithSize(writer, writer->size);
2860
+ }
2861
+
2862
+ static inline PyObject*
2863
+ PyBytesWriter_FinishWithPointer(PyBytesWriter *writer, void *buf)
2864
+ {
2865
+ Py_ssize_t size = (char*)buf - (char*)PyBytesWriter_GetData(writer);
2866
+ if (size < 0 || size > _PyBytesWriter_GetAllocated(writer)) {
2867
+ PyBytesWriter_Discard(writer);
2868
+ PyErr_SetString(PyExc_ValueError, "invalid end pointer");
2869
+ return NULL;
2870
+ }
2871
+
2872
+ return PyBytesWriter_FinishWithSize(writer, size);
2873
+ }
2874
+
2875
+ static inline int
2876
+ PyBytesWriter_Resize(PyBytesWriter *writer, Py_ssize_t size)
2877
+ {
2878
+ if (size < 0) {
2879
+ PyErr_SetString(PyExc_ValueError, "size must be >= 0");
2880
+ return -1;
2881
+ }
2882
+ if (_PyBytesWriter_Resize_impl(writer, size, 1) < 0) {
2883
+ return -1;
2884
+ }
2885
+ writer->size = size;
2886
+ return 0;
2887
+ }
2888
+
2889
+ static inline int
2890
+ PyBytesWriter_Grow(PyBytesWriter *writer, Py_ssize_t size)
2891
+ {
2892
+ if (size < 0 && writer->size + size < 0) {
2893
+ PyErr_SetString(PyExc_ValueError, "invalid size");
2894
+ return -1;
2895
+ }
2896
+ if (size > PY_SSIZE_T_MAX - writer->size) {
2897
+ PyErr_NoMemory();
2898
+ return -1;
2899
+ }
2900
+ size = writer->size + size;
2901
+
2902
+ if (_PyBytesWriter_Resize_impl(writer, size, 1) < 0) {
2903
+ return -1;
2904
+ }
2905
+ writer->size = size;
2906
+ return 0;
2907
+ }
2908
+
2909
+ static inline void*
2910
+ PyBytesWriter_GrowAndUpdatePointer(PyBytesWriter *writer,
2911
+ Py_ssize_t size, void *buf)
2912
+ {
2913
+ Py_ssize_t pos = (char*)buf - (char*)PyBytesWriter_GetData(writer);
2914
+ if (PyBytesWriter_Grow(writer, size) < 0) {
2915
+ return NULL;
2916
+ }
2917
+ return (char*)PyBytesWriter_GetData(writer) + pos;
2918
+ }
2919
+
2920
+ static inline int
2921
+ PyBytesWriter_WriteBytes(PyBytesWriter *writer,
2922
+ const void *bytes, Py_ssize_t size)
2923
+ {
2924
+ if (size < 0) {
2925
+ size_t len = strlen((const char*)bytes);
2926
+ if (len > (size_t)PY_SSIZE_T_MAX) {
2927
+ PyErr_NoMemory();
2928
+ return -1;
2929
+ }
2930
+ size = (Py_ssize_t)len;
2931
+ }
2932
+
2933
+ Py_ssize_t pos = writer->size;
2934
+ if (PyBytesWriter_Grow(writer, size) < 0) {
2935
+ return -1;
2936
+ }
2937
+ char *buf = (char*)PyBytesWriter_GetData(writer);
2938
+ memcpy(buf + pos, bytes, (size_t)size);
2939
+ return 0;
2940
+ }
2941
+
2942
+ static inline int
2943
+ PyBytesWriter_Format(PyBytesWriter *writer, const char *format, ...)
2944
+ Py_GCC_ATTRIBUTE((format(printf, 2, 3)));
2945
+
2946
+ static inline int
2947
+ PyBytesWriter_Format(PyBytesWriter *writer, const char *format, ...)
2948
+ {
2949
+ va_list vargs;
2950
+ va_start(vargs, format);
2951
+ PyObject *str = PyBytes_FromFormatV(format, vargs);
2952
+ va_end(vargs);
2953
+
2954
+ if (str == NULL) {
2955
+ return -1;
2956
+ }
2957
+ int res = PyBytesWriter_WriteBytes(writer,
2958
+ PyBytes_AS_STRING(str),
2959
+ PyBytes_GET_SIZE(str));
2960
+ Py_DECREF(str);
2961
+ return res;
2962
+ }
2963
+ #endif // PY_VERSION_HEX < _Py_PACK_VERSION(3, 15)
2964
+
2965
+
2966
+ #if PY_VERSION_HEX < _Py_PACK_VERSION(3, 15) || defined(Py_LIMITED_API)
2967
+ static inline PyObject*
2968
+ PyTuple_FromArray(PyObject *const *array, Py_ssize_t size)
2969
+ {
2970
+ PyObject *tuple = PyTuple_New(size);
2971
+ if (tuple == NULL) {
2972
+ return NULL;
2973
+ }
2974
+ for (Py_ssize_t i=0; i < size; i++) {
2975
+ PyObject *item = array[i];
2976
+ #ifndef Py_LIMITED_API
2977
+ PyTuple_SET_ITEM(tuple, i, Py_NewRef(item));
2978
+ #else
2979
+ if (PyTuple_SetItem(tuple, i, Py_NewRef(item)) < 0) {
2980
+ Py_DECREF(tuple);
2981
+ return NULL;
2982
+ }
2983
+ #endif
2984
+ }
2985
+ return tuple;
2986
+ }
2987
+ #endif
2988
+
2989
+
2990
+ #if PY_VERSION_HEX < _Py_PACK_VERSION(3, 15) && !defined(Py_LIMITED_API)
2991
+ static inline Py_hash_t
2992
+ PyUnstable_Unicode_GET_CACHED_HASH(PyObject *op)
2993
+ {
2994
+ #ifdef PYPY_VERSION
2995
+ (void)op; // unused argument
2996
+ return -1;
2997
+ #else
2998
+ return ((PyASCIIObject*)op)->hash;
2999
+ #endif
3000
+ }
3001
+ #endif
3002
+
3003
+ #if (_Py_PACK_VERSION(3, 13) <= PY_VERSION_HEX \
3004
+ && PY_VERSION_HEX < _Py_PACK_VERSION(3, 15) \
3005
+ && !defined(PYPY_VERSION) && !defined(Py_LIMITED_API))
3006
+ // Immortal objects were implemented in Python 3.12, however there is no easy API
3007
+ // to make objects immortal until 3.14 which has _Py_SetImmortal(). Since
3008
+ // immortal objects are primarily needed for free-threading, this API is implemented
3009
+ // for 3.14 using _Py_SetImmortal() and uses private macros on 3.13.
3010
+ #if _Py_PACK_VERSION(3, 14) <= PY_VERSION_HEX
3011
+ PyAPI_FUNC(void) _Py_SetImmortal(PyObject *op);
3012
+ #endif
3013
+
3014
+ static inline int
3015
+ PyUnstable_SetImmortal(PyObject *op)
3016
+ {
3017
+ assert(op != NULL);
3018
+ if (!PyUnstable_Object_IsUniquelyReferenced(op) || PyUnicode_Check(op)) {
3019
+ return 0;
3020
+ }
3021
+ #if _Py_PACK_VERSION(3, 14) <= PY_VERSION_HEX
3022
+ _Py_SetImmortal(op);
3023
+ #else
3024
+ // Python 3.13 doesn't export _Py_SetImmortal() function
3025
+ if (PyObject_GC_IsTracked(op)) {
3026
+ PyObject_GC_UnTrack(op);
3027
+ }
3028
+ #ifdef Py_GIL_DISABLED
3029
+ op->ob_tid = _Py_UNOWNED_TID;
3030
+ op->ob_ref_local = _Py_IMMORTAL_REFCNT_LOCAL;
3031
+ op->ob_ref_shared = 0;
3032
+ #else
3033
+ op->ob_refcnt = _Py_IMMORTAL_REFCNT;
3034
+ #endif
3035
+ #endif
3036
+ return 1;
3037
+ }
3038
+ #endif
3039
+
3040
+
3041
+ // Python 3.14 added PyImport_ImportModuleAttr()
3042
+ // and PyImport_ImportModuleAttrString()
3043
+ #if PY_VERSION_HEX < _Py_PACK_VERSION(3, 14) || defined(Py_LIMITED_API)
3044
+ static inline PyObject*
3045
+ PyImport_ImportModuleAttr(PyObject *mod_name, PyObject *attr_name)
3046
+ {
3047
+ PyObject *mod = PyImport_Import(mod_name);
3048
+ if (mod == NULL) {
3049
+ return NULL;
3050
+ }
3051
+
3052
+ PyObject *result = PyObject_GetAttr(mod, attr_name);
3053
+ Py_DECREF(mod);
3054
+ return result;
3055
+ }
3056
+
3057
+ static inline PyObject *
3058
+ PyImport_ImportModuleAttrString(const char *mod_name, const char *attr_name)
3059
+ {
3060
+ PyObject *mod_name_obj = PyUnicode_FromString(mod_name);
3061
+ if (mod_name_obj == NULL) {
3062
+ return NULL;
3063
+ }
3064
+ PyObject *attr_name_obj = PyUnicode_FromString(attr_name);
3065
+ if (attr_name_obj == NULL) {
3066
+ Py_DECREF(mod_name_obj);
3067
+ return NULL;
3068
+ }
3069
+
3070
+ PyObject *result = PyImport_ImportModuleAttr(mod_name_obj, attr_name_obj);
3071
+ Py_DECREF(attr_name_obj);
3072
+ Py_DECREF(mod_name_obj);
3073
+ return result;
3074
+ }
3075
+ #endif
3076
+
3077
+
3078
+ // Python 3.11 added PyType_GetName() and PyType_GetQualName()
3079
+ #if (PY_VERSION_HEX < _Py_PACK_VERSION(3, 11) \
3080
+ || (defined(Py_LIMITED_API) && Py_LIMITED_API+0 < _Py_PACK_VERSION(3, 11)))
3081
+ static inline PyObject*
3082
+ PyType_GetName(PyTypeObject *type)
3083
+ {
3084
+ return PyObject_GetAttrString(_PyObject_CAST(type), "__name__");
3085
+ }
3086
+
3087
+ static inline PyObject*
3088
+ PyType_GetQualName(PyTypeObject *type)
3089
+ {
3090
+ return PyObject_GetAttrString(_PyObject_CAST(type), "__qualname__");
3091
+ }
3092
+ #endif
3093
+
3094
+
3095
+ // Python 3.13 added PyType_GetModuleName() and PyType_GetFullyQualifiedName()
3096
+ #if (PY_VERSION_HEX < _Py_PACK_VERSION(3, 13) \
3097
+ || (defined(Py_LIMITED_API) && Py_LIMITED_API+0 < _Py_PACK_VERSION(3, 13)))
3098
+ static inline PyObject*
3099
+ PyType_GetModuleName(PyTypeObject *type)
3100
+ {
3101
+ return PyObject_GetAttrString(_PyObject_CAST(type), "__module__");
3102
+ }
3103
+
3104
+ static inline PyObject *
3105
+ PyType_GetFullyQualifiedName(PyTypeObject *type)
3106
+ {
3107
+ PyObject *qualname = PyType_GetQualName(type);
3108
+ if (qualname == NULL) {
3109
+ return NULL;
3110
+ }
3111
+
3112
+ PyObject *module = PyType_GetModuleName(type);
3113
+ if (module == NULL) {
3114
+ Py_DECREF(qualname);
3115
+ return NULL;
3116
+ }
3117
+
3118
+ PyObject *result;
3119
+ if (PyUnicode_Check(module)
3120
+ && PyUnicode_EqualToUTF8(module, "builtins") == 0
3121
+ && PyUnicode_EqualToUTF8(module, "__main__") == 0)
3122
+ {
3123
+ result = PyUnicode_FromFormat("%U.%U", module, qualname);
3124
+ }
3125
+ else {
3126
+ result = Py_NewRef(qualname);
3127
+ }
3128
+ Py_DECREF(module);
3129
+ Py_DECREF(qualname);
3130
+ return result;
3131
+ }
3132
+ #endif
3133
+
3134
+
3135
+ #ifdef __cplusplus
3136
+ }
3137
+ #endif
3138
+ #endif // PYTHONCAPI_COMPAT