예제 #1
0
파일: hashmap.c 프로젝트: SerhoLiu/libakio
int hashmap_put(hashmap *map, const char *key, void *value)
{
    map_entry *entry;

    if (map == NULL || key == NULL) {
        return 0;
    }

    /* 当 use/size >= 2/3 时,扩大表 */
    if (map->use * 3 >= map->size * 2) {
        _hashmap_resize(map);
    }

    unsigned long hash = _string_hash(key);
    unsigned long index = hash;
    unsigned long perturb = hash;
    
    while (1) {
        index = index & (map->size - 1);
        entry = &(map->entrys[index]);
        
        if ((entry->key != NULL) && (!map->compare(entry->key, key))) {
            entry->value = value;
            if (entry->isdel == TRUE) {
                entry->isdel = FALSE;
            }
            return 1;
        }

        if (entry->key == NULL) {
            entry->key = key;
            entry->value = value;
            entry->isdel = FALSE;
            map->use++;
            return 1;
        }

        perturb >>= 5;
        index = (index << 2) + index + perturb + 1;
    }
}
예제 #2
0
int hashmap_add(hashmap_t map, int key, long value){
    if (!map)
        return -1;
    int hash_code = map->hs(key);
    hash_code %= map->capacity;
    if (hash_code < 0)
        hash_code += map->capacity;
    struct hashmap_pair *pair = _hashmap_list_find(map, map->lists[hash_code], key);
    if (pair == NULL) {
        pair = (struct hashmap_pair*)calloc(1, sizeof(struct hashmap_pair));
        assert(pair != NULL);
        pair->key = key;
        pair->value = value;
        list_insert_at_tail(map->lists[hash_code], pair);
        map->len++;
        if (map->len > map->capacity * map->resize_factor) {
            _hashmap_resize(map);
        }
    }
    else {
        pair->value = value;
    }
    return 0;
}