diff options
author | kdx <kikoodx@paranoici.org> | 2023-01-14 12:37:03 +0100 |
---|---|---|
committer | kdx <kikoodx@paranoici.org> | 2023-01-14 12:37:03 +0100 |
commit | ae70101ad3c97507f1ed73decd3572fc72aad55e (patch) | |
tree | 2fc0e68f03561e642655bcc416b551f3e7d7e1c3 | |
parent | 108b1c64383e8ad8bdd8d7f87ef0cdbe68d882ff (diff) | |
download | sloth-ae70101ad3c97507f1ed73decd3572fc72aad55e.tar.gz |
pop/push/inspect_stack
-rw-r--r-- | main.c | 7 | ||||
-rw-r--r-- | sloth.c | 37 | ||||
-rw-r--r-- | sloth.h | 4 |
3 files changed, 48 insertions, 0 deletions
@@ -8,12 +8,19 @@ int main(int argc, char **argv) (void)argc, (void)argv; /* Initialize sloth. */ Sloth *const sloth = calloc(1, sizeof(Sloth)); + SlothError err; if (sloth == NULL) return 1; /* Read stdin line by line until exhaustion. */ char *line = NULL; while ((line = getln(stdin)) != NULL) { printf("%s", line); + err = sloth_push(sloth, line[0]); + if (err != NULL) { + fprintf(stderr, "%s\n", err); + break; + } + sloth_inspect_stack(sloth); free(line); } /* Free everything. */ @@ -1,4 +1,5 @@ #include "sloth.h" +#include <stdio.h> #include <stdlib.h> void sloth_deinit(Sloth *ctx) @@ -8,3 +9,39 @@ void sloth_deinit(Sloth *ctx) ctx->stack = NULL; } } + +SlothError sloth_pop(Sloth *ctx, SlothByte *v) +{ + if (ctx->stack_size == 0) + return "sloth_pull: stack is empty"; + *v = ctx->stack[ctx->stack_size - 1]; + ctx->stack_size -= 1; + return NULL; +} + +SlothError sloth_push(Sloth *ctx, SlothByte v) +{ + if (ctx->stack == NULL) { + ctx->stack = malloc(sizeof(SlothByte) * 16); + if (ctx->stack == NULL) + return "sloth_push: calloc failed"; + ctx->stack_capacity = 16; + } else if (ctx->stack_size == ctx->stack_capacity) { + SlothByte *const new_stack = + realloc(ctx->stack, ctx->stack_capacity * 2); + if (new_stack == NULL) + return "sloth_push: realloc failed"; + ctx->stack_capacity *= 2; + } + ctx->stack[ctx->stack_size] = v; + ctx->stack_size += 1; + return NULL; +} + +void sloth_inspect_stack(const Sloth *ctx) +{ + printf("size: %lu\n", ctx->stack_size); + printf("capacity: %lu\n", ctx->stack_capacity); + for (size_t i = 0; i < ctx->stack_size; i++) + printf("%08lx: %d\n", i, ctx->stack[i]); +} @@ -6,6 +6,7 @@ #define SLOTH_BITS 16 typedef uint16_t SlothByte; +typedef const char* SlothError; typedef struct Sloth { SlothByte *stack; size_t stack_size; @@ -14,3 +15,6 @@ typedef struct Sloth { } Sloth; void sloth_deinit(Sloth *ctx); +SlothError sloth_pop(Sloth *ctx, SlothByte *v); +SlothError sloth_push(Sloth *ctx, SlothByte v); +void sloth_inspect_stack(const Sloth *ctx); |