stack.c 1.7 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899
  1. #include <stdlib.h>
  2. #include <stdio.h>
  3. #include <string.h>
  4. #include <errno.h>
  5. #include "sans.h"
  6. #include "stack.h"
  7. #define MAX_STACK (1<<20)
  8. u stack_ptr = 0;
  9. sdata stack[MAX_STACK];
  10. void stack_dump() {
  11. u i = stack_ptr;
  12. //puts("--- stack dump start ---");
  13. while(i > 0) {
  14. printf("%d\n", stack[i--].tag);
  15. }
  16. //puts("--- stack dump end ---");
  17. }
  18. void stack_push(sdata obj) {
  19. //printf("stack_push(%d)\n", obj.tag);
  20. if (stack_ptr < MAX_STACK) {
  21. stack[stack_ptr++] = obj;
  22. }
  23. else {
  24. log_err("stack/stack_push: overflow\n");
  25. }
  26. }
  27. sdata stack_pop() {
  28. //printf("stack_pop()\n");
  29. if (stack_ptr) {
  30. return stack[--stack_ptr];
  31. }
  32. else {
  33. log_err("stack/stack_pop: underflow\n");
  34. }
  35. }
  36. void stack_grow(u n) {
  37. //printf("stack_grow(%lu)\n", n);
  38. u new = stack_ptr + n;
  39. if (new <= MAX_STACK) {
  40. stack_ptr = new;
  41. }
  42. else {
  43. log_err("stack/stack_grow: overflow\n");
  44. }
  45. }
  46. void stack_shrink(u n) {
  47. //printf("stack_shrink(%lu)\n", n);
  48. u new = stack_ptr - n;
  49. if (new >= 0) {
  50. stack_ptr = new;
  51. }
  52. else {
  53. log_err("stack/stack_shrink: underflow\n");
  54. }
  55. }
  56. sdata stack_ref(u o) {
  57. u o1 = stack_ptr - o - 1;
  58. if (o1 >= 0) {
  59. return stack[o1];
  60. }
  61. else {
  62. log_err("stack/stack_ref: out of bounds\n");
  63. }
  64. }
  65. void stack_set(u o, sdata val) {
  66. u o1 = stack_ptr - o - 1;
  67. if (o1 >= 0) {
  68. stack[o1] = val;
  69. }
  70. else {
  71. log_err("stack/stack_set: out of bounds\n");
  72. }
  73. }
  74. void stack_fold(u width, u distance) {
  75. // stack_fold(2, 3) will move
  76. // the top 2 things on the stack
  77. // back down by 3
  78. //
  79. // [a][b][c][d][e][f]
  80. // [a][e][f]
  81. //
  82. memmove(&stack[stack_ptr-width-distance],
  83. &stack[stack_ptr-width],
  84. sizeof(sdata)*width);
  85. stack_ptr -= distance;
  86. }