aboutsummaryrefslogtreecommitdiff
path: root/tool_src/QvLib/QvDict.cpp
blob: 52b3be669c7b00f89e3035b2bccda640b8a0f699 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
#include <QvDict.h>

struct QvDictListThing {
    QvPList	*keyList;
    QvPList	*valueList;
};

QvDict::QvDict( int entries )
{
    tableSize=entries;
    buckets=new QvDictEntry *[tableSize];
    for (int i = 0; i < tableSize; i++)
	buckets[i] = NULL;
}

QvDict::~QvDict()
{
    clear();
    delete [] buckets;
}

void
QvDict::clear()
{
    int		i;
    QvDictEntry	*entry, *nextEntry;

    for (i = 0; i < tableSize; i++) {

	for (entry = buckets[i]; entry != NULL; entry = nextEntry) {
	    nextEntry = entry->next;
	    delete entry;
	}
	buckets[i] = NULL;
    }
}

QvBool
QvDict::enter(u_long key, void *value)
{
    QvDictEntry		*&entry = findEntry(key);

    if (entry == NULL) {
	entry = new QvDictEntry(key, value);
	entry->next = NULL;
	return TRUE;
    }
    else {
	entry->value = value;
	return FALSE;
    }
}

QvBool
QvDict::find(u_long key, void *&value) const
{
    QvDictEntry		*&entry = findEntry(key);

    if (entry == NULL) {
	value = NULL;
	return FALSE;
    }
    else {
	value = entry->value;
	return TRUE;
    }
}

QvDictEntry *&
QvDict::findEntry(u_long key) const
{
    QvDictEntry		**entry;

    entry = &buckets[key % tableSize];

    while (*entry != NULL) {
	if ((*entry)->key == key)
	    break;
	entry = &(*entry)->next;
    }
    return *entry;
}

QvBool
QvDict::remove(u_long key)
{
    QvDictEntry		*&entry = findEntry(key);
    QvDictEntry		*tmp;

    if (entry == NULL)
	return FALSE;
    else {
	tmp = entry;
	entry = entry->next;
	delete tmp;
	return TRUE;
    }
}