btcs

bitcoin script parser/evaluator/compiler/decompiler
git clone git://jb55.com/btcs
Log | Files | Refs | README | LICENSE

stack.h (1755B)


      1 
      2 #ifndef BTCS_STACK_H
      3 #define BTCS_STACK_H
      4 
      5 #include <assert.h>
      6 #include <string.h>
      7 #include <stdio.h>
      8 #include "misc.h"
      9 
     10 // Maximum number of values on script interpreter stack
     11 static const int MAX_STACK_SIZE = 1000;
     12 
     13 // Maximum number of values on script interpreter stack
     14 #define DEFAULT_STACK_SIZE 32
     15 
     16 struct stack {
     17   void *_data[DEFAULT_STACK_SIZE];
     18   void **bottom;
     19   void **top;
     20   int capacity;
     21 };
     22 
     23 int   stack_init(struct stack *);
     24 int   stack_init_size(struct stack *, int size);
     25 void  stack_free(struct stack *);
     26 void  stack_clear(struct stack *);
     27 void* stack_pop(struct stack *);
     28 void  stack_erase(struct stack *, int ind);
     29 void  stack_push(struct stack *, void *val);
     30 
     31 static inline void *
     32 stack_top(struct stack *stack, int ind) {
     33   void **p = stack->top + ind;
     34   assert(p >= stack->bottom);
     35   assert(p);
     36   return *p;
     37 }
     38 
     39 static inline int
     40 stack_size(struct stack *stack) {
     41   return stack->top - stack->bottom;
     42 }
     43 
     44 static inline void
     45 stack_swap(struct stack *stack, int ind1, int ind2) {
     46   void *temp = *(stack->top + ind1);
     47   *(stack->top + ind1) = *(stack->top + ind2);
     48   *(stack->top + ind2) = temp;
     49 }
     50 
     51 #define stack_push_small(T, stack, val) { \
     52   assert(sizeof(T) <= sizeof(void*)); \
     53   void *tmp = 0; \
     54   memcpy(&tmp, val, sizeof(T));                    \
     55   stack_push(stack, tmp); \
     56 }
     57 
     58 #define stack_top_small(T, stack, v, ind)     \
     59   memcpy(v, stack->top + ind, sizeof(T))
     60 
     61 static inline void
     62 _stack_push_smallt(struct stack *stack, void *p, size_t size) {
     63 #if 0
     64   u8 *b = (u8*)p;
     65   printf("pushing small", "");
     66   for (size_t i = 0; i < size; ++i) {
     67     printf(" %02x", b[i]);
     68   }
     69   printf("\n");
     70 #endif
     71   assert(size <= sizeof(void*));
     72   void *tmp = 0;
     73   memcpy(&tmp, p, size);
     74   stack_push(stack, tmp);
     75 }
     76 
     77 #endif /* BTCS_STACK_H */