From 63274ac7f99c516b88bd1f94e05e5c715a4800ce Mon Sep 17 00:00:00 2001 From: Nick Bowler Date: Tue, 12 Jul 2011 20:41:15 -0400 Subject: [PATCH] Avoid modifying the input command string. This gives the individual command functions access to the entire (unadultered) input from the user. --- src/cdecl99.c | 39 ++++++++++++++++++++++++++------------- 1 file changed, 26 insertions(+), 13 deletions(-) diff --git a/src/cdecl99.c b/src/cdecl99.c index 5c67ed8..2df7ec8 100644 --- a/src/cdecl99.c +++ b/src/cdecl99.c @@ -92,7 +92,7 @@ retry: return buf; } -static int cmd_explain(char *cmd, char *arg) +static int cmd_explain(const char *cmd, const char *arg) { struct cdecl *decl; const char *str; @@ -116,7 +116,7 @@ out: return ret; } -static int cmd_simplify(char *cmd, char *arg) +static int cmd_simplify(const char *cmd, const char *arg) { struct cdecl *decl; const char *str; @@ -151,16 +151,16 @@ out: return ret; } -static int cmd_quit(char *cmd, char *arg) +static int cmd_quit(const char *cmd, const char *arg) { return 0; } -static int cmd_help(char *cmd, char *arg); +static int cmd_help(const char *cmd, const char *arg); static const struct command { char name[16]; - int (*func)(char *cmd, char *arg); + int (*func)(const char *cmd, const char *arg); const char *blurb; } commands[] = { { "explain", cmd_explain, "Explain a C declaration." }, @@ -171,7 +171,7 @@ static const struct command { }; static const size_t ncommands = sizeof commands / sizeof commands[0]; -static int cmd_help(char *cmd, char *arg) +static int cmd_help(const char *cmd, const char *arg) { for (size_t i = 0; i < ncommands; i++) { if (!commands[i].blurb) @@ -183,24 +183,37 @@ static int cmd_help(char *cmd, char *arg) return 1; } -static int run_command(char *line) +/* + * Ensure that the first n characters of str equal the entire (null-terminated) + * string cmd. + */ +static int cmd_cmp(const char *str, const char *cmd, size_t n) +{ + size_t cmdlen = strlen(cmd); + + if (n < cmdlen) + return -1; + if (n > cmdlen) + return 1; + return memcmp(str, cmd, n); +} + +static int run_command(const char *line) { - char *cmd = line + strspn(line, " \t"); - char *arg = cmd + strcspn(cmd, " \t"); + const char *cmd = line + strspn(line, " \t"); + const char *arg = cmd + strcspn(cmd, " \t"); if (cmd[0] == '\0') return 1; - if (arg[0] != '\0') - *arg++ = '\0'; for (size_t i = 0; i < ncommands; i++) { - if (strcmp(cmd, commands[i].name) != 0) + if (cmd_cmp(cmd, commands[i].name, arg-cmd) != 0) continue; return commands[i].func(cmd, arg); } - fprintf(stderr, "Undefined command: %s\n", cmd); + fprintf(stderr, "Undefined command: %.*s\n", (int)(arg-cmd), cmd); return -1; } -- 2.43.2