-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathhash.cs
145 lines (145 loc) · 4.01 KB
/
hash.cs
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
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
namespace System.Grams {
public class Hash {
public const int MAX = 15485863;
public static int GetHashCode(string key) {
int h = 0x1505;
for (int i = 0; i < key.Length; i++) {
h ^= (h << 0x5) + key[i] + (h >> 2);
}
return h & 0x7fffffff;
}
public static Hash Small() {
return new Hash(113);
}
public static Hash Medium() {
return new Hash(1733);
}
public static Hash Max() {
return new Hash(MAX);
}
private Hash(int size = MAX) {
nodes = new Gram[size];
}
uint version;
public uint Version {
get {
return version;
}
}
Gram[] nodes;
public Gram[] Nodes {
get {
return nodes;
}
}
public Gram this[string key] {
get {
return Get(key);
}
}
int count;
public int Count {
get {
return count;
}
}
int collisions;
public int Collisions {
get {
return collisions;
}
}
int depth;
public int Depth {
get {
return depth;
}
}
public void ForEach(Action<Gram> take) {
for (int i = 0; i < nodes.Length; i++) {
Gram g = nodes[i];
while (g != null) {
take(g);
g = g.Prev;
}
}
}
public System.Collections.Generic.IEnumerable<Gram> All() {
for (int i = 0; i < nodes.Length; i++) {
Gram g = nodes[i];
while (g != null) {
yield return g;
g = g.Prev;
}
}
}
public void Clear(bool gc = true) {
for (int i = 0; i < nodes.Length; i++) {
nodes[i] = null;
}
version = 0;
count = 0;
collisions = 0;
depth = 0;
if (gc) {
GC.Collect();
GC.WaitForFullGCComplete();
}
}
public Gram[] List() {
Gram[] list = new Gram[Count]; int id = 0;
for (int i = 0; i < nodes.Length; i++) {
Gram g = nodes[i];
while (g != null) {
list[id++] = g;
g = g.Prev;
}
}
return list;
}
public bool Has(string key) { return Get(key) != null; }
public Gram Get(string key) {
if (key == null || key.Length == 0) {
return null;
}
int h = GetHashCode(key);
Gram g = nodes[h % nodes.Length];
while (g != null) {
if (g.HashCode == h && Gram.Compare(g.Key, key) == 0) {
break;
}
g = g.Prev;
}
return g;
}
public Gram Put(string key) {
if (key == null || key.Length == 0) {
throw new ArgumentNullException();
}
var iter = 0;
int h = GetHashCode(key);
Gram g = nodes[h % nodes.Length];
while (g != null) {
if (g.HashCode == h && Gram.Compare(g.Key, key) == 0) {
break;
}
g = g.Prev;
iter++;
}
if (g == null) {
g = new Gram(key, h, nodes[h % nodes.Length]);
if (g.Prev != null) {
collisions++;
}
nodes[h % nodes.Length] = g;
count++;
iter++;
if (iter > depth) {
depth = iter;
}
}
version++;
return g;
}
}
}