| ... | ... |
@@ -20,24 +20,26 @@ static int cmpchoice(const void *_idx1, const void *_idx2) {
|
| 20 | 20 |
|
| 21 | 21 |
static void choices_resize(choices_t *c, int new_capacity){
|
| 22 | 22 |
c->strings = realloc(c->strings, new_capacity * sizeof(const char *)); |
| 23 |
- c->results = realloc(c->results, new_capacity * sizeof(struct scored_position)); |
|
| 24 | 23 |
|
| 25 |
- if(!c->strings || !c->results){
|
|
| 24 |
+ if(!c->strings){
|
|
| 26 | 25 |
fprintf(stderr, "Error: Can't allocate memory\n"); |
| 27 | 26 |
abort(); |
| 28 | 27 |
} |
| 29 | 28 |
|
| 30 |
- for(int i = c->capacity; i < new_capacity; i++){
|
|
| 31 |
- c->strings[i] = NULL; |
|
| 32 |
- } |
|
| 33 | 29 |
c->capacity = new_capacity; |
| 34 | 30 |
} |
| 35 | 31 |
|
| 32 |
+static void choices_reset_search(choices_t *c){
|
|
| 33 |
+ free(c->results); |
|
| 34 |
+ c->selection = c->available = 0; |
|
| 35 |
+ c->results = NULL; |
|
| 36 |
+} |
|
| 37 |
+ |
|
| 36 | 38 |
void choices_init(choices_t *c){
|
| 37 | 39 |
c->strings = NULL; |
| 38 | 40 |
c->results = NULL; |
| 39 | 41 |
c->capacity = c->size = 0; |
| 40 |
- c->selection = c->available = 0; |
|
| 42 |
+ choices_reset_search(c); |
|
| 41 | 43 |
choices_resize(c, INITIAL_CAPACITY); |
| 42 | 44 |
} |
| 43 | 45 |
|
| ... | ... |
@@ -47,6 +49,9 @@ void choices_free(choices_t *c){
|
| 47 | 49 |
} |
| 48 | 50 |
|
| 49 | 51 |
void choices_add(choices_t *c, const char *choice){
|
| 52 |
+ /* Previous search is now invalid */ |
|
| 53 |
+ choices_reset_search(c); |
|
| 54 |
+ |
|
| 50 | 55 |
if(c->size == c->capacity){
|
| 51 | 56 |
choices_resize(c, c->capacity * 2); |
| 52 | 57 |
} |
| ... | ... |
@@ -58,8 +63,13 @@ size_t choices_available(choices_t *c){
|
| 58 | 63 |
} |
| 59 | 64 |
|
| 60 | 65 |
void choices_search(choices_t *c, const char *search){
|
| 61 |
- c->selection = 0; |
|
| 62 |
- c->available = 0; |
|
| 66 |
+ choices_reset_search(c); |
|
| 67 |
+ |
|
| 68 |
+ c->results = malloc(c->size * sizeof(struct scored_position)); |
|
| 69 |
+ if(!c->results){
|
|
| 70 |
+ fprintf(stderr, "Error: Can't allocate memory\n"); |
|
| 71 |
+ abort(); |
|
| 72 |
+ } |
|
| 63 | 73 |
|
| 64 | 74 |
for(size_t i = 0; i < c->size; i++){
|
| 65 | 75 |
if(has_match(search, c->strings[i])){
|