#include "dispatch.h" #include #include static const char *skip_space(const char *text) { while (*text != '\0' && isspace((unsigned char)*text)) { text += 1; } return text; } static int at_end(const char *text) { return *text == '\0' || *text == '#'; } static int parse_integer(const char **cursor, int *value) { const char *text = *cursor; unsigned magnitude = 0; unsigned limit; int negative = 0; int digits = 0; if (*text == '+' || *text == '-') { negative = *text == '-'; text += 1; } limit = negative ? (unsigned)INT_MAX + 1u : (unsigned)INT_MAX; while (*text >= '0' && *text <= '9') { unsigned digit = (unsigned)(*text - '0'); if (magnitude > (limit - digit) / 10u) { return -1; } magnitude = magnitude * 10u + digit; text += 1; digits = 1; } if (!digits) { return -1; } if (!at_end(text) && !isspace((unsigned char)*text)) { return -1; } if (negative && magnitude == (unsigned)INT_MAX + 1u) { *value = INT_MIN; } else if (negative) { *value = -(int)magnitude; } else { *value = (int)magnitude; } *cursor = text; return 0; } int command_parse(const char *line, Command *command) { const char *text = skip_space(line); unsigned index; command->op = '?'; command->argc = 0; for (index = 0; index < COMMAND_ARGS; ++index) { command->arg[index] = 0; } if (at_end(text)) { return 0; } command->op = *text; text += 1; if (!at_end(text) && !isspace((unsigned char)*text)) { return -1; } text = skip_space(text); while (!at_end(text)) { if (command->argc == COMMAND_ARGS) { return -1; } if (parse_integer(&text, &command->arg[command->argc]) != 0) { return -1; } command->argc += 1; text = skip_space(text); } return 1; }