-
Notifications
You must be signed in to change notification settings - Fork 0
/
hash.cc
122 lines (110 loc) · 2.55 KB
/
hash.cc
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
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
// -*- C++ -*-
//
// Hash class implementation.
//
// Copyright 1992-2021 Deven T. Corzine <[email protected]>
//
// SPDX-License-Identifier: MIT
//
#include "config.h"
#include "boolean.h"
#include "object.h"
#include "string2.h"
#include "hash.h"
int Hash::HashFunction(const char *key)
{
unsigned long hash = 0;
unsigned const char *ptr = (unsigned const char *) key;
int len = strlen(key);
while (len--) {
hash <<= 4;
hash += *ptr++;
hash ^= (hash & 0xf0000000) >> 24;
hash &= 0x0fffffff;
}
return hash % Size;
}
void Hash::Store(const char *key, const char *value)
{
HashEntry *entry = new HashEntry(key, value);
int hash = HashFunction(key);
entry->next = bucket[hash];
bucket[hash] = entry;
count++;
while (entry->next) {
if (entry->key == key) {
entry->next = entry->next->next;
count--;
return;
}
entry = entry->next;
}
}
void Hash::Delete(const char *key)
{
int hash = HashFunction(key);
Pointer<HashEntry> entry(bucket[hash]);
if (entry->key == key) {
bucket[hash] = entry->next;
count--;
} else {
while (entry->next) {
if (entry->key == key) {
entry->next = entry->next->next;
count--;
return;
}
entry = entry->next;
}
}
}
boolean Hash::Known(const char *key)
{
int hash = HashFunction(key);
HashEntry *entry = bucket[hash];
while (entry) {
if (entry->key == key) return true;
entry = entry->next;
}
return false;
}
String Hash::Fetch(const char *key)
{
int hash = HashFunction(key);
HashEntry *entry = bucket[hash];
while (entry) {
if (entry->key == key) return entry->value;
entry = entry->next;
}
return String();
}
HashEntry &Hash::operator [](const char *key)
{
int hash = HashFunction(key);
HashEntry *entry = bucket[hash];
while (entry) {
if (entry->key == key) return *entry;
entry = entry->next;
}
entry = new HashEntry(key, "");
entry->next = bucket[hash];
bucket[hash] = entry;
count++;
return *entry;
}
HashEntry *HashIter::operator ++() {
if (entry) {
if (entry = entry->next) return entry;
while (++bucket < Hash::Size) {
if (entry = array->bucket[bucket]) return entry;
}
bucket = 0;
} else {
bucket = 0;
while (++bucket < Hash::Size) {
if (entry = array->bucket[bucket]) return entry;
}
bucket = 0;
}
return entry;
}