Add a lookup-and-return-default-value method

This commit is contained in:
ntchambers 2018-06-19 15:13:51 -05:00
parent d1ef28b489
commit 2ee28fcd97
2 changed files with 17 additions and 0 deletions

View File

@ -12,6 +12,7 @@ struct hashmap {
struct hashmap new_map();
void insert_map(struct hashmap *map, const char *key, const void *value);
const void *lookup_map(struct hashmap *map, const char *key);
const void *lookup_map_default(struct hashmap *map, const char *key, const void *default_value);
int exists_map(struct hashmap *map, const char *key);
const void *remove_map(struct hashmap *map, const char *key);
void foreach_map(struct hashmap *map, void (*cb)(const char *key, const void *value));

View File

@ -60,6 +60,22 @@ const void *lookup_map(struct hashmap *map, const char *key) {
return NULL;
}
const void *lookup_map_default(struct hashmap *map, const char *key, const void *default_value) {
if(key == NULL) {
return NULL;
}
int index = hash_map(key);
for(struct node *iter = map->buckets[index].head; iter != NULL; iter = iter->next) {
if(strcmp(iter->key, key) == 0) {
return iter->value;
}
}
return default_value;
}
int exists_map(struct hashmap *map, const char *key) {
return lookup_map(map, key) != NULL;
}