utstack.h (3313B)
1 /* 2 Copyright (c) 2018-2022, Troy D. Hanson https://troydhanson.github.io/uthash/ 3 All rights reserved. 4 5 Redistribution and use in source and binary forms, with or without 6 modification, are permitted provided that the following conditions are met: 7 8 * Redistributions of source code must retain the above copyright 9 notice, this list of conditions and the following disclaimer. 10 11 THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS 12 IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED 13 TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A 14 PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER 15 OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, 16 EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, 17 PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR 18 PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF 19 LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING 20 NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS 21 SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. 22 */ 23 24 #ifndef UTSTACK_H 25 #define UTSTACK_H 26 27 #define UTSTACK_VERSION 2.3.0 28 29 /* 30 * This file contains macros to manipulate a singly-linked list as a stack. 31 * 32 * To use utstack, your structure must have a "next" pointer. 33 * 34 * ----------------.EXAMPLE ------------------------- 35 * struct item { 36 * int id; 37 * struct item *next; 38 * }; 39 * 40 * struct item *stack = NULL; 41 * 42 * int main() { 43 * int count; 44 * struct item *tmp; 45 * struct item *item = malloc(sizeof *item); 46 * item->id = 42; 47 * STACK_COUNT(stack, tmp, count); assert(count == 0); 48 * STACK_PUSH(stack, item); 49 * STACK_COUNT(stack, tmp, count); assert(count == 1); 50 * STACK_POP(stack, item); 51 * free(item); 52 * STACK_COUNT(stack, tmp, count); assert(count == 0); 53 * } 54 * -------------------------------------------------- 55 */ 56 57 #define STACK_TOP(head) (head) 58 59 #define STACK_EMPTY(head) (!(head)) 60 61 #define STACK_PUSH(head,add) \ 62 STACK_PUSH2(head,add,next) 63 64 #define STACK_PUSH2(head,add,next) \ 65 do { \ 66 (add)->next = (head); \ 67 (head) = (add); \ 68 } while (0) 69 70 #define STACK_POP(head,result) \ 71 STACK_POP2(head,result,next) 72 73 #define STACK_POP2(head,result,next) \ 74 do { \ 75 (result) = (head); \ 76 (head) = (head)->next; \ 77 } while (0) 78 79 #define STACK_COUNT(head,el,counter) \ 80 STACK_COUNT2(head,el,counter,next) \ 81 82 #define STACK_COUNT2(head,el,counter,next) \ 83 do { \ 84 (counter) = 0; \ 85 for ((el) = (head); el; (el) = (el)->next) { ++(counter); } \ 86 } while (0) 87 88 #endif /* UTSTACK_H */