]> git.datanom.net - hashtable.git/blobdiff - hashtable.c
Add more functions
[hashtable.git] / hashtable.c
index aa301326d732e42dbfcc85e2bf6f58d409abef69..b6423634464b663ce8c57a2d48a4d175e7c3847b 100644 (file)
@@ -101,7 +101,7 @@ bool hash_table_insert(Hashtable* ht, const void* key, void* obj) {
 
 void* hash_table_lookup(Hashtable* ht, const void* key) {
        if (key == NULL || ht == NULL) return false;
-       uint64_t index = hash_table_index(ht, key);
+       uint32_t index = hash_table_index(ht, key);
 
        Node* node = ht->nodes[index];
        while (node != NULL && ht->compare(node->data, key) == false) {
@@ -109,7 +109,7 @@ void* hash_table_lookup(Hashtable* ht, const void* key) {
        }
 
        if (node == NULL) return NULL;
-       printf("find: %p -> found: %p\n", key, node->data);
+       //printf("find: %p -> found: %p\n", key, node->data);
 
        return node->data;
 }
@@ -250,6 +250,53 @@ bool hash_table_iter_next(HashtableIter* iter, void** key, void** value) {
        return false;
 }
 
+bool hash_table_contains(Hashtable* ht, const void* key) {
+       if (ht == NULL || key == NULL) return false;
+
+       if (hash_table_lookup(ht, key) == NULL)
+               return false;
+       return true;
+}
+
+uint64_t hash_table_size(Hashtable *ht) {
+       uint64_t size = 0;
+
+       if (ht == NULL) return size;
+
+       for (uint32_t i = 0; i < ht->size; i++) {
+               if (ht->nodes[i] != NULL) {
+                       Node* node = ht->nodes[i];
+                       while (node != NULL) {
+                               size++;
+                               node = node->next;
+                       }
+               }
+       }
+
+       return size;
+}
+
+bool hash_table_replace(Hashtable *ht, void* key, void* value) {
+       if (ht == NULL || key == NULL || value == NULL) return false;
+
+       uint32_t index = hash_table_index(ht, key);
+
+       Node* node = ht->nodes[index];
+       while (node != NULL && ht->compare(node->data, key) == false) {
+               node = node->next;
+       }
+
+       if (node == NULL)
+               return hash_table_insert(ht, key, value);
+       else {
+               free(node->data);
+               node->key = key;
+               node->data = value;
+       }
+
+       return true;
+}
+
 uint64_t int_hash(const void* key) {
        return *(uint64_t*) key;
 }
This page took 0.036445 seconds and 5 git commands to generate.