exec: fix binary search

This commit is contained in:
Peter McGoron 2021-07-30 23:57:22 -04:00
parent 9b4ae3765b
commit f915a09e1a
3 changed files with 15 additions and 8 deletions

View File

@ -1,10 +1,13 @@
TESTS=test/input
TESTS=test/input test/exec
tests: $(TESTS)
for i in $(TESTS); do ./$$i -v; done
TEST_EXEC=test/exec.o exec.o
test/exec: $(TEST_EXEC)
$(CC) -Wall $(TEST_EXEC) -o test/exec
TEST_INPUT=test/input.o input.o
test/input: $(TEST_INPUT)
$(CC) -Wall $(TEST_INPUT) -o test/input
.c.o:
$(CC) -std=c89 -Wall -c $< -o $@
$(CC) -g -std=c89 -Wall -c $< -o $@

10
exec.c
View File

@ -15,13 +15,13 @@ int strcmp(const char *s1, const char *s2) {
# include <string.h>
#endif
struct libscomm_cmd *hg_bsearch(const char *name, 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;
while (upper <= lower) {
i = upper-lower/2;
while (upper >= lower) {
i = (upper - lower)/2 + lower;
rel = strcmp(name, cmds->arr[i].name);
/* x > cmds[i] */
if (rel > 0)
@ -35,10 +35,10 @@ struct libscomm_cmd *hg_bsearch(const char *name, struct libscomm_cmd_store *cmd
return NULL;
}
int libscomm_exec(const char *name, struct libscomm_cmd_store *cmds, struct libscomm_line *ln) {
int libscomm_exec(const struct libscomm_cmd_store *cmds, struct libscomm_line *ln) {
struct libscomm_cmd *cmd;
cmd = hg_bsearch(name, cmds);
cmd = hg_bsearch(ln->buf[ln->name], cmds);
if (!cmd)
return LIBSCOMM_NOT_FOUND;
return cmd->exec(ln);

6
exec.h
View File

@ -16,4 +16,8 @@ struct libscomm_cmd_store {
size_t len;
};
#define libscomm_mkcmds(l) {l, sizeof(l) / sizeof(l[0])}
#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])}
#endif
int libscomm_exec(const struct libscomm_cmd_store *cmds, struct libscomm_line *ln);