diff options
author | JSDurand <mmemmew@gmail.com> | 2022-01-12 20:26:08 +0800 |
---|---|---|
committer | JSDurand <mmemmew@gmail.com> | 2022-01-12 20:26:08 +0800 |
commit | 5730d6c04258e192195bfbbbed76d68fd78ed458 (patch) | |
tree | 92e64bd9576155000cf462ed1db3624e3bed3f8d /src/list.c | |
parent | 91016bd3855375796fd1eabd501ebc12491f2655 (diff) |
Implement a simple hash table.
It is a very basic and simple hash table. It is so simple that I
hesitate to call it a hash table. Anyways, I think it suffices for my
purposes here.
* Makefile.am: Add necessary files.
* grammar.c (new_tnt_string): Formatting.
* ht.c (new_ht): Constructor
(destroy_ht): Destructor
(ht_expand): Rehash
(ht_insert, ht_delete, ht_find): Main functions.
* list.c (add_to_list, list_assure_size): Modify the use of realloc.
* test/check_ht.c: Ensure this is working correctly.
* util.c (read_entire_file): Modify the use of realloc.
Diffstat (limited to 'src/list.c')
-rw-r--r-- | src/list.c | 43 |
1 files changed, 11 insertions, 32 deletions
@@ -39,8 +39,7 @@ add_to_list(List *ls, void *element) /* The capacity can be zero only when the list has been destroyed, in which case adding an element to that list is definitely an error. */ - eprintf("%s:%d, Adding an element to a destroyed list.\n", - __FILE__, __LINE__); + fleprintf0("Adding an element to a destroyed list.\n"); } (ls->len)++; @@ -55,30 +54,17 @@ add_to_list(List *ls, void *element) if (new_capacity >= ls->capacity + max_diff) new_capacity = ls->capacity + max_diff; - void **array = MYALLOC(void *, ls->capacity); - - if (array == NULL) { - ls->len -= 1; - return 1; - } - - for (NUM i = 0; i < ls->capacity; i++) - *(array+i) = *(ls->array+i); - /* The new_capacity will not be zero, so upon failure it returns NULL. */ - ls->array = realloc(ls->array, sizeof(void*) * new_capacity); + void **newarr = realloc(ls->array, sizeof(void*) * new_capacity); - if (ls->array == NULL) { + if (newarr == NULL) { + fleprintf0("Fail to realloc\n"); ls->len -= 1; - free(array); return 1; } - for (NUM i = 0; i < ls->capacity; i++) - *(ls->array+i) = *(array+i); - - free(array); + ls->array = newarr; for (NUM i = ls->capacity; i < new_capacity; i++) *(ls->array+i) = NULL; @@ -179,21 +165,14 @@ list_assure_size(List *ls, NUM size) { if (ls->capacity >= size) return 0; /* we are good */ - void **array = MYALLOC(void *, ls->capacity); + void **newarray = realloc(ls->array, sizeof(void*) * size); - if (array == NULL) return 1; - - for (NUM i = 0; i < ls->len; i++) - *(array+i) = *(ls->array+i); - - ls->array = realloc(ls->array, sizeof(void*) * size); - - if (ls->array == NULL) return 1; - - for (NUM i = 0; i < ls->len; i++) - *(ls->array+i) = *(array+i); + if (newarray == NULL) { + fleprintf0("Fail to realloc\n"); + return 1; + } - free(array); + ls->array = newarray; for (NUM i = ls->capacity; i < size; i++) *(ls->array+i) = NULL; |