/ src / stack.c
stack.c
 1  /*
 2   *  Bean Java VM
 3   *  Copyright (C) 2005-2015 Christian Lins <christian@lins.me>
 4   *
 5   *  Licensed under the Apache License, Version 2.0 (the "License");
 6   *  you may not use this file except in compliance with the License.
 7   *  You may obtain a copy of the License at
 8   *
 9   *     http://www.apache.org/licenses/LICENSE-2.0
10   *
11   *  Unless required by applicable law or agreed to in writing, software
12   *  distributed under the License is distributed on an "AS IS" BASIS,
13   *  WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
14   *  See the License for the specific language governing permissions and
15   *  limitations under the License.
16   */
17  
18  #include <vm.h>
19  
20  /**
21   * Pops all elements of the given stack.
22   * The elements itself are released to the free heap space.
23   */
24  void Stack_destroy(Stack* stack)
25  {
26      assert(stack != NULL);
27  
28      while (stack->size > 0) {
29          void *data;
30          Stack_pop(stack, &data);
31          free(data);
32      }
33      
34      free(stack);
35  }
36  
37  /** Creates a new Stack instance ind initializes it */
38  Stack* Stack_new(unsigned int limit)
39  {
40      assert(limit > 0);
41      
42      Stack* stack = (Stack*)malloc(sizeof(Stack));
43  
44      stack->limit = limit;
45      stack->size = 0;
46      stack->top = NULL;
47      
48      return stack;
49  }
50  
51  int Stack_pop(Stack* stack, void** data)
52  {
53      #ifdef DEBUG
54          printf("Stack_pop(%p) limit=%u, size=%u\n", (void*)stack, stack->limit, stack->size);
55      #endif
56  
57      void *ptr;
58  
59      if (stack->size == 0) {
60          return 1;  /* Stack underflow */
61      } else {
62          *data = stack->top->data;
63          ptr = stack->top;
64          stack->top = stack->top->next;
65          stack->size--;
66          free(ptr);
67          return 0;
68      }
69  }
70  
71  int Stack_push(Stack* stack, void* data)
72  {
73      #ifdef DEBUG
74          printf("Stack_push(%p) limit=%u, size=%u\n", (void*)stack, stack->limit, stack->size);
75      #endif
76  
77      if (stack->size == stack->limit) {
78          return 1;  /* Stack overflow */
79      } else {
80          StackElement* new = malloc(sizeof(StackElement));
81          new->data = data;
82          new->next = stack->top;
83          stack->top = new;
84          stack->size++;
85          return 0;
86      }
87  }