exec: fix binary search
This commit is contained in:
parent
9b4ae3765b
commit
f915a09e1a
7
Makefile
7
Makefile
|
@ -1,10 +1,13 @@
|
||||||
TESTS=test/input
|
TESTS=test/input test/exec
|
||||||
|
|
||||||
tests: $(TESTS)
|
tests: $(TESTS)
|
||||||
for i in $(TESTS); do ./$$i -v; done
|
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.o input.o
|
||||||
test/input: $(TEST_INPUT)
|
test/input: $(TEST_INPUT)
|
||||||
$(CC) -Wall $(TEST_INPUT) -o test/input
|
$(CC) -Wall $(TEST_INPUT) -o test/input
|
||||||
.c.o:
|
.c.o:
|
||||||
$(CC) -std=c89 -Wall -c $< -o $@
|
$(CC) -g -std=c89 -Wall -c $< -o $@
|
||||||
|
|
10
exec.c
10
exec.c
|
@ -15,13 +15,13 @@ int strcmp(const char *s1, const char *s2) {
|
||||||
# include <string.h>
|
# include <string.h>
|
||||||
#endif
|
#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 lower = 0, upper = cmds->len-1;
|
||||||
size_t i;
|
size_t i;
|
||||||
int rel;
|
int rel;
|
||||||
|
|
||||||
while (upper <= lower) {
|
while (upper >= lower) {
|
||||||
i = upper-lower/2;
|
i = (upper - lower)/2 + lower;
|
||||||
rel = strcmp(name, cmds->arr[i].name);
|
rel = strcmp(name, cmds->arr[i].name);
|
||||||
/* x > cmds[i] */
|
/* x > cmds[i] */
|
||||||
if (rel > 0)
|
if (rel > 0)
|
||||||
|
@ -35,10 +35,10 @@ struct libscomm_cmd *hg_bsearch(const char *name, struct libscomm_cmd_store *cmd
|
||||||
return NULL;
|
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;
|
struct libscomm_cmd *cmd;
|
||||||
|
|
||||||
cmd = hg_bsearch(name, cmds);
|
cmd = hg_bsearch(ln->buf[ln->name], cmds);
|
||||||
if (!cmd)
|
if (!cmd)
|
||||||
return LIBSCOMM_NOT_FOUND;
|
return LIBSCOMM_NOT_FOUND;
|
||||||
return cmd->exec(ln);
|
return cmd->exec(ln);
|
||||||
|
|
6
exec.h
6
exec.h
|
@ -16,4 +16,8 @@ struct libscomm_cmd_store {
|
||||||
size_t len;
|
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);
|
||||||
|
|
Loading…
Reference in New Issue