00001
00002
00003
00004
00005
00006
00007
00008
00009
00010
00011
00012
00013
00014
00015
00016
00017
00018
00019
00020
00021
00022
00023
00024
00025 #include <eyedb/eyedb.h>
00026 #include "eyedb/GenHashTable.h"
00027
00028 namespace eyedb {
00029
00030 GenHashTable::GenHashTable(int _pref_len, int n) : pref_len(_pref_len)
00031 {
00032 nkeys = 1;
00033
00034 n >>= 3;
00035
00036 for (;;)
00037 {
00038 if (nkeys >= n)
00039 break;
00040 nkeys <<= 1;
00041 }
00042
00043 mask = nkeys - 1;
00044
00045 lists = (LinkedList **)malloc(sizeof(LinkedList *) * nkeys);
00046 memset(lists, 0, sizeof(LinkedList *)*nkeys);
00047 }
00048
00049 struct GLink {
00050 char *name;
00051 int ind;
00052
00053 GLink(const char *_name, int _ind) : name(strdup(_name)), ind(_ind) {}
00054
00055 ~GLink() {
00056 free(name);
00057 }
00058 };
00059
00060 inline int GenHashTable::get_key(const char *tok)
00061 {
00062 tok += pref_len;
00063 int len = strlen(tok);
00064 int k = 0;
00065
00066 for (int i = 0; i < len; i++)
00067 k += *tok++;
00068
00069 return k&mask;
00070 }
00071
00072 void GenHashTable::insert(const char *name, int ind)
00073 {
00074 GLink *l = new GLink(name, ind);
00075 int k = get_key(name);
00076
00077 if (!lists[k])
00078 lists[k] = new LinkedList();
00079
00080 lists[k]->insertObjectLast(l);
00081 }
00082
00083 int GenHashTable::get(const char *name)
00084 {
00085 LinkedList *list;
00086
00087 if (list = lists[get_key(name)])
00088 {
00089 GLink *l;
00090 LinkedListCursor c(list);
00091 while (c.getNext((void *&)l))
00092 if (!strcmp(l->name, name))
00093 return l->ind;
00094 }
00095
00096 return -1;
00097 }
00098
00099 GenHashTable::~GenHashTable()
00100 {
00101 for (int i = 0; i < nkeys; i++)
00102 {
00103 LinkedList *list = lists[i];
00104 if (list)
00105 {
00106 GLink *l;
00107 LinkedListCursor c(list);
00108 while (c.getNext((void *&)l))
00109 delete l;
00110
00111 delete list;
00112 }
00113 }
00114
00115 free(lists);
00116 }
00117
00118 void
00119 GenHashTable::display(FILE *fd)
00120 {
00121 fprintf(fd, "HashTable KEYS %d\n", nkeys);
00122 for (int i = 0; i < nkeys; i++)
00123 if (lists[i])
00124 fprintf(fd, "lists[%d] = %d\n", i, lists[i]->getCount());
00125 }
00126
00127 }