libsepol: hashtab: save one comparison on hit

When the comparison function returns 0, avoid a repeated call to it.

Signed-off-by: Christian Göttsche <cgzones@googlemail.com>
Acked-by: James Carter <jwcart2@gmail.com>
This commit is contained in:
Christian Göttsche 2024-06-08 19:19:23 +02:00 committed by James Carter
parent fd08019984
commit a3332e5741

View File

@ -112,15 +112,17 @@ int hashtab_insert(hashtab_t h, hashtab_key_t key, hashtab_datum_t datum)
hashtab_check_resize(h);
hvalue = h->hash_value(h, key);
prev = NULL;
cur = h->htable[hvalue];
while (cur && h->keycmp(h, key, cur->key) > 0) {
prev = cur;
cur = cur->next;
}
if (cur && (h->keycmp(h, key, cur->key) == 0))
return SEPOL_EEXIST;
for (prev = NULL, cur = h->htable[hvalue]; cur; prev = cur, cur = cur->next) {
int cmp;
cmp = h->keycmp(h, key, cur->key);
if (cmp > 0)
continue;
if (cmp == 0)
return SEPOL_EEXIST;
break;
}
newnode = (hashtab_ptr_t) malloc(sizeof(hashtab_node_t));
if (newnode == NULL)
@ -151,14 +153,19 @@ int hashtab_remove(hashtab_t h, hashtab_key_t key,
return SEPOL_ENOENT;
hvalue = h->hash_value(h, key);
last = NULL;
cur = h->htable[hvalue];
while (cur != NULL && h->keycmp(h, key, cur->key) > 0) {
last = cur;
cur = cur->next;
for (last = NULL, cur = h->htable[hvalue]; cur; last = cur, cur = cur->next) {
int cmp;
cmp = h->keycmp(h, key, cur->key);
if (cmp > 0)
continue;
if (cmp == 0)
break;
return SEPOL_ENOENT;
}
if (cur == NULL || (h->keycmp(h, key, cur->key) != 0))
if (cur == NULL)
return SEPOL_ENOENT;
if (last == NULL)
@ -183,14 +190,18 @@ hashtab_datum_t hashtab_search(hashtab_t h, const_hashtab_key_t key)
return NULL;
hvalue = h->hash_value(h, key);
cur = h->htable[hvalue];
while (cur != NULL && h->keycmp(h, key, cur->key) > 0)
cur = cur->next;
for (cur = h->htable[hvalue]; cur; cur = cur->next) {
int cmp;
if (cur == NULL || (h->keycmp(h, key, cur->key) != 0))
return NULL;
cmp = h->keycmp(h, key, cur->key);
if (cmp > 0)
continue;
if (cmp == 0)
return cur->datum;
break;
}
return cur->datum;
return NULL;
}
void hashtab_destroy(hashtab_t h)