Expand or create the hash table, * when malloc_failed is non-NULL, it'll avoid panic if malloc fails (in which case it'll be set to 1). * Returns DICT_OK if expand was performed, and DICT_ERR if skipped. */
| 136 | * when malloc_failed is non-NULL, it'll avoid panic if malloc fails (in which case it'll be set to 1). |
| 137 | * Returns DICT_OK if expand was performed, and DICT_ERR if skipped. */ |
| 138 | int _dictExpand(dict *d, unsigned long size, bool fShrink, int* malloc_failed) |
| 139 | { |
| 140 | if (malloc_failed) *malloc_failed = 0; |
| 141 | |
| 142 | /* the size is invalid if it is smaller than the number of |
| 143 | * elements already inside the hash table */ |
| 144 | if (dictIsRehashing(d) || (d->ht[0].used > size && !fShrink) || size == 0) |
| 145 | return DICT_ERR; |
| 146 | |
| 147 | dictht n; /* the new hash table */ |
| 148 | unsigned long realsize = _dictNextPower(size); |
| 149 | |
| 150 | /* Detect overflows */ |
| 151 | if (realsize < size || realsize * sizeof(dictEntry*) < realsize) |
| 152 | return DICT_ERR; |
| 153 | |
| 154 | /* Rehashing to the same table size is not useful. */ |
| 155 | if (realsize == d->ht[0].size) return DICT_ERR; |
| 156 | |
| 157 | /* Allocate the new hash table and initialize all pointers to NULL */ |
| 158 | n.size = realsize; |
| 159 | n.sizemask = realsize-1; |
| 160 | if (malloc_failed) { |
| 161 | n.table = (dictEntry**)ztrycalloc(realsize*sizeof(dictEntry*)); |
| 162 | *malloc_failed = n.table == NULL; |
| 163 | if (*malloc_failed) |
| 164 | return DICT_ERR; |
| 165 | } else { |
| 166 | n.table = (dictEntry**)zcalloc(realsize*sizeof(dictEntry*)); |
| 167 | } |
| 168 | |
| 169 | n.used = 0; |
| 170 | |
| 171 | /* Is this the first initialization? If so it's not really a rehashing |
| 172 | * we just set the first hash table so that it can accept keys. */ |
| 173 | if (d->ht[0].table == NULL) { |
| 174 | d->ht[0] = n; |
| 175 | return DICT_OK; |
| 176 | } |
| 177 | |
| 178 | /* Prepare a second hash table for incremental rehashing */ |
| 179 | d->ht[1] = n; |
| 180 | d->rehashidx = 0; |
| 181 | return DICT_OK; |
| 182 | } |
| 183 | |
| 184 | /* Resize the table to the minimal size that contains all the elements, |
| 185 | * but with the invariant of a USED/BUCKETS ratio near to <= 1 */ |
no test coverage detected