|
| 1 | +#ifndef Py_INTERNAL_OBJECT_STACK_H |
| 2 | +#define Py_INTERNAL_OBJECT_STACK_H |
| 3 | + |
| 4 | +#ifdef __cplusplus |
| 5 | +extern "C" { |
| 6 | +#endif |
| 7 | + |
| 8 | +#ifndef Py_BUILD_CORE |
| 9 | +# error "this header requires Py_BUILD_CORE define" |
| 10 | +#endif |
| 11 | + |
| 12 | +// _PyObjectStack is a stack of Python objects implemented as a linked list of |
| 13 | +// fixed size buffers. |
| 14 | + |
| 15 | +// Chosen so that _PyObjectStackChunk is a power-of-two size. |
| 16 | +#define _Py_OBJECT_STACK_CHUNK_SIZE 254 |
| 17 | + |
| 18 | +typedef struct _PyObjectStackChunk { |
| 19 | + struct _PyObjectStackChunk *prev; |
| 20 | + Py_ssize_t n; |
| 21 | + PyObject *objs[_Py_OBJECT_STACK_CHUNK_SIZE]; |
| 22 | +} _PyObjectStackChunk; |
| 23 | + |
| 24 | +typedef struct _PyObjectStack { |
| 25 | + _PyObjectStackChunk *head; |
| 26 | +} _PyObjectStack; |
| 27 | + |
| 28 | + |
| 29 | +extern _PyObjectStackChunk * |
| 30 | +_PyObjectStackChunk_New(void); |
| 31 | + |
| 32 | +extern void |
| 33 | +_PyObjectStackChunk_Free(_PyObjectStackChunk *); |
| 34 | + |
| 35 | +extern void |
| 36 | +_PyObjectStackChunk_ClearFreeList(_PyFreeListState *state, int is_finalization); |
| 37 | + |
| 38 | +// Push an item onto the stack. Return -1 on allocation failure, 0 on success. |
| 39 | +static inline int |
| 40 | +_PyObjectStack_Push(_PyObjectStack *stack, PyObject *obj) |
| 41 | +{ |
| 42 | + _PyObjectStackChunk *buf = stack->head; |
| 43 | + if (buf == NULL || buf->n == _Py_OBJECT_STACK_CHUNK_SIZE) { |
| 44 | + buf = _PyObjectStackChunk_New(); |
| 45 | + if (buf == NULL) { |
| 46 | + return -1; |
| 47 | + } |
| 48 | + buf->prev = stack->head; |
| 49 | + buf->n = 0; |
| 50 | + stack->head = buf; |
| 51 | + } |
| 52 | + |
| 53 | + assert(buf->n >= 0 && buf->n < _Py_OBJECT_STACK_CHUNK_SIZE); |
| 54 | + buf->objs[buf->n] = obj; |
| 55 | + buf->n++; |
| 56 | + return 0; |
| 57 | +} |
| 58 | + |
| 59 | +// Pop the top item from the stack. Return NULL if the stack is empty. |
| 60 | +static inline PyObject * |
| 61 | +_PyObjectStack_Pop(_PyObjectStack *stack) |
| 62 | +{ |
| 63 | + _PyObjectStackChunk *buf = stack->head; |
| 64 | + if (buf == NULL) { |
| 65 | + return NULL; |
| 66 | + } |
| 67 | + assert(buf->n > 0 && buf->n <= _Py_OBJECT_STACK_CHUNK_SIZE); |
| 68 | + buf->n--; |
| 69 | + PyObject *obj = buf->objs[buf->n]; |
| 70 | + if (buf->n == 0) { |
| 71 | + stack->head = buf->prev; |
| 72 | + _PyObjectStackChunk_Free(buf); |
| 73 | + } |
| 74 | + return obj; |
| 75 | +} |
| 76 | + |
| 77 | +// Remove all items from the stack |
| 78 | +extern void |
| 79 | +_PyObjectStack_Clear(_PyObjectStack *stack); |
| 80 | + |
| 81 | +#ifdef __cplusplus |
| 82 | +} |
| 83 | +#endif |
| 84 | +#endif // !Py_INTERNAL_OBJECT_STACK_H |
0 commit comments