Browse code

Fix divide by zero on empty choices list

John Hawthorn authored on 15/09/2014 03:26:09
Showing 3 changed files

... ...
@@ -10,7 +10,7 @@ INSTALL_DATA=${INSTALL} -m 644
10 10
 
11 11
 all: fzy fzytest
12 12
 
13
-fzytest: fzytest.o match.o
13
+fzytest: fzytest.o match.o choices.o
14 14
 	$(CC) $(CFLAGS) $(CCFLAGS) -o $@ $^
15 15
 
16 16
 test: fzytest
... ...
@@ -80,10 +80,12 @@ double choices_getscore(choices_t *c, size_t n){
80 80
 }
81 81
 
82 82
 void choices_prev(choices_t *c){
83
-	c->selection = (c->selection + c->available - 1) % c->available;
83
+	if(c->available)
84
+		c->selection = (c->selection + c->available - 1) % c->available;
84 85
 }
85 86
 
86 87
 void choices_next(choices_t *c){
87
-	c->selection = (c->selection + 1) % c->available;
88
+	if(c->available)
89
+		c->selection = (c->selection + 1) % c->available;
88 90
 }
89 91
 
... ...
@@ -1,5 +1,7 @@
1 1
 #include <stdio.h>
2
+
2 3
 #include "match.h"
4
+#include "choices.h"
3 5
 
4 6
 int testsrun = 0, testsfailed = 0, assertionsrun = 0;
5 7
 
... ...
@@ -109,6 +111,23 @@ int test_positions_exact(){
109 111
 	return 0;
110 112
 }
111 113
 
114
+int test_empty_choices(){
115
+	choices_t choices;
116
+	choices_init(&choices);
117
+	assert(choices.size == 0);
118
+	assert(choices.available == 0);
119
+	assert(choices.selection == 0);
120
+
121
+	choices_prev(&choices);
122
+	assert(choices.selection == 0);
123
+
124
+	choices_next(&choices);
125
+	assert(choices.selection == 0);
126
+
127
+	choices_free(&choices);
128
+	return 0;
129
+}
130
+
112 131
 void summary(){
113 132
 	printf("%i tests, %i assertions, %i failures\n", testsrun, assertionsrun, testsfailed);
114 133
 }
... ...
@@ -125,6 +144,8 @@ int main(int argc, char *argv[]){
125 144
 	runtest(test_positions_4);
126 145
 	runtest(test_positions_exact);
127 146
 
147
+	runtest(test_empty_choices);
148
+
128 149
 	summary();
129 150
 
130 151
 	/* exit 0 if all tests pass */