Use temp hack in htable_free_*()
[eleutheria.git] / misc / fsm / fsm.c
blobe0769a8a5439d953f1be90b626d86d095380e05f
1 #include "fsm.h"
2 #include "types.h"
4 #include <stdio.h>
5 #include <stdlib.h>
6 #include <string.h>
8 /* Callback funtions prototypes */
9 static unsigned int fsm_hashf(const void *key);
10 static int fsm_cmpf(const void *arg1, const void *arg2);
11 static void fsm_printf(const void *key, const void *data);
13 fsmret_t fsm_init(fsm_t **fsm, size_t size, unsigned int factor)
15 /* Allocate memory fsm's state table */
16 if ((*fsm = malloc(sizeof *fsm)) == NULL)
17 return FSM_NOMEM;
19 if (((*fsm)->sttable = malloc(sizeof *(*fsm)->sttable)) == NULL) {
20 free(*fsm);
21 return FSM_NOMEM;
24 if (htable_init((*fsm)->sttable, size, factor,
25 fsm_hashf, fsm_cmpf, fsm_printf) == HT_NOMEM) {
26 free((*fsm)->sttable);
27 free(*fsm);
28 return FSM_NOMEM;
31 return FSM_OK;
34 fsmret_t fsm_add_state(fsm_t *fsm, unsigned int key, state_t *state)
36 unsigned int *pkey;
38 /* Allocate memory for new key */
39 if ((pkey = malloc(sizeof *pkey)) == NULL)
40 return FSM_NOMEM;
42 *pkey = key;
44 /* Insert event to hash table */
45 if (htable_insert(fsm->sttable, pkey, state) == HT_EXISTS) {
46 free(pkey);
47 return FSM_EXISTS;
50 return FSM_OK;
53 fsmret_t fsm_free(fsm_t *fsm)
55 htable_free_all_obj(fsm->sttable, 0);
56 htable_free(fsm->sttable);
57 free(fsm->sttable);
58 free(fsm);
60 return FSM_OK;
63 void fsm_print_states(const fsm_t *fsm)
65 htable_print(fsm->sttable);
68 /* Callback funtions */
69 static unsigned int fsm_hashf(const void *key)
71 return *(const unsigned int *)key;
74 static int fsm_cmpf(const void *arg1, const void *arg2)
76 unsigned int a = *(const unsigned int *)arg1;
77 unsigned int b = *(const unsigned int *)arg2;
79 if (a > b)
80 return -1;
81 else if (a == b)
82 return 0;
83 else
84 return 1;
87 static void fsm_printf(const void *key, const void *data)
89 printf("key: %d ",
90 *(const unsigned int *)key);