| 1 |
#include <QvDict.h> |
| 2 |
|
| 3 |
struct QvDictListThing { |
| 4 |
QvPList *keyList; |
| 5 |
QvPList *valueList; |
| 6 |
}; |
| 7 |
|
| 8 |
QvDict::QvDict( int entries ) |
| 9 |
{ |
| 10 |
tableSize=entries; |
| 11 |
buckets=new QvDictEntry *[tableSize]; |
| 12 |
for (int i = 0; i < tableSize; i++) |
| 13 |
buckets[i] = NULL; |
| 14 |
} |
| 15 |
|
| 16 |
QvDict::~QvDict() |
| 17 |
{ |
| 18 |
clear(); |
| 19 |
delete [] buckets; |
| 20 |
} |
| 21 |
|
| 22 |
void |
| 23 |
QvDict::clear() |
| 24 |
{ |
| 25 |
int i; |
| 26 |
QvDictEntry *entry, *nextEntry; |
| 27 |
|
| 28 |
for (i = 0; i < tableSize; i++) { |
| 29 |
|
| 30 |
for (entry = buckets[i]; entry != NULL; entry = nextEntry) { |
| 31 |
nextEntry = entry->next; |
| 32 |
delete entry; |
| 33 |
} |
| 34 |
buckets[i] = NULL; |
| 35 |
} |
| 36 |
} |
| 37 |
|
| 38 |
QvBool |
| 39 |
QvDict::enter(u_long key, void *value) |
| 40 |
{ |
| 41 |
QvDictEntry *&entry = findEntry(key); |
| 42 |
|
| 43 |
if (entry == NULL) { |
| 44 |
entry = new QvDictEntry(key, value); |
| 45 |
entry->next = NULL; |
| 46 |
return TRUE; |
| 47 |
} |
| 48 |
else { |
| 49 |
entry->value = value; |
| 50 |
return FALSE; |
| 51 |
} |
| 52 |
} |
| 53 |
|
| 54 |
QvBool |
| 55 |
QvDict::find(u_long key, void *&value) const |
| 56 |
{ |
| 57 |
QvDictEntry *&entry = findEntry(key); |
| 58 |
|
| 59 |
if (entry == NULL) { |
| 60 |
value = NULL; |
| 61 |
return FALSE; |
| 62 |
} |
| 63 |
else { |
| 64 |
value = entry->value; |
| 65 |
return TRUE; |
| 66 |
} |
| 67 |
} |
| 68 |
|
| 69 |
QvDictEntry *& |
| 70 |
QvDict::findEntry(u_long key) const |
| 71 |
{ |
| 72 |
QvDictEntry **entry; |
| 73 |
|
| 74 |
entry = &buckets[key % tableSize]; |
| 75 |
|
| 76 |
while (*entry != NULL) { |
| 77 |
if ((*entry)->key == key) |
| 78 |
break; |
| 79 |
entry = &(*entry)->next; |
| 80 |
} |
| 81 |
return *entry; |
| 82 |
} |
| 83 |
|
| 84 |
QvBool |
| 85 |
QvDict::remove(u_long key) |
| 86 |
{ |
| 87 |
QvDictEntry *&entry = findEntry(key); |
| 88 |
QvDictEntry *tmp; |
| 89 |
|
| 90 |
if (entry == NULL) |
| 91 |
return FALSE; |
| 92 |
else { |
| 93 |
tmp = entry; |
| 94 |
entry = entry->next; |
| 95 |
delete tmp; |
| 96 |
return TRUE; |
| 97 |
} |
| 98 |
} |