summaryrefslogtreecommitdiff
path: root/src/util
diff options
context:
space:
mode:
Diffstat (limited to 'src/util')
-rw-r--r--src/util/shared.c9
-rw-r--r--src/util/stack.c32
-rw-r--r--src/util/stack.h26
3 files changed, 63 insertions, 4 deletions
diff --git a/src/util/shared.c b/src/util/shared.c
index e207c6d..3e6fca3 100644
--- a/src/util/shared.c
+++ b/src/util/shared.c
@@ -20,6 +20,11 @@ void error(const char* format, ...) {
FILE* get_file_s(const char* path, const char* type) {
struct stat s;
+ if (streql("-", path) && type[0] == 'r') {
+ clearerr(stdin);
+ fflush(stdin);
+ return stdin;
+ }
if (lstat(path, &s) < 0) {
if (type[0] != 'r') goto read;
fprintf(stderr, "error: failed to read %s: %s\n", path, strerror(errno));
@@ -40,10 +45,6 @@ read:
}
FILE* get_file(const char* path, const char* type) {
- if (streql("-", path) && type[0] == 'r') {
- clearerr(stdin);
- return stdin;
- }
FILE* file = get_file_s(path, type);
if (file == NULL) exit(EXIT_FAILURE);
return file;
diff --git a/src/util/stack.c b/src/util/stack.c
new file mode 100644
index 0000000..15d5a8e
--- /dev/null
+++ b/src/util/stack.c
@@ -0,0 +1,32 @@
+#include "stack.h"
+
+#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;
+ stack->data = malloc(size);
+}
+
+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;
+ stack->data = realloc(stack->data, stack->capacity);
+ }
+ 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);
+}
diff --git a/src/util/stack.h b/src/util/stack.h
new file mode 100644
index 0000000..01a48e5
--- /dev/null
+++ b/src/util/stack.h
@@ -0,0 +1,26 @@
+#pragma once
+
+#include <stddef.h>
+#include <stdbool.h>
+
+struct Stack {
+ size_t size;
+ size_t capacity;
+ void* data;
+};
+
+void stack_init(struct Stack* stack, size_t size);
+void stack_push(struct Stack* stack, void* data, size_t len);
+void* stack_pop(struct Stack* stack, size_t len);
+void stack_free(struct Stack* stack);
+
+inline void stack_push_int(struct Stack* stack, int value) {
+ stack_push(stack, &value, sizeof(int));
+}
+
+inline 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;
+}