trigger update
[henge/webcc.git] / src / core / trigger.h
1 /*!@file
2 \brief Trigger Mechanism
3 \details includes a small, 15 (by default) element list of function pointers
4 that may be registered and triggered like a stack of functions.
5 Useful for synchronizing function calls.
6
7 Usage example:
8 #include <trigger.h>
9
10 void trigger_test(void);
11
12 extern void hack_the_planet(void);
13 extern void hack_the_plants(void);
14 extern void hack_robert_plant(void);
15
16 void
17 trigger_test()
18 { TRIGGER_SET(hack_the_planet);
19 TRIGGER_SET(hack_the_plants);
20 TRIGGER_SET(hack_robert_plant);
21
22 //Don't worry robert!
23 TRIGGER_POP();
24
25 TRIGGER();
26 }
27
28 Advanced Usage Example:
29 #define MAX_TRIGGER_FUNCS 2
30 #define TRIGGERS kill_trigger flush_trigger
31 #include <trigger.h>
32 #include <hack_functions.h>
33
34 void
35 advanced_trigger_test()
36 { TRIGGER_SET(kill_trigger, hack_the_planet);
37 TRIGGER_SET(kill_trigger, hack_the_missiles);
38 TRIGGER_SET(flush_trigger, hack_the_government);
39 TRIGGER_SET(flush trigger, hack_my_tax_bill);
40
41 if (robert_plant_hacked())
42 { TRIGGER(kill_trigger);
43
44 TRIGGER_POP(flush_trigger);
45 TRIGGER_SET(flush_trigger, hack_the_missile_defenses);
46 }
47 TRIGGER(flush_trigger);
48 }
49
50
51 \author K
52 \date 2016
53 -----------------------------------------------------------------------------*/
54
55 #ifndef _TRIGGER_H_
56 #define _TRIGGER_H_
57
58 /** The number of trigger functions per trigger */
59 #ifndef MAX_TRIGGER_FUNCS
60 #define MAX_TRIGGER_FUNCS 15
61 #endif
62
63 /* Internal macro prototypes */
64 #define _TRIGGER_DEL(TARG) --TARG.num_funcs
65 #define _TRIGGER_POP(TARG) (TARG.func[_TRIGGER_DEL(TARG)])()
66 #define _TRIGGER_SET(TARG, FUNC) TARG.func[TARG.num_funcs++] = FUNC
67 #define _TRIGGER(TARG) while(TARG.num_funcs) TRIGGER_POP(TARG)
68
69 /* If TRIGGERS is not defined, use only a default trigger and define shorthand
70 functions for easy use. */
71 #ifndef TRIGGERS
72 #define TRIGGERS default_trigger
73 #define TRIGGER_DEL() _TRIGGER_DEL(default_trigger)
74 #define TRIGGER_POP() _TRIGGER_POP(default_trigger)
75 #define TRIGGER_SET(FUNC) _TRIGGER_SET(default_trigger, FUNC)
76 #define TRIGGER() _TRIGGER(default_trigger)
77 #else
78 #define TRIGGER_DEL(TARG) _TRIGGER_DEL(TARG)
79 #define TRIGGER_POP(TARG) _TRIGGER_POP(TARG)
80 #define TRIGGER_SET(TARG,FUNC) _TRIGGER_SET(TARG,FUNC)
81 #define TRIGGER(TARG) _TRIGGER(TARG)
82 #endif
83
84 static struct call_trigger
85 { int num_funcs;
86 void (*func[MAX_TRIGGER_FUNCS])(void);
87 } TRIGGERS;
88
89 #endif //_TRIGGER_H_