static void _parcHashMap_Resize(PARCHashMap *hashMap, size_t newCapacity) { if (newCapacity < hashMap->minCapacity) { return; } PARCLinkedList **newBuckets = parcMemory_AllocateAndClear(newCapacity * sizeof(PARCLinkedList*)); for (unsigned int i = 0; i < hashMap->capacity; i++) { if (hashMap->buckets[i] != NULL) { if (!parcLinkedList_IsEmpty(hashMap->buckets[i])) { PARCIterator *elementIt = parcLinkedList_CreateIterator(hashMap->buckets[i]); while (parcIterator_HasNext(elementIt)) { _PARCHashMapEntry *entry = parcIterator_Next(elementIt); PARCHashCode keyHash = parcObject_HashCode(entry->key); int newBucket = keyHash % newCapacity; if (newBuckets[newBucket] == NULL) { newBuckets[newBucket] = parcLinkedList_Create(); } parcLinkedList_Append(newBuckets[newBucket], entry); } parcIterator_Release(&elementIt); } parcLinkedList_Release(&hashMap->buckets[i]); } } PARCLinkedList **cleanupBuckets = hashMap->buckets; hashMap->buckets = newBuckets; hashMap->capacity = newCapacity; parcMemory_Deallocate(&cleanupBuckets); }
bool parcHashMap_Remove(PARCHashMap *hashMap, const PARCObject *key) { PARCHashCode keyHash = parcObject_HashCode(key); int bucket = keyHash % hashMap->capacity; bool result = false; if (hashMap->buckets[bucket] != NULL) { PARCIterator *iterator = parcLinkedList_CreateIterator(hashMap->buckets[bucket]); while (parcIterator_HasNext(iterator)) { _PARCHashMapEntry *entry = parcIterator_Next(iterator); if (parcObject_Equals(key, entry->key)) { parcIterator_Remove(iterator); hashMap->size--; result = true; break; } } parcIterator_Release(&iterator); } // When expanded by 2 the load factor goes from .75 (3/4) to .375 (3/8), if // we compress by 2 when the load factor is .25 (1/4) the load // factor becomes .5 (1/2). double loadFactor = (double)hashMap->size/(double)hashMap->capacity; if (loadFactor <= (hashMap->minLoadFactor)) { _parcHashMap_Resize(hashMap, hashMap->capacity / 2); } return result; }
static _PARCHashMapEntry * _parcHashMap_GetEntry(const PARCHashMap *hashMap, const PARCObject *key) { PARCHashCode keyHash = parcObject_HashCode(key); int bucket = keyHash % hashMap->capacity; _PARCHashMapEntry *result = NULL; if (hashMap->buckets[bucket] != NULL) { PARCIterator *iterator = parcLinkedList_CreateIterator(hashMap->buckets[bucket]); while (parcIterator_HasNext(iterator)) { _PARCHashMapEntry *entry = parcIterator_Next(iterator); if (parcObject_Equals(key, entry->key)) { result = entry; break; } } parcIterator_Release(&iterator); } return result; }
PARCIterator * parcSortedList_CreateIterator(PARCSortedList *instance) { return parcLinkedList_CreateIterator(instance->list); }