| 47 | } |
| 48 | |
| 49 | void *ht_add( ht_t *ht, void *key, void *value ) |
| 50 | { |
| 51 | void *old = NULL; |
| 52 | hash_t hash = ( ht->key_hash ? ht->key_hash( key ) % HT_N_BUCKETS : (unsigned long)key % HT_N_BUCKETS ); |
| 53 | ht_entry_t *entry = NULL, |
| 54 | *tail = NULL, |
| 55 | *bucket = NULL; |
| 56 | |
| 57 | bucket = ht->buckets[ hash ]; |
| 58 | |
| 59 | void *v = ht->val_copy ? ht->val_copy(value) : value; |
| 60 | |
| 61 | // new bucket |
| 62 | if( bucket == NULL ) |
| 63 | { |
| 64 | ht->buckets[ hash ] = ht_make_entry( ht->key_copy ? ht->key_copy(key) : key, v ); |
| 65 | } |
| 66 | else |
| 67 | { |
| 68 | for( entry = bucket; entry; entry = entry->next ) |
| 69 | { |
| 70 | tail = entry; |
| 71 | |
| 72 | // existing key, replace old value |
| 73 | if( ht->key_cmp( key, entry->key ) == 0 ) |
| 74 | { |
| 75 | old = entry->value; |
| 76 | entry->value = v; |
| 77 | break; |
| 78 | } |
| 79 | } |
| 80 | |
| 81 | // nothing found, append new entry |
| 82 | if( entry == NULL ) |
| 83 | { |
| 84 | tail->next = ht_make_entry( ht->key_copy ? ht->key_copy(key) : key, v ); |
| 85 | } |
| 86 | } |
| 87 | |
| 88 | return old; |
| 89 | } |
| 90 | |
| 91 | void *ht_get( ht_t *ht, void *key ) |
| 92 | { |
no test coverage detected