Here is some code I have that has been extracted and shrunk down from a project of mine.
#include <stdio.h>
#include <stdint.h>
#include <time.h>
#include <string.h>
#define streq(x, y) (strcmp((x), (y)) == 0)
#define ARRAY_SIZE(x) (sizeof(x)/sizeof(x[0]))
typedef struct
{
const char *cmd;
void* (*fn)(void);
} __attribute__((__packed__)) Command;
void* getTime(void)
{
return ((void*)((uintptr_t)time(NULL)));
}
void* getDay(void)
{
time_t t = time(NULL);
struct tm tm = *localtime(&t);
return ((void*)((uintptr_t)(tm.tm_wday)));
}
static Command commands[] =
{
{"time", getTime},
{"day", getDay},
};
int main(int argc, char *argv[])
{
for (int i = 0; i < ARRAY_SIZE(commands); ++i)
{
Command *p = commands+i;
if (streq(argv[1], p->cmd)) printf("%d\n", (int)p->fn());
}
}
When run with some given input, it runs the method associated with that input. Since this is a scaled down version of my project, it can only run two commands.
$ ./test-command day
4
Right now, my implementation should run with \$ O \left( n\right)\$ time complexity. This would be unacceptable with the hundreds of thousands of commands my project could scale to. I am looking for reviews on scalability and optimization, and how well my Command structure and function pointer template would scale as well.