Branch data Line data Source code
1 : : /* SPDX-License-Identifier: BSD-3-Clause 2 : : * Copyright(c) 2019-2023 Broadcom 3 : : * All rights reserved. 4 : : */ 5 : : 6 : : #include <stdio.h> 7 : : #include <stdlib.h> 8 : : #include <stdbool.h> 9 : : #include <stdint.h> 10 : : #include <errno.h> 11 : : #include "stack.h" 12 : : 13 : : #define STACK_EMPTY -1 14 : : 15 : : /* Initialize stack 16 : : */ 17 : : int 18 : 0 : stack_init(int num_entries, uint32_t *items, struct stack *st) 19 : : { 20 [ # # ]: 0 : if (items == NULL || st == NULL) 21 : : return -EINVAL; 22 : : 23 : 0 : st->max = num_entries; 24 : 0 : st->top = STACK_EMPTY; 25 : 0 : st->items = items; 26 : : 27 : 0 : return 0; 28 : : } 29 : : 30 : : /* 31 : : * Return the address of the items 32 : : */ 33 : 0 : uint32_t *stack_items(struct stack *st) 34 : : { 35 : 0 : return st->items; 36 : : } 37 : : 38 : : /* Return the size of the stack 39 : : */ 40 : : int32_t 41 : 0 : stack_size(struct stack *st) 42 : : { 43 : 0 : return st->top + 1; 44 : : } 45 : : 46 : : /* Check if the stack is empty 47 : : */ 48 : : bool 49 : 0 : stack_is_empty(struct stack *st) 50 : : { 51 : 0 : return st->top == STACK_EMPTY; 52 : : } 53 : : 54 : : /* Check if the stack is full 55 : : */ 56 : : bool 57 : 0 : stack_is_full(struct stack *st) 58 : : { 59 : 0 : return st->top == st->max - 1; 60 : : } 61 : : 62 : : /* Add element x to the stack 63 : : */ 64 : : int 65 : 0 : stack_push(struct stack *st, uint32_t x) 66 : : { 67 [ # # ]: 0 : if (stack_is_full(st)) 68 : : return -EOVERFLOW; 69 : : 70 : : /* add an element and increments the top index 71 : : */ 72 : 0 : st->items[++st->top] = x; 73 : : 74 : 0 : return 0; 75 : : } 76 : : 77 : : /* Pop top element x from the stack and return 78 : : * in user provided location. 79 : : */ 80 : : int 81 : 0 : stack_pop(struct stack *st, uint32_t *x) 82 : : { 83 [ # # ]: 0 : if (stack_is_empty(st)) 84 : : return -ENOENT; 85 : : 86 : 0 : *x = st->items[st->top]; 87 : 0 : st->top--; 88 : : 89 : 0 : return 0; 90 : : } 91 : : 92 : : /* Dump the stack 93 : : */ 94 : 0 : void stack_dump(struct stack *st) 95 : : { 96 : : int i, j; 97 : : 98 : 0 : printf("top=%d\n", st->top); 99 : 0 : printf("max=%d\n", st->max); 100 : : 101 [ # # ]: 0 : if (st->top == -1) { 102 : : printf("stack is empty\n"); 103 : 0 : return; 104 : : } 105 : : 106 [ # # ]: 0 : for (i = 0; i < st->max + 7 / 8; i++) { 107 : 0 : printf("item[%d] 0x%08x", i, st->items[i]); 108 : : 109 [ # # ]: 0 : for (j = 0; j < 7; j++) { 110 [ # # ]: 0 : if (i++ < st->max - 1) 111 : 0 : printf(" 0x%08x", st->items[i]); 112 : : } 113 : : printf("\n"); 114 : : } 115 : : }