Use temp hack in htable_free_*()
[eleutheria.git] / misc / fsm / states.c
blob1a0eb98510ad938d49f1dc92654ebed90d69459f
1 #include "types.h"
2 #include "states.h"
4 #include <stdio.h>
5 #include <stdlib.h>
6 #include <string.h>
8 /* Callback functions prototypes */
9 static unsigned int state_hashf(const void *key);
10 static int state_cmpf(const void *arg1, const void *arg2);
11 static void state_printf(const void *key, const void *data);
13 stret_t state_init(state_t **state, size_t size, unsigned int factor)
15 /* Allocate memory state's event table */
16 if ((*state = malloc(sizeof *state)) == NULL)
17 return ST_NOMEM;
19 if (((*state)->evttable = malloc(sizeof *(*state)->evttable)) == NULL) {
20 free(*state);
21 return ST_NOMEM;
24 if (htable_init((*state)->evttable, size, factor,
25 state_hashf, state_cmpf, state_printf) == HT_NOMEM) {
26 free((*state)->evttable);
27 free(*state);
28 return ST_NOMEM;
31 return ST_OK;
34 stret_t state_add_evt(state_t *state, unsigned int key, const char *desc, void (*actionf)(void *data), state_t *newstate)
36 event_t *pevt;
37 unsigned int *pkey;
39 /* Allocate memory for new key */
40 if ((pkey = malloc(sizeof *pkey)) == NULL)
41 return ST_NOMEM;
43 *pkey = key;
45 /* Allocate memory for new event */
46 if ((pevt = malloc(sizeof *pevt)) == NULL) {
47 free(pkey);
48 return ST_NOMEM;
51 /* Fill in structure's members */
52 strncpy(pevt->evt_desc, desc, MAX_EVT_DESC);
53 pevt->evt_actionf = actionf;
54 pevt->evt_newstate = newstate;
56 /* Insert event to hash table */
57 if (htable_insert(state->evttable, pkey, pevt) == HT_EXISTS) {
58 free(pkey);
59 free(pevt);
60 return ST_EXISTS;
63 return ST_OK;
66 stret_t state_rem_evt(state_t *state, unsigned int key)
68 if (htable_free_obj(state->evttable, &key) == HT_NOTFOUND)
69 return ST_NOTFOUND;
71 return ST_OK;
74 stret_t state_free(state_t *state)
76 htable_free_all_obj(state->evttable, 2);
77 htable_free(state->evttable);
78 free(state->evttable);
79 free(state);
81 return ST_OK;
84 void state_print_evts(const state_t *state)
86 htable_print(state->evttable);
89 /* Callback funtions */
90 static unsigned int state_hashf(const void *key)
92 return *(const unsigned int *)key;
95 static int state_cmpf(const void *arg1, const void *arg2)
97 unsigned int a = *(const unsigned int *)arg1;
98 unsigned int b = *(const unsigned int *)arg2;
100 if (a > b)
101 return -1;
102 else if (a == b)
103 return 0;
104 else
105 return 1;
108 static void state_printf(const void *key, const void *data)
110 printf("key: %d\tdesc: %s ",
111 *(const unsigned int *)key,
112 ((const event_t *)data)->evt_desc);