Example #1
0
/* 删除字典中指定的哈希表
 *
 * Destroy an entire dictionary
 *
 * Args:
 *  d 被删除的哈希表所属的字典
 *  ht 被删除的哈希表
 *
 * Returns:
 *  DICT_OK 删除成功(这个函数不可能失败)
 */
int _dictClear(dict *d, dictht *ht)
{
    unsigned long i;

    // 遍历整个哈希表,删除所有节点链
    /* Free all the elements */
    for (i = 0; i < ht->size && ht->used > 0; i++) {
        dictEntry *he, *nextHe;

        // 碰到空节点链,跳到下一个节点链去 
        if ((he = ht->table[i]) == NULL) continue;

        // 如果节点链非空,就遍历删除所有节点
        while(he) {
            nextHe = he->next;

            dictFreeKey(d, he); // 释放 key 空间
            dictFreeVal(d, he); // 释放 value 空间
            zfree(he);          // 释放节点

            ht->used--;         // 减少计数器

            he = nextHe;
        }
    }

    // 释放哈希表节点指针数组的空间
    /* Free the table and the allocated cache structure */
    zfree(ht->table);
    // 并重置(清空)哈希表各项属性
    /* Re-initialize the table */
    _dictReset(ht);

    return DICT_OK; /* never fails */
}
Example #2
0
/* Destroy an entire dictionary */
int _dictClear(dict *d, dictht *ht)
{
#ifdef _WIN32
    size_t i;
#else
    unsigned long i;
#endif

    /* Free all the elements */
    for (i = 0; i < ht->size && ht->used > 0; i++) {
        dictEntry *he, *nextHe;

        if ((he = ht->table[i]) == NULL) continue;
        while(he) {
            nextHe = he->next;
            dictFreeKey(d, he);
            dictFreeVal(d, he);
            zfree(he);
            ht->used--;
            he = nextHe;
        }
    }
    /* Free the table and the allocated cache structure */
    zfree(ht->table);
    /* Re-initialize the table */
    _dictReset(ht);
    return DICT_OK; /* never fails */
}
Example #3
0
/* 删除指定元素的底层实现代码
 *
 * Args:
 *  d
 *  key
 *  nofree 指示是否释放被删除元素的键和值
 *
 * Returns:
 *  DICT_ERR 字典为空,删除失败
 *  DICT_OK 删除成功
 */
static int dictGenericDelete(dict *d, const void *key, int nofree)
{
    unsigned int h, idx;
    dictEntry *he, *prevHe;
    int table;

    // 字典为空,删除失败
    if (d->ht[0].size == 0)
        return DICT_ERR;

    // 平摊 rehash
    if (dictIsRehashing(d))
        _dictRehashStep(d);

    // 哈希值
    h = dictHashKey(d, key);

    // 遍历
    for (table = 0; table <= 1; table++) {
        idx = h & d->ht[table].sizemask;    // 地址索引
        he = d->ht[table].table[idx];       // 表头节点
        prevHe = NULL;
        while(he) {
            if (dictCompareKeys(d, key, he->key)) {
                /* Unlink the element from the list */
                if (prevHe)
                    prevHe->next = he->next;
                else
                    d->ht[table].table[idx] = he->next;

                if (!nofree) {
                    dictFreeKey(d, he);
                    dictFreeVal(d, he);
                }

                zfree(he);
                d->ht[table].used--;

                return DICT_OK;
            }
            // 推进指针
            prevHe = he;
            he = he->next;
        }
        if (!dictIsRehashing(d)) break;
    }

    return DICT_ERR; /* not found */
}