(root)/
gawk-5.2.2/
extension/
stack.c
       1  /*
       2   * stack.c -- Implementation for stack functions for use by extensions.
       3   */
       4  
       5  /*
       6   * Copyright (C) 2012, 2013 the Free Software Foundation, Inc.
       7   *
       8   * This file is part of GAWK, the GNU implementation of the
       9   * AWK Programming Language.
      10   *
      11   * GAWK is free software; you can redistribute it and/or modify
      12   * it under the terms of the GNU General Public License as published by
      13   * the Free Software Foundation; either version 3 of the License, or
      14   * (at your option) any later version.
      15   *
      16   * GAWK is distributed in the hope that it will be useful,
      17   * but WITHOUT ANY WARRANTY; without even the implied warranty of
      18   * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
      19   * GNU General Public License for more details.
      20   *
      21   * You should have received a copy of the GNU General Public License
      22   * along with this program; if not, write to the Free Software
      23   * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA  02110-1301, USA
      24   */
      25  
      26  #include <stdlib.h>
      27  
      28  #include "stack.h"
      29  
      30  #define INITIAL_STACK	20
      31  
      32  static size_t size;
      33  static void **stack;
      34  static int index = -1;
      35  
      36  /* stack_empty --- return true if stack is empty */
      37  
      38  int
      39  stack_empty()
      40  {
      41  	return index < 0;
      42  }
      43  
      44  /* stack_top --- return top object on the stack */
      45  
      46  void *
      47  stack_top()
      48  {
      49  	if (stack_empty() || stack == NULL)
      50  		return NULL;
      51  
      52  	return stack[index];
      53  }
      54  
      55  /* stack_pop --- pop top object and return it */
      56  
      57  void *
      58  stack_pop()
      59  {
      60  	if (stack_empty() || stack == NULL)
      61  		return NULL;
      62  
      63  	return stack[index--];
      64  }
      65  
      66  /* stack_push --- push an object onto the stack */
      67  
      68  int stack_push(void *object)
      69  {
      70  	void **new_stack;
      71  	size_t new_size = 2 * size;
      72  
      73  	if (stack == NULL) {
      74  		stack = (void **) malloc(INITIAL_STACK * sizeof(void *));
      75  		if (stack == NULL)
      76  			return 0;
      77  		size = INITIAL_STACK;
      78  	} else if (index + 1 >= size) {
      79  		if (new_size < size)
      80  			return 0;
      81  		new_stack = realloc(stack, new_size * sizeof(void *));
      82  		if (new_stack == NULL)
      83  			return 0;
      84  		size = new_size;
      85  		stack = new_stack;
      86  	}
      87  
      88  	stack[++index] = object;
      89  	return 1;
      90  }