exec: split long lines and add user pointer

This commit is contained in:
Peter McGoron 2021-07-31 20:36:22 -04:00
parent c1f581eabf
commit 698df8abba
3 changed files with 23 additions and 17 deletions

8
exec.c
View File

@ -15,7 +15,8 @@ int strcmp(const char *s1, const char *s2) {
# include <string.h>
#endif
struct libscomm_cmd *hg_bsearch(const char *name, const struct libscomm_cmd_store *cmds) {
struct libscomm_cmd *hg_bsearch(const char *name,
const struct libscomm_cmd_store *cmds) {
size_t lower = 0, upper = cmds->len-1;
size_t i;
int rel;
@ -35,11 +36,12 @@ struct libscomm_cmd *hg_bsearch(const char *name, const struct libscomm_cmd_stor
return NULL;
}
int libscomm_exec(const struct libscomm_cmd_store *cmds, struct libscomm_line *ln) {
int libscomm_exec(const struct libscomm_cmd_store *cmds,
struct libscomm_line *ln, void *ptr) {
struct libscomm_cmd *cmd;
cmd = hg_bsearch(ln->buf[ln->name], cmds);
if (!cmd)
return LIBSCOMM_NOT_FOUND;
return cmd->exec(ln);
return cmd->exec(ln,ptr);
}

10
exec.h
View File

@ -8,7 +8,7 @@ enum libscomm_cmd_r {
struct libscomm_cmd {
const char *name;
int (*exec)(struct libscomm_line *);
int (*exec)(struct libscomm_line *, void *);
};
struct libscomm_cmd_store {
@ -18,6 +18,10 @@ struct libscomm_cmd_store {
#if defined(__STDC_VERSION__)
#define libscomm_mkcmds(...) {(struct libscomm_cmd []){__VA_ARGS__}, \
sizeof((struct libscomm_cmd []){__VA_ARGS__}) / sizeof((struct libscomm_cmd []){__VA_ARGS__}[0])}
sizeof((struct libscomm_cmd []){__VA_ARGS__}) / \
sizeof((struct libscomm_cmd []){__VA_ARGS__}[0])}
#endif
int libscomm_exec(const struct libscomm_cmd_store *cmds, struct libscomm_line *ln);
int libscomm_exec(const struct libscomm_cmd_store *cmds,
struct libscomm_line *ln,
void *ptr
);

View File

@ -2,7 +2,8 @@
#include "../exec.h"
#define mkfun(f, n) \
int f(struct libscomm_line *x __attribute__((unused))) { \
int f(struct libscomm_line *x __attribute__((unused)), \
void *ptr __attribute__((unused))) { \
return n; \
}
@ -27,20 +28,19 @@ struct libscomm_cmd cmdarr[] = {
#define arrlen(x) (sizeof(x) / sizeof((x)[0]))
const struct libscomm_cmd_store cmds = {cmdarr, arrlen(cmdarr)};
TEST execute_one(void) {
struct libscomm_line x = {0};
x.buf[0] = "foo";
x.len = 1;
ASSERT_EQ(libscomm_exec(&cmds, &x), LIBSCOMM_CMD_OK);
PASS();
}
#define doexec(f, n) do{\
x.buf[0] = f; \
ASSERT_EQ(libscomm_exec(&cmds, &x), n); \
ASSERT_EQ(libscomm_exec(&cmds, &x, NULL), n); \
} while(0)
TEST execute_one(void) {
struct libscomm_line x = {0};
x.len = 1;
doexec("foo", LIBSCOMM_CMD_OK);
PASS();
}
TEST execute_multiple(void) {
struct libscomm_line x = {0};
x.len = 1;