burkey.co /docs/libflint/stack
index stack
~/docs/libflint/stack.md
libflint

Stack

libflint·Data Structures

A LIFO stack of void * backed by a List. The caller owns the Stack handle. Payloads are borrowed unless a destroy callback is set.

Usage#

Initialize a Stack with NULL for borrowed payloads, or a destructor such as free for payloads the stack should free when destroyed.

Stack stack;
stack_init(&stack, NULL);
int value = 42;
if (stack_push(&stack, &value) == 0) {
    void *data;
    if (stack_pop(&stack, &data) == 0) {
        /* data == &value */
    }
}
stack_destroy(&stack);

Pop writes the payload to the caller and does not call the destructor. stack_destroy frees the remaining nodes, calls the destructor on their payloads from the top toward the bottom, and zeros the handle. It does not free the Stack. A second destroy is a no-op.

Structs#

Stack#

typedef struct {
    List impl;
} Stack;

The top is the tail of impl.

Functions#

stack_init#

Initializes an empty stack and stores destroy. The destructor runs only from stack_destroy, and only on payloads still on the stack. Pass NULL for borrowed data. Do not call it on a stack that still owns nodes. stack must be non-NULL.

void stack_init(Stack *stack, void (*destroy)(void *data));

stack_destroy#

Frees every node. If destroy is non-NULL, calls it on each remaining payload from the top toward the bottom. Does not free the Stack handle. Zeros the handle, so a second call is a no-op. stack must be non-NULL.

void stack_destroy(Stack *stack);

stack_push#

Pushes data on the top. The pointer is stored, not the payload bytes. Returns 0 on success and -1 if node allocation fails. Failure leaves the stack unchanged. stack must be non-NULL. A NULL payload is allowed.

int stack_push(Stack *stack, const void *data);

stack_peek#

Returns the top payload without removing it. Returns NULL if the stack is empty or the stored payload is NULL. stack must be non-NULL.

void *stack_peek(Stack *stack);

stack_pop#

Removes the top node and writes its payload to *data. Returns 0 on success. Returns -1 if the stack is empty or data is NULL, and leaves the stack unchanged. Does not call destroy. A stored NULL payload is removed, and *data is set to NULL.

int stack_pop(Stack *stack, void **data);

Macros#

stack_size#

The number of elements.

#define stack_size(s) ((s)->impl.size)

stack_is_empty#

Nonzero when the stack has no elements.

#define stack_is_empty(s) ((s)->impl.size == 0)