Add some comments plus fix a possible mem leak
[eleutheria.git] / misc / fsm / states.c
blobcdf55c6cd0286d5ceab7f2219c4478eab1bc03e3
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 /* Allocate memory for state's key */
32 if (((*state)->st_key = malloc(sizeof *(*state)->st_key)) == NULL) {
33 free((*state)->evttable);
34 free(*state);
35 return ST_NOMEM;
38 return ST_OK;
41 stret_t state_add_evt(state_t *state, unsigned int key, const char *desc, void (*actionf)(void *data), state_t *newstate)
43 event_t *pevt;
44 unsigned int *pkey;
46 /* Allocate memory for new key */
47 if ((pkey = malloc(sizeof *pkey)) == NULL)
48 return ST_NOMEM;
50 *pkey = key;
52 /* Allocate memory for new event */
53 if ((pevt = malloc(sizeof *pevt)) == NULL) {
54 free(pkey);
55 return ST_NOMEM;
58 /* Fill in structure's members */
59 strncpy(pevt->evt_desc, desc, MAX_EVT_DESC);
60 pevt->evt_actionf = actionf;
61 pevt->evt_newstate = newstate;
63 /* Insert event to hash table */
64 if (htable_insert(state->evttable, pkey, pevt) == HT_EXISTS) {
65 free(pkey);
66 free(pevt);
67 return ST_EXISTS;
70 return ST_OK;
73 stret_t state_rem_evt(state_t *state, unsigned int key)
75 if (htable_free_obj(state->evttable, &key, HT_FREEKEY | HT_FREEDATA) == HT_NOTFOUND)
76 return ST_NOTFOUND;
78 return ST_OK;
81 unsigned int state_get_key(state_t *state)
83 return *state->st_key;
86 stret_t state_free(state_t *state)
88 htable_free_all_obj(state->evttable, HT_FREEKEY | HT_FREEDATA);
89 htable_free(state->evttable);
90 free(state->evttable);
91 free(state);
93 return ST_OK;
96 void state_print_evts(const state_t *state)
98 htable_print(state->evttable);
101 /* Callback funtions */
102 static unsigned int state_hashf(const void *key)
104 return *(const unsigned int *)key;
107 static int state_cmpf(const void *arg1, const void *arg2)
109 unsigned int a = *(const unsigned int *)arg1;
110 unsigned int b = *(const unsigned int *)arg2;
112 if (a > b)
113 return -1;
114 else if (a == b)
115 return 0;
116 else
117 return 1;
120 static void state_printf(const void *key, const void *data)
122 printf("key: %u\tdesc: %s ",
123 *(const unsigned int *)key,
124 ((const event_t *)data)->evt_desc);