From 8417e77d7b60c220f28ac25f2812ea79509dfd99 Mon Sep 17 00:00:00 2001 From: John Hawthorn Date: Sun, 14 Sep 2014 20:26:09 -0700 Subject: Fix divide by zero on empty choices list --- Makefile | 2 +- choices.c | 6 ++++-- fzytest.c | 21 +++++++++++++++++++++ 3 files changed, 26 insertions(+), 3 deletions(-) diff --git a/Makefile b/Makefile index 37f9b54..25fc0ea 100644 --- a/Makefile +++ b/Makefile @@ -10,7 +10,7 @@ INSTALL_DATA=${INSTALL} -m 644 all: fzy fzytest -fzytest: fzytest.o match.o +fzytest: fzytest.o match.o choices.o $(CC) $(CFLAGS) $(CCFLAGS) -o $@ $^ test: fzytest diff --git a/choices.c b/choices.c index 9681de9..933b8a0 100644 --- a/choices.c +++ b/choices.c @@ -80,10 +80,12 @@ double choices_getscore(choices_t *c, size_t n){ } void choices_prev(choices_t *c){ - c->selection = (c->selection + c->available - 1) % c->available; + if(c->available) + c->selection = (c->selection + c->available - 1) % c->available; } void choices_next(choices_t *c){ - c->selection = (c->selection + 1) % c->available; + if(c->available) + c->selection = (c->selection + 1) % c->available; } diff --git a/fzytest.c b/fzytest.c index cc20d0e..285975a 100644 --- a/fzytest.c +++ b/fzytest.c @@ -1,5 +1,7 @@ #include + #include "match.h" +#include "choices.h" int testsrun = 0, testsfailed = 0, assertionsrun = 0; @@ -109,6 +111,23 @@ int test_positions_exact(){ return 0; } +int test_empty_choices(){ + choices_t choices; + choices_init(&choices); + assert(choices.size == 0); + assert(choices.available == 0); + assert(choices.selection == 0); + + choices_prev(&choices); + assert(choices.selection == 0); + + choices_next(&choices); + assert(choices.selection == 0); + + choices_free(&choices); + return 0; +} + void summary(){ printf("%i tests, %i assertions, %i failures\n", testsrun, assertionsrun, testsfailed); } @@ -125,6 +144,8 @@ int main(int argc, char *argv[]){ runtest(test_positions_4); runtest(test_positions_exact); + runtest(test_empty_choices); + summary(); /* exit 0 if all tests pass */ -- cgit v1.2.3