1/** 2 * \file 3 * \brief Barrelfish collections library stack 4 */ 5 6/* 7 * Copyright (c) 2012, ETH Zurich. 8 * All rights reserved. 9 * 10 * This file is distributed under the terms in the attached LICENSE file. 11 * If you do not find this file, copies can be found by writing to: 12 * ETH Zurich D-INFK, Universitaetstrasse 6, CH-8092 Zurich. Attn: Systems Group. 13 */ 14 15#include <collections/list.h> 16#include <collections/stack.h> 17 18#include <assert.h> 19 20/** 21 * \brief Initialize the stack data structure. 22 * 23 * \param stack Pointer to a pointer to a stack. Filled-in by function. 24 * 25 * Example usage: 26 * \code 27 * struct collections_stack *stack; 28 * collections_stack_create(&stack); 29 * \endcode 30 */ 31void collections_stack_create(struct collections_stack **stack) 32{ 33 *stack = (struct collections_stack *) 34 malloc(sizeof(struct collections_stack)); 35 assert(*stack != NULL); 36 37 (*stack)->num_elements = 0; 38 39 // create a linked list to hold the elements of the stack 40 collections_list_create(&(*stack)->elements, NULL); 41 42 return; 43} 44 45/** 46 * \brief Returns the top element of the stack and removes it. 47 */ 48void *collections_stack_pop(struct collections_stack *stack) 49{ 50 return collections_list_remove_ith_item(stack->elements, 0); 51} 52 53/** 54 * \brief Push an element to the top of the stack. 55 */ 56void collections_stack_push(struct collections_stack *stack, void *element) 57{ 58 collections_list_insert(stack->elements, element); 59 60 return; 61} 62 63/** 64 * \brief Returns the top element of the stack, does not remove it. 65 */ 66void *collections_stack_top(struct collections_stack *stack) 67{ 68 return collections_list_get_ith_item(stack->elements, 0); 69} 70 71/** 72 * \brief Free all memory associated with the stack. 73 */ 74void collections_stack_release(struct collections_stack *stack) 75{ 76 if (stack == NULL) { 77 return; 78 } 79 80 collections_list_release(stack->elements); 81 free(stack); 82} 83