shithub: sl

Download patch

ref: 6d46176da4835180f7dc317df5179de9ce8d9dc0
parent: 83185ad9f68ed39250938c91877deedb16cb67d6
author: Sigrid Solveig Haflínudóttir <sigrid@ftrv.se>
date: Thu Jan 2 00:37:03 EST 2025

htable_new, htable_reset: slight rewrite for readability

--- a/htable.c
+++ b/htable.c
@@ -10,21 +10,19 @@
 htable_new(htable_t *h, size_t size)
 {
 	if(size <= HT_N_INLINE/2){
-		h->size = size = HT_N_INLINE;
+		size = HT_N_INLINE;
 		h->table = &h->_space[0];
 	}else{
 		size = nextipow2(size);
 		size *= 2; // 2 pointers per key/value pair
 		size *= 2; // aim for 50% occupancy
-		h->size = size;
-		h->table = MEM_ALLOC(size*sizeof(void*));
+		h->table = MEM_ALLOC(size * sizeof(*h->table));
 	}
-	if(h->table == nil)
-		return nil;
-	size_t i;
-	for(i = 0; i < size; i++)
-		h->table[i] = HT_NOTFOUND;
+	assert(h->table != nil);
+	h->size = size;
 	h->i = 0;
+	for(size_t i = 0; i < size; i++)
+		h->table[i] = HT_NOTFOUND;
 	return h;
 }
 
@@ -40,15 +38,11 @@
 htable_reset(htable_t *h, size_t sz)
 {
 	sz = nextipow2(sz);
-	if(h->size > sz*4 && h->size > HT_N_INLINE){
-		size_t newsz = sz*4;
-		void **newtab = MEM_REALLOC(h->table, newsz*sizeof(void*));
-		if(newtab == nil)
-			return;
-		h->size = newsz;
-		h->table = newtab;
+	if(h->size > sz*4 && h->table != &h->_space[0]){
+		MEM_FREE(h->table);
+		htable_new(h, sz);
+	}else{
+		for(size_t i = 0, hsz = h->size; i < hsz; i++)
+			h->table[i] = HT_NOTFOUND;
 	}
-	size_t i, hsz = h->size;
-	for(i = 0; i < hsz; i++)
-		h->table[i] = HT_NOTFOUND;
 }