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
|
//========================================================================
//
// NameToCharCode.cc
//
// Copyright 2001-2002 Glyph & Cog, LLC
//
//========================================================================
#include "aconf.h"
#ifdef USE_GCC_PRAGMAS
#pragma implementation
#endif
#include <string.h>
#include "gmem.h"
#include "nametocharcode.h"
//------------------------------------------------------------------------
struct NameToCharCodeEntry {
char *name;
CharCode c;
};
//------------------------------------------------------------------------
NameToCharCode::NameToCharCode() {
int i;
size = 31;
len = 0;
tab = (NameToCharCodeEntry *)gmalloc(size * sizeof(NameToCharCodeEntry));
for (i = 0; i < size; ++i) {
tab[i].name = NULL;
}
}
NameToCharCode::~NameToCharCode() {
int i;
for (i = 0; i < size; ++i) {
if (tab[i].name) {
gfree(tab[i].name);
}
}
gfree(tab);
}
void NameToCharCode::add(char *name, CharCode c) {
NameToCharCodeEntry *oldTab;
int h, i, oldSize;
// expand the table if necessary
if (len >= size / 2) {
oldSize = size;
oldTab = tab;
size = 2*size + 1;
tab = (NameToCharCodeEntry *)gmalloc(size * sizeof(NameToCharCodeEntry));
for (h = 0; h < size; ++h) {
tab[h].name = NULL;
}
for (i = 0; i < oldSize; ++i) {
if (oldTab[i].name) {
h = hash(oldTab[i].name);
while (tab[h].name) {
if (++h == size) {
h = 0;
}
}
tab[h] = oldTab[i];
}
}
gfree(oldTab);
}
// add the new name
h = hash(name);
while (tab[h].name && strcmp(tab[h].name, name)) {
if (++h == size) {
h = 0;
}
}
if (!tab[h].name) {
tab[h].name = copyString(name);
}
tab[h].c = c;
++len;
}
CharCode NameToCharCode::lookup(char *name) {
int h;
h = hash(name);
while (tab[h].name) {
if (!strcmp(tab[h].name, name)) {
return tab[h].c;
}
if (++h == size) {
h = 0;
}
}
return 0;
}
int NameToCharCode::hash(char *name) {
char *p;
unsigned int h;
h = 0;
for (p = name; *p; ++p) {
h = 17 * h + (int)(*p & 0xff);
}
return (int)(h % size);
}
|