Debian Codegraph @

mypyc/lib-rt/pythoncapi_compat.h

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