lazysphere/lib/stack.c

44 lines
1.1 KiB
C
Raw Normal View History

2023-05-15 01:43:02 +00:00
#include "lslib.h"
2023-05-02 04:37:30 +00:00
#include <stdint.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
void stack_init(struct Stack* stack, size_t size) {
stack->size = 0;
stack->capacity = size;
2023-05-15 01:43:02 +00:00
stack->data = xalloc(size);
2023-05-02 04:37:30 +00:00
}
void stack_push(struct Stack* stack, void* data, size_t len) {
size_t new_size = stack->size + len;
if (new_size >= stack->capacity) {
stack->capacity = new_size * 2;
2023-05-15 01:43:02 +00:00
stack->data = xrealloc(stack->data, stack->capacity);
2023-05-02 04:37:30 +00:00
}
memcpy((uint8_t*)stack->data + stack->size, data, len);
stack->size += len;
}
void* stack_pop(struct Stack* stack, size_t len) {
if (stack->size < len) return NULL;
stack->size -= len;
return (uint8_t*)stack->data + stack->size;
}
void stack_free(struct Stack *stack) {
free(stack->data);
}
2023-05-04 20:10:37 +00:00
void stack_push_int(struct Stack *stack, int value) {
stack_push(stack, &value, sizeof(int));
}
bool stack_pop_int(struct Stack *stack, int* value) {
void* d = stack_pop(stack, sizeof(int));
if (d == NULL) return false;
*value = *(int*)(d);
return true;
}