Implementing a basic jump table for dynamic command parsing 04-17-2018, 04:43 PM
#1
So, was in a PM with another member who was complaining about having to have a massive command parser with a shitload of if-strncmp's in it. I gave him this C code to solve that problem and be more clean, maybe you guys will like it as well:
Code:
#define ALLOWED_COMMANDS 2
void helpfunc(void)
{
  printf("help message\n");
}
void clearfunc(void)
{
  // some clear function
}
struct jmp_tbl_s
{
  const char *command;
  void (*handler)(void);
} jump_table[ALLOWED_COMMANDS] =
{
  (struct jmp_tbl_s)
  {
    .command = "help",
    .handler = &helpfunc
  },
  (struct jmp_tbl_s)
  {
    .command = "clear",
    .handler = &clearfunc
  }
};
void processCommand(const char *command)
{
  int i;
  size_t cmdlen;
  const size_t len = strlen(command);
  for (i = 0; i < ALLOWED_COMMANDS; ++i)
  {
    cmdlen = strlen(jump_table[i].command);
    if (!strncpy(jump_table[i].command, command, len > cmdlen ? cmdlen : len))
    {
      *(jump_table[i].handler)();
      break;
    }
  }
}

























![[+]](https://sinister.ly/images/modern/collapse_collapsed.png)

